09.01.06
ToCSV Plugin
by Chris Abad
I had a need to do a very simple CSV of a collection of ActiveRecord objects. Very similar to doing a CSV export of a MySQL table through phpMyAdmin or something like that. I really liked the cleanliness of the to_xml method, and wanted somthing similar… so I wrote a plugin for it. This plugin provides support for responding to the CSV format, as well as exporting a collection of ActiveRecord objects to CSV .
Installation
./script/plugin install -x http://svn.integralserver.com/plugins/to_csv
Usage
You can simply take a collection of ActiveRecord objects and apply the to_csv method to them:
@users = User.find(:all) @users.to_csv
Here are some different options:
# Don't put a header row into the CSV file @users.to_csv(:header => false) # Exclude the id and created_at columns @users.to_csv(:except => ['id','created_at']) # Only include the login and password columns @users.to_csv(:only => ['login','password'])
For a more RES Tful way of exporting a CSV , do something like this in your controller:
respond_to do |wants| wants.csv do render :text => @users.to_csv response.headers['Content-Type'] = 'text/csv; charset=iso-8859-1; header=present' response.headers['Content-Disposition'] = "attachment; filename=users_#{Time.now.strftime("%m-%d-%Y")}.csv" end end
Go forth
That wasn’t too difficult now was it? I wrote this plugin for a very specific purpose and it fits my needs just fine. However, feel free to make suggestions. I’m open to adding additional functionality where its both reasonable and appropriate.
Comments
Ben 5 months later
Test
Leave a Comment