如何通过' roo'导入csv文件宝石?

时间:2015-10-15 18:35:19

标签: ruby-on-rails ruby csv import

请帮助导入csv文件。

我安装gem' roo'和宝石&icon;'我为进口文件制作脚手架产品nad表格:

<%= form_tag import_products_path, multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import" %>
<% end %>

配置/ 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)

on

when '.csv' then Roo::Csv.new(file.path, nil, :ignore) 

但问题没有解决。

在这个主题中,我向Suraj询问了有关调整的问题,但没有得到回复。

请帮助impoer csv-file

2 个答案:

答案 0 :(得分:0)

仅添加要求'csv'

`when '.csv' then Roo::Csv.new(file.path, nil, :ignore)`

但是我使用另一种方法:

`when ".csv" then CSV.parse(File.read(file.path), :headers => true)`

并阅读使用此

`spreadsheet.each do |row|
   line = []
   row.to_a.each_with_index do |val|
     line.push(val[1].to_s)
   end
   rows.push(line)
end`

答案 1 :(得分:-1)

将Csv.new更改为CSV.new这样做后会出现什么错误?

http://localhost:8888/api/HostEntry

更新

而不是:

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)