Export data to Excel (xls) in Ruby on Rails
Posted by Dhaval Parikh on Apr 2, 2009 |
The code Below will help to export the data in excel in Ruby on Rails
#Controller
class UserController < ApplicationController def export headers['Content-Type'] = "application/vnd.ms-excel" headers['Content-Disposition'] = 'attachment; filename="report.xls"' headers['Cache-Control'] = '' @users = User.find(:all) end
#View
export.html.erb
<%= link_to "Export as Excel", export_person_url %>
_report.html.erb
<table border="1"> <tr> <th>Name</th> </tr> <% @users.each do |u| %> <tr> <td><%= u.name %></td> <% end %> </tr> </table>

Hi, this is a cool way to export to excel, But is posible to format column?? like Text columnn or Number Column?
thanks
Yes ofcourse u can do it…let me know what exactly ur looking for and I can help u out
This is the most simplest way opening an html in excel. This method applies to all the scripting languages(asp, php, asp.net etc). You just need to add Content Type in the head section of html.
Also, all formatting applied to html applies to the excel file.
HEADING will appear same in excel as in IE.
Hi, can i create a new worksheet on the same .xls file using this?
Dhaval, I am a Rails Newbie and do not understand the implementation of the “views”. The controller I think I got (I just cut and paste and changed where you had “user(s)” to “classmate(s)” to match my model. But I don’t get how you call the “export.html.erb” or where the partial “_report.html.erb” gets called.
Can you provide more details for implementing this solution??? TIA!
Dhaval, sorry I don’t know if my first post went thru or not as I don’t yet see it above. But I am trying to implement this solution but don’t understand how to incorporate the “views” into my existing project. I have cut-and-pasted the controller into mine, but I don’t get how to reference the “export.html.erb” and the partial “_report.html.erb” into my app. Can you provide greater details??? My app uses “classmate” in place of “user”. TIA.
Note that this form of export to Excel will not work with versions of Excel including 2007 and newer. Excel now verifies that the content of the file matches with the file extension. It will throw up a scary security exception to your users if you do it this way.