我从.xls
Link - => https://github.com/bparanj/exp使用ruby on rails下载了导入Github
的代码。
设置apache服务器后当我们选择要导入的.xlsx文件时,我收到以下错误消息
ActiveModel::UnknownAttributeError in ProductsController#import
Extracted source (around line #17):
def self.import(file)
spreadsheet = Roo::Spreadsheet.open(file.path)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
主要 product.rb 文件
require 'csv'
class Product < ApplicationRecord
validates_presence_of :price
def self.to_csv(options = {})
desired_columns = ["id", "name", "released_on", "price"]
CSV.generate(options) do |csv|
csv << desired_columns
all.each do |product|
csv << product.attributes.values_at(*desired_columns)
end
end
end
def self.import(file)
spreadsheet = Roo::Spreadsheet.open(file.path)
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
product.save!
end
end
源代码可在=&gt; https://github.com/bparanj/exp
中找到