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

8 comments:

Unknown said...

Nice, exactly what I was looking for, thanks !

Unknown said...

Hi, i keen getting
undefined method `comma' i have installed etc and still not working. any ideas?

Unknown said...

I was having the same problem as jcooper above, but I resolved it by adding "require 'comma'" to the model.

Thanks for the article, very helpful!

Anonymous said...

how do you add crafterm-comma to environment.rb? I tried both

config.gem "comma"

and

config.gem "crafterm-comma"

and none worked.

Unknown said...

@zr600 Try this;

config.gem "crafterm-comma", :lib => "comma"

Neil said...

This almost worked for me, but I had to do:

comma do |f|
f.field_to_display_1
f.field_to_display_2
end

Unknown said...

can.t get it working, ActionView::MissingTemplate

Threadhead said...

Same as Jam said... ActionView::MissingTemplate error.