Archive for June 28th, 2007

How to generate CSV files in Rails

Controller code :

require 'csv'
   def export_to_csv@customers=CustomerInformation.find(:all)
      report = StringIO.new
      CSV::Writer.generate(report, ',') do |title|
         title << ['Id', 'Title', 'Job Title', 'First Name', 'Last Name']
         @customers.each do |c|
            title < 'text/csv; charset=iso-8859-1; header=present',:filename => 'report.csv', :disposition =>'attachment', :encoding => 'utf8')
         end
      end
   end

View:

    <% form_tag({ :action =>  :export_to_csv })do -%>
       <%= submit_tag "Export To CSV" -%>
    <% end -%>

4 comments June 28, 2007


Calendar

June 2007
M T W T F S S
    Jul »
 123
45678910
11121314151617
18192021222324
252627282930  

Posts by Month

Posts by Category