嗨,我想从 CSV 和 excel 文件中读取和写入数据。有人可以帮我吗
哪个 gem 或插件更适合这个。
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'
你可以试试 roo gem for excel
https://github.com/hmcgowan/roo
对于 CSV
https://github.com/arydjmal/to_csv