无法使用CSV文件中的ruby电子表格gem写入工作簿

时间:2014-10-22 18:04:29

标签: ruby excel csv spreadsheet

我目前不熟悉Ruby,并且很难写入excel文件。

我想解析一个CSV文件,提取csv文件中的'food'列中的数据= butter,并将'food'列= butter的行放入一个新的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电子表格的众多主题,但我无法让它工作。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

完全更新 如果你试试这个怎么办:

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

指出了这一点
  

将此工作簿写入文件,IO流或写入器对象。后者会    一旦有一个Excel-Writer可用,就会更有意义。

就像我说的那样,我对这个宝石完全不熟悉,文档很糟糕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')

答案 1 :(得分:0)

尝试write_xlsx宝石。这是我简单的csvtoxlsx.rb脚本,用于将*.csv中的folder组合为single.xlsx

require "csv"
require "write_xlsx"

def csvtoxls(csv, xlsx)

    count = 0

    workbook = WriteXLSX.new(xlsx)

    Dir[csv].sort.each do | file |
        puts file
        name = File.basename(file, ".csv")
        worksheet = workbook.add_worksheet(name)
        i = 0
        CSV.foreach(file) do | row |
            worksheet.write_row(i, 0, row)
            i = i + 1
            count = count + 1
        end
    end

    workbook.close

    count
end

abort("Syntax: ruby -W0 csvtoxlsx.rb 'folder/*.csv' single.xlsx") if ARGV.length < 2

time_begin = Time.now
count = csvtoxls(ARGV[0], ARGV[1])
time_spent = Time.now - time_begin

puts "csvtoxlsx process #{ARGV[0]} with #{count} rows in #{time_spent.round(2)} seconds"