2012-10-25 41 views
1

我正在使用Spreadsheet gem將excel數據導入數據庫。我的觀點是: -excel導入不能使用電子表格gem

<% 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 

我有t請參考blog

任何人都可以告訴我這段代碼出了什麼問題。

回答

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 

祝你好運! Dennis

相關問題