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:
Nice, exactly what I was looking for, thanks !
Hi, i keen getting
undefined method `comma' i have installed etc and still not working. any ideas?
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!
how do you add crafterm-comma to environment.rb? I tried both
config.gem "comma"
and
config.gem "crafterm-comma"
and none worked.
@zr600 Try this;
config.gem "crafterm-comma", :lib => "comma"
This almost worked for me, but I had to do:
comma do |f|
f.field_to_display_1
f.field_to_display_2
end
can.t get it working, ActionView::MissingTemplate
Same as Jam said... ActionView::MissingTemplate error.
Post a Comment