如何通过'roo'gem导入csv文件?
问题描述:
请帮忙导入csv文件。如何通过'roo'gem导入csv文件?
我安装gem'roo'和gem'iconv'。我做支架产品河畔形式导入文件:
<%= form_tag import_products_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import" %>
<% end %>
的config/routes.rb中
resources :products do
collection { post :import }
end
products_controller.rb
def import
Product.import(params[:file])
redirect_to root_url, notice: "Products imported."
end
型号/ product.rb
def self.import(file)
spreadsheet = open_spreadsheet(file)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
product = find_by_id(row["id"]) || new
product.attributes = row.to_hash.slice(*accessible_attributes)
product.save!
end
end
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
when ".csv" then Csv.new(file.path, nil, :ignore)
when ".xls" then Excel.new(file.path, nil, :ignore)
when ".xlsx" then Excelx.new(file.path, nil, :ignore)
else raise "Unknown file type: #{file.original_filename}"
end
end
我使用这个受欢迎的教程:http://railscasts.com/episodes/396-importing-csv-and-excel?autoplay=true
但之后通过形式加载CSV文件,浏览器显示如下:
NameError in ProductsController#import
uninitialized constant Csv
和控制台显示的跟随误差
message:#<ActionDispatch::Http::UploadedFile:0x000000060f36a0 @tempfile=#<Tempfile:/tmp/RackMultipart20151015-18667-14nvfde.csv>, @original_filename="products (2).csv", @content_type="text/csv", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"products (2).csv\"\r\nContent-Type: text/csv\r\n">
Completed 500 Internal Server Error in 12ms (ActiveRecord: 0.0ms)
NameError (uninitialized constant Csv):
app/models/product.rb:25:in `open_spreadsheet'
app/models/product.rb:11:in `import'
app/controllers/products_controller.rb:82:in `import'
我尝试在型号替换:
when ".csv" then Csv.new(file.path, nil, :ignore)
在
when '.csv' then Roo::Csv.new(file.path, nil, :ignore)
但问题没有解决。
在这个话题中,我问Suraj关于调整,但没有收到任何回应。
请帮助impoer CSV文件
答
变化Csv.new到CSV.new是什么做的,经过这个错误吗?
http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html#method-c-new
更新
而不是做:
def self.import(file)
spreadsheet = open_spreadsheet(file)
header = spreadsheet.row(1)
尝试这样做:
def self.import(file)
spreadsheet = Roo::Spreadsheet.open('./name_of_file')
header = spreadsheet.row(1)
你实现 的config/application.rb中 需要 'CSV' 要求'iconv' 部分? – peter
是的。我实现的是 – stackow1
Roo :: CSV.new(file.path,nil,:ignore)我得到这个可能会解决你的错误 –