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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:43:35  来源:igfitidea点击:

Export data to CSV in rails

ruby-on-railscsvexport

提问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

回答by douglasr

Checkout this Stack Overflow answerfor using CSV in Ruby 1.9.x (which, as Fletch noted, includes FasterCSV but with slightly different syntax).

查看此 Stack Overflow答案以在 Ruby 1.9.x 中使用 CSV(正如 Fletch 指出的那样,包括 FasterCSV,但语法略有不同)。