The CSV text-file format is a common choice for both import and export when performing data migrations. What if you want to generate CSV files from the database records and want to export within a Rails application?
Here is the code that allow you to generate CSV file form the database records
Controller:
require 'csv'def export_to_csv
@customers=CustomerInformation.find(:all)
report = StringIO.new
CSV::Writer.generate(report, ',') do |title|
title << ['Id','Job Title','First Name','Last Name']
@customers.each do |c|
title << [c.id,c.job_title,c.first_name,c.last_name]
end
end
report.rewind
send_data(report.read,:type=>'text/csv;charset=iso-8859-1;
header=present',:filename=>'report.csv',
:disposition =>'attachment', :encoding => 'utf8')
end
View:
Your view will look like
<% form_tag({ :action => :export_to_csv })do -%>
<%= submit_tag "Export To CSV" -%>
<% end -%>
on 17 Oct, 2007 at 02:21PM
errrm, the title says: How to generate CSV files in Rails, but the code imports, not generates.
i'd love to know how to generate a cvs file.
on 17 Oct, 2007 at 09:11PM
I am sorry you are you are right, this happened because I just changed my blog from wordpress to rails. Now post is edited.
Thanks