Ruby-on-rails 在 Rails 中将数据导出为 CSV
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4302050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Export data to CSV in rails
提问by boblin
I need export data as CSV in rails appl. I found this plugin: https://github.com/crafterm/comma. Do you know about some better solution?
我需要在 rails appl 中将数据导出为 CSV。我找到了这个插件:https: //github.com/crafterm/comma。你知道一些更好的解决方案吗?
回答by hade
If using Ruby 1.9.x, then use CSV rather than FasterCSV and stick with the default delimiters.
如果使用 Ruby 1.9.x,则使用 CSV 而不是 FasterCSV 并坚持使用默认分隔符。
Controller:
控制器:
respond_to do |format|
...
format.csv { render :layout => false }
end
show.csv.erb:
show.csv.erb:
<%= this_is_your_view_helper_method.html_safe %>
controller_helper.rb:
controller_helper.rb:
require 'csv'
def this_is_your_view_helper_method
CSV.generate do |csv|
Product.find(:all).each do |product|
csv << ... add stuff here ...
end
end
end

