1

我正在使用电子表格 gem 将 excel 数据导入数据库。我的观点是:-

<% form_for :dump, :url=>{:action=>"excel_import"}, :html => { :multipart => true } do |f| -%>
 Select an Excel File :
 <%= f.file_field :excel_file -%>
 <%= submit_tag 'Submit' -%>
<% end -%>

我的控制器是:-

require 'spreadsheet'

def excel_import
 Spreadsheet.client_encoding = 'UTF-8'
 book = Spreadsheet.open params[:dump][:excel_file]
 sheet1 = book.worksheet 0
 sheet1.each do |row|
 TimeSheet.new(:ac_no => row[0]).save
 end
end

参数:-

 {"utf8"=>"✓", "authenticity_token"=>"vhyy1pzYJpM9hCdgP5AiFC1Pv0UtbpLSzStZDWiZzs8=", "dump"=>{"excel_file"=>#<ActionDispatch::Http::UploadedFile:0x9a8f5f8 @original_filename="SwipeData_DeliveryTeam_Sep12.xls", @content_type="application/vnd.ms-excel", @headers="Content-Disposition: form-data; name=\"dump[excel_file]\"; filename=\"SwipeData_DeliveryTeam_Sep12.xls\"\r\nContent-Type: application/vnd.ms-excel\r\n", @tempfile=#<File:/tmp/RackMultipart20121025-4534-n7pw14>>}, "commit"=>"Submit"}

当我尝试上传 excel 文件并单击提交按钮时,出现错误:-

 can't convert ActionDispatch::Http::UploadedFile into String

我从博客中获取了参考

谁能告诉我这段代码出了什么问题。

4

1 回答 1

3

使用您提到的相同博客参考时,我遇到了完全相同的问题。

我能够使用此参考解决它。

这是你的方法修改为我的方法,我的现在正在工作!

require 'spreadsheet'
require 'fileutils'
require 'iconv'

def excel_import

 tmp = params[:dump][:excel_file].tempfile

 Spreadsheet.client_encoding = 'UTF-8'

 book = Spreadsheet.open tmp.path

 sheet1 = book.worksheet 0
 sheet1.each do |row|
 TimeSheet.new(:ac_no => row[0]).save
 end
end

FileUtils.rm tmp.path

祝你好运!丹尼斯

于 2012-10-29T15:13:53.670 回答