Thursday, February 3, 2011

Exporting as CSV file in RAILS.

I have used Fastercsv gem to generate csv data and used send_data method..

def create_csv
@customers = Customer.all
csv_string = FasterCSV.generate do |csv|
csv << ["First Name", "Last Name", "Email", "Home Phone", "Alternate Phone", "Address Line1", "Address Line2", "City", "State", "Zip"]
@customers.each do |customer|
csv << [customer.firstname, customer.lastname, customer.email, customer.home_phone_number, customer.cell_phone_number, customer.address_line1, customer.address_line2, customer.city, customer.state, customer.zip]
end
end
send_data csv_string, :filename => "customers.csv" , :type=>"text/csv"
end

No comments: