Sunday, June 28, 2009

Rails view: Export to csv

A simple and efficient export of a view to a csv file can be achieved by following these steps:

1. Install

install the following gems:

gem install fastercsv
gem install crafterm-comma --source=http://gems.github.com


2. Usage


In your controller, add:

class PostsController < ApplicationController

# GET /posts
# GET /posts.xml
# GET /posts.csv
def index
@posts= Posts.find(:all)

respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @posts}
format.csv { render :csv => @posts}
end
end

In your model, add:

# ===============
# = CSV support =
# ===============
comma do # implicitly named :default


field_to_display_1
field_to_display_2
field_to_display_3
field_to_display_4
field_to_display_5
field_to_display_6

end

In your view, add a link to the file:

the text is for example "Export to Excel" and the target of the link is /posts.csv

Rails will see the different extension and choose the appropriate render method from your controller.


3. That's it


When you click on the "Export to excel" link in the view you will get a CSV file. Depending on your browser settings, it will open in MS Excel or ask you where to save it.

from there, you can extrapolate and add params to the view.

More information

1 comments:

jhc_ said...

Nice, exactly what I was looking for, thanks !