excel导入不适用于电子表格gem

时间:2012-10-25 08:30:28

标签: ruby-on-rails-3 gem

我使用Spreadsheet 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

我参考了blog

任何人都可以告诉我这段代码出了什么问题。

1 个答案:

答案 0 :(得分:3)

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

我可以使用此reference来解决此问题。

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

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
祝你好运! 丹尼斯