从CSV文件中使用ruby电子表格gem写入工作簿时遇到困难

我目前是Ruby新手,很难写一个excel文件。

我想通过一个CSV文件parsing,提取csv文件中的'food'列=黄油的数据,并将'food'列=黄油的行放入一个新的excel工作簿中。 我可以将“食物”栏中包含黄油的数据很好地写入CSV文件,但是无法将其写入工作簿(Excel格式)。

require 'rubygems' require 'csv' require 'spreadsheet' csv_fname = 'commissions.csv' options = { headers: :first_row } food_type = { 'food' => 'butter'} food_type_match = nil CSV.open(csv_fname, 'r', options) do |csv| food_type_match = csv.find_all do |row| Hash[row].select { |k,v| food_type[k] } == food_type end end #writing the 'butter' data to a CSV file #CSV.open('butter.csv', 'w') do |csv_object| # food_type_match.each do |row_array| # csv_object << row_array # end #end book = Spreadsheet::Workbook.new sheet1 = book.create_worksheet food_type_match.each do |csv| csv.each_with_index do |row, i| sheet1.row(i).replace(row) end end 

电子表格生成但是空白。 我已经通过ruby电子表格上的许多主题进行了search,但我不能得到它的工作。 任何帮助将不胜感激。

完全更新如果你尝试这样做:

 book = Spreadsheet::Workbook.new sheet1 = book.create_worksheet food_type_match.each do |csv| csv.each_with_index do |row, i| sheet1.insert_row(i,row) end end book.write('/path_to_output_location/book.xls') 

此外,输出到哪里? 我不能看到这样的道路,所以我会认为这是问题,但你说它产生? 我添加了写行,因为代码说明了这一点#write

将此工作簿写入文件,IOstream或Writer对象。 如果不仅仅有一个Excel-Writer可用,后者将更有意义。

就像我说的,我完全不熟悉这个gem和文件是可怕的axslx这将是这样的事情

 package = Axlsx::Package.new book = package.workbook book.add_worksheet do |sheet| food_type_match.each do |csv| sheet.add_row csv end end package.serialize('/path_to_output_location/book.xlsx')