[英]Error while importing .xlsx file using roo gem in ruby on rails
I got the following error: 我收到以下错误:
NoMethodError in ClientsController#table
undefined method `phone' for nil:NilClass
This occurs when I try to import .xlsx,.xls or .csv files into ruby on rails application. 当我尝试将.xlsx,.xls或.csv文件导入Rails应用程序中的ruby时,会发生这种情况。
Model code is given below: 型号代码如下:
attr_accessible :name, :kind, :address_attributes, :emails_attributes, :phones_attributes, :attachments_attributes
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]
client = find_by_id(row["id"]) || new
client.attributes = row.to_hash.slice(*accessible_attributes)
client.save!
end
end
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
when '.csv' then Roo::Csv.new(file.path)
when '.xls' then Roo::Excel.new(file.path)
when '.xlsx' then Roo::Excelx.new(file.path)
else
raise "Unknown file type: #{file.original_filename}"
end
end
Controller code is given below: 控制器代码如下:
def import
Client.import(params[:file])
redirect_to clients_path, notice: "Clients imported."
end
apps/Services/config/application.rb file include the following code: apps / Services / config / application.rb文件包含以下代码:
require 'csv'
require 'iconv'
gem file include the following: gem文件包括以下内容:
gem 'roo', '~> 2.1.0'
gem "iconv", "~> 1.0.3"
gem 'roo-xls'
I think that you should use this syntax for Roo gem: 我认为您应该对Roo gem使用以下语法:
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
when ".csv" then Roo::CSV.new(file.path, nil, :ignore)
when ".xls" then Roo::Excel.new(file.path, nil, :ignore)
when ".xlsx" then Roo::Excelx.new(file.path, nil, :ignore)
else
raise "Unknown file type: #{file.original_filename}"
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.