我在关注这个 railscast视频,但我很难将我的数据导出到 excel(或 CSV)。
我在前端显示的一些数据中使用 will_paginate,如下所示:
sql = "select complex..."
@data = paginate_by_sql([sql],
:per_page => params[:rows],
:page => params[:page])
所以,照原样,我认为这应该可行:
respond_to do |format|
format.html
format.xls { send_data @data.to_csv(:col_sep => "\t") }
end
它实际上正确地下载了一个 xls 文件,内容全乱了,它每列显示一行,内容如下所示:
#<Product:0x00000004c83328>
PS -> 使用 rails 最新版本
::编辑:: 每列一行,我的意思是仅在我的 Excel 工作表和这一行上有一行
A 列 = #<Product:0x00000004c83328>
B 列 = #<Product:0x00000004c83329>
C 列 = #<Product:0x00000004c8333>
(30 列)
更新
做了一个简单的测试练习,最后所有的列都只在一列中:
csv_string = CSV.generate(:col_sep => ",") do |csv|
csv << ["row", "of", "CSV", "data"]
csv << ["another", "row"]
end
respond_to do |format|
format.html
format.csv { send_data csv_string,
:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment; filename=records.csv" }
end
(:col_sep => ",")
我想是可选的。
结果:
最佳答案
您几乎完成了,您只需要映射每个 Product
模型对象,因为您正在对它们调用 to_s
,这是未定义的。
因此,如果您只想要一个标题列表,您可以覆盖模型 (app/models/product.rb
) 上的 to_s
方法来执行如下操作:
def to_s
title
end
或者,要生成逗号分隔的列表,您可以这样做
def to_s
[title, price, availability].join(',')
end
https://stackoverflow.com/questions/17049573/