rss
twitter
    Find out what I'm doing, Follow Me :)

How to export data to CSV In Ruby on Rails

The exporting of data to CSV in Rails is very easy just like snitching icecream from 2 year baby. You just need to install a Gem for it and a method and its done.

The procedure is written below:-

1. install the fastercsv gem :-

sudo gem install fastercsv


2. now in the controller use this gem and copy the method in the bottom of your controller and also use CSV as written:-


class ArticlesController < ApplicationController

require 'fastercsv'
......
.
.
.

def show_users
@users = User.find(:all)
stream_csv do |csv|
csv << ["Show all the users in excel"]
csv << [""]
csv << ["ID" ,"Name" ,"Address" ,"Email"]
@users.each do |u|
csv << [u.id, u.name, u.address, u.email]
end
end

end

private
def stream_csv

filename = action_name + ".csv"

#this is required if you want this to work with IE
if request.env['HTTP_USER_AGENT'] =~ /msie/i
headers['Pragma'] = 'public'
headers["Content-type"] = "text/plain"
headers['Cache-Control'] = 'no-cache, must-revalidate, post-check=0, pre-check=0'
headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
headers['Expires'] = "0"
else
headers["Content-Type"] ||= 'text/csv'
headers["Content-Disposition"] = "attachment; filename=\"#{filename}\""
end

render :text => Proc.new { |response, output|
csv = FasterCSV.new(output, :row_sep => "\r\n")
yield csv
}
end

end




and its done. You have exported data to excel sheet .

4 comments:

pixelnate said...

I saw your post and it's exactly the code that is used in the extension for RadiantCMS called the 'Subscription_Lists' extension. Radiant was upgraded to work with Rails 2.3.4 and now this part of the extension is broken.

I get an undefined method on '<<' on this part of the code 'csv << ["Show all the users in excel"]'. Any thoughts about what might be happening there? Thanks.

Moysh said...

Hi pixelNate,
I also experienced this error.
it is because faster_csv(line 1466) is calling the method '<<' on it's @io isntabce variable (wich is set to the Response object).
A workaroud will be to add the following code to your rails init procedure:

module ActionController
class Response
def <<(val)
write(val)
end
end
end

Hope this will help :-)

Unknown said...
This comment has been removed by the author.
Unknown said...

And what code should I put in the view? I tried <%= link_to "Report", :action => "show_users" %> and it didn't work.