Exporting to CSV in Rails

Posted by topher
on Thursday, April 26

To export data to CSV, I use CSV::Writer.

1
2
3
4
5
6
7
8
9
10
11
12
13
def report
  CSV::Writer.generate(output="") do |csv|
    csv << %w(Name Price)
    @items.each do |item|
       csv << [item.name, item.price]
    end
  end

  send_data(output,
    :type => "text/csv",
    :filename => 'report.csv')
  end
end

You can also checkout FasterCSV.