mysql - 通过 Rails 将 SQL 文件或 Excel 文件中的数据导入数据库

标签 mysql sql ruby-on-rails database import-from-excel

<分区>

我有来自 Excel 电子表格的数据,我想通过 Rails 将其导入数据库。我正在使用 Rails 3.2.3 和 Ruby 1.9.2。

数据是用户名和密码,文件名为member.xlsx

<%= form_for @member do |f| %>
    <%= f.text_field :import,
        :maxlength=>'50',
        :style=>'width: 250px;',
        :placeholder => 'browse file *.sql or *.xlsx' %>
    <%= f.submit  %><% end %>

我的 table :

create_table :members do |t|
  t.string :username
  t.string :password_hash
  t.string :password_salt

已解决

解决方案

我使用电子表格 gem 来解析 Excel 文件,使用 CarrierWave gem 来上传 Excel 文件。因为我正在为用户使用设计模型,所以这里是导入文件的 Controller 的样子

def import
    if params[:excel_file].nil?
      redirect_to user_new_import_path, :flash => { :error => 'You have not selected a file'}
    else
      test_file = params[:excel_file]
      file = ExcelUploader.new
      file.store!(test_file)
      book = Spreadsheet.open "#{file.store_path}"
      sheet1 = book.worksheet 0
      sheet1.each 1 do |row|
        name = row[0]
        email = row[2]
        generated_password = Devise.friendly_token.first(6) 
        temp_password = generated_password
        @user = User.create(:name => name, :email => email, :password => temp_password, :password_confirmation => temp_password)     
         UserMailer.password_send(@user).deliver
      end
      if @user.save
        redirect_to users_path, :notice => "success"
      else
        redirect_to new_import_user_path, :flash => { :error => 'error. try again' }
      end
    end
end

最佳答案

导入一个 sql 文件是一个可怕的想法,因为 sql 可以对你的数据库做任何事情。

导入 Excel 文件正常。有Excel gem 可以读取数据。 roo gem 可用于 xlsx 格式,但我还没有测试过。我告诉用户使用 Excel 以 xls 格式存储文件,然后他们上传。

更好的方法(从应用程序开发人员的角度来看)是导入 csv 文件。 csv 的缺点是该文件只包含一个表。

另一方面,Excel 导入的一个问题是人们可以为您提供多个选项卡文件、公式而不是单元格中的值等。因此请务必包含大量错误检查。

常见问题:当您的代码需要 Date 对象时,人们却在 Excel 工作表中将日期作为字符串输入。或者人们输入的数字作为字符串。您的代码应该测试并处理这些问题。

参见 http://rubygems.org/gems/roo

回复:“给我一些代码”—— StackOverflow 不是这样工作的。希望以上内容对您的旅程有所帮助。

关于mysql - 通过 Rails 将 SQL 文件或 Excel 文件中的数据导入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10556458/

相关文章:

MYSQL 5.7 表 3 字段 DATETIME '0000-00-00 00:00:00' 如何将新结构更改为 DEFAULT NULL

mysql - 根据INT列值更新SQL数据库重复字段

ruby-on-rails - Rails 未定义方法 `map' for nil :NilClass - form collection_select

mysql - Apache mahout 评估速度极慢 - 使用修改后的 NearestNUserNeighborhoud

php - 使用 php 和 Codeigniter 备份 SQL 表

sql - 如何将值插入到具有外键关系的两个表中?

ruby-on-rails - Sidekiq和Twilio闯入 worker “wrong number of arguments (1 for 2)”

ruby-on-rails - 如何更改 Controller /:id to controller/:name in Rails 3? 的 Rails 路由

mysql - 如何在mysql和Visual Basic中设置变量组?

mysql - 在 Mysql 过程中传递多个日期