我有来自 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 %>
我的桌子:
create_table :members do |t|
t.string :username
t.string :password_hash
t.string :password_salt
解决了
解决方案
我正在使用电子表格 gem 来解析 Excel 文件,并使用 CarrierWave gem 来上传 Excel 文件。因为我正在为用户使用设计模型,所以这是用于导入文件的控制器的样子
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