rails gem或插件,用于读取和写入excel和csv文件

时间:2012-05-16 12:09:11

标签: ruby-on-rails ruby rubygems

您好我想从CSV和excel文件中读取和写入数据。任何人都可以帮助我

哪个gem或插件更适合这个。

2 个答案:

答案 0 :(得分:4)

ruby​​ 1.9.x在Stdlib中提供了一个漂亮而快速的CSV类,请参阅http://www.ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/index.html

对于电子表格,我建议http://spreadsheet.rubyforge.org/,或已经建议https://github.com/hmcgowan/roo

修改
我可以从我的代码中挖掘一个csv的例子,这可能会帮助你开始。

导入:

CSV.foreach(params[:csv][:csv_file].tempfile) do |row|
  # do something with your row ...
end

出口:

@export = CSV.generate do |csv|
  # adding header columns
  csv << [
    'Column 1', 
    'Column 2', 
    'Column 3' #, ...
  ]

  @records.each do |record|
    csv << [
      record.name,
      record.description,
      record.created_at #, ...
    ]
  end
end

# if you want to send the data directly to the client (works inside a controller action)
send_data @export, :type => 'text/csv; charset=utf-8; header=present', :disposition => 'attachment: filename=export.csv'

答案 1 :(得分:1)

你可以试试exo的宝石

吗?
 https://github.com/hmcgowan/roo

对于CSV

  https://github.com/arydjmal/to_csv