在rails中将数据导出为CSV

bob*_*lin 21 csv export ruby-on-rails

我需要在rails appl中将导出数据作为CSV.我找到了这个插件:https://github.com/crafterm/comma.你知道一些更好的解决方案吗?

had*_*ade 37

如果使用Ruby 1.9.x,则使用CSV而不是FasterCSV并使用默认分隔符.

控制器:

respond_to do |format|
  ...           
  format.csv { render :layout => false }
end
Run Code Online (Sandbox Code Playgroud)

show.csv.erb:

<%= this_is_your_view_helper_method.html_safe %>
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

  • FasterCSV实际上成了Ruby 1.9中的标准CSV库,因此无需下载它,如果您使用的是Ruby 1.9,它就已经存在了. (10认同)