从 Excel 文件读取和保存数据 - 如何解析文件 - #<Array:0x1579b6a8> 的未定义方法 'to_f'



我在RailsCast上学习了如何从Excel导入数据的教程。

我想阅读我的excel文件,并告诉他哪些信息读取和保存指示行拿起。我在model(。rb)文件中这样写:

def self.to_csv(options = {})
  CSV.generate(options) do |csv|
    csv<<column_names
    all.each do |repartition|
      csv<<repartition.attributes.values_at(*column_names)
    end
  end
end
def self.import(file)
  #Ouverture du fichier
  spreadsheet = open_spreadsheet(file)
  #Lecture du fichier, lignes par lignes, en aveugle
  (1..spreadsheet.last_row).each do |i|
    @repartition=Repartition.new
  @repartition.fond_repartition_id=spreadsheet.row(4)
    @repartition.date_repartition=spreadsheet.row(3)
    @repartition.AssetAllocCash=spreadsheet.row(5)
    @repartition.AssetAllocEquity=spreadsheet.row(6)
    @repartition.AssetAllocBond=spreadsheet.row(7)
    @repartition.AssetAllocOther=spreadsheet.row(8)

#Sauvegarde de la ligne qui vient d'être lu
    repartition.save!
  #Depart prochaine ligne ou fin
  end
end

def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::Csv.new(file.path, options={})
  when ".xls" then Roo::Excel.new(file.path, options={})
  when ".xlsx" then Roo::Excelx.new(file.path, options={})
  else raise "Unknown file type: #{file.original_filename}"
  end
end

我在控制器中写了这段代码

def import
  Repartition.import(params[:file])
  redirect_to upload_path, notice: "Répartition effectuée avec succès"
end

我有错误信息:

NoMethodError in RepartitionsController#import
undefined method `to_f' for #<Array:0x1579b6a8>

我所有的数据都是浮动属性。为什么会出现这个错误?

我就是这么做的。为了解析我的excel文件,我执行了以下步骤。

我正在使用宝石房。在我的GemFile中有这样一行:

gem 'roo', '~>2.1.0'

然后我运行命令行:

bundle install

In my controller:

  def import
    Repartition.import(params[:file])
    redirect_to resultat_path, notice: "Répartition effectuée avec succès"
  end

然后在我的模型中:

  def self.open_file(file)
  	case File.extname(file.original_filename)
  	when ".csv" then Roo::Csv.new(file.path, options={})
  	when ".xls" then Roo::Excel.new(file.path, options={})
  	when ".xlsx" then Roo::Excelx.new(file.path, options={})
  	else raise "Unknown file type: #{file.original_filename}"
  	end
  end
  def self.import(file_path)
  	#Ouverture du fichier
  	file = open_file(file_path)
  	#Lecture du fichier
  	(1..file.last_row).each do |i|
  		row = file.row(i)
  		@repartition=Repartition.new
		@repartition.fond_repartition_id=row[4]
	    @repartition.date_repartition=row[3]
  		@repartition.save!
  		end
  end

然后在我想要交互的网页上,我这样写:

<%= form_tag import_repartitions_path, multipart: true do %>
	<%= file_field_tag :file %>
	<%= submit_tag "Importer", class: "btn btn-primary" %>
<% end %>

错误是我忘记写(首先)

row = file.row(i)

那么我想读的名字就错了。在我的数据库模式中,我用属性"date_repartitio"迁移了我的表,而不是"date_repartition"和错误to_f是说,而不是读取"date_repartition",这是一个浮点数(不是我知道的日期时间),它正在读取"date_repartitio",这实际上是不存在的。

但是,我还没有代码来避免每次运行import方法时创建一个实体。

最新更新