Export data to Excel (xls) in Ruby on Rails

Posted by Dhaval Parikh on Apr 2, 2009 |
Subscribe

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>
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Technorati
  • StumbleUpon
  • Reddit
  • Twitter
  • Yahoo! Buzz

Tags: , , ,

7 Comments

joselo
Sep 11, 2009 at 9:01 pm

Hi, this is a cool way to export to excel, But is posible to format column?? like Text columnn or Number Column?

thanks


 
Dhaval Parikh
Sep 15, 2009 at 1:27 pm

Yes ofcourse u can do it…let me know what exactly ur looking for and I can help u out


 
Nirav
Sep 16, 2009 at 4:24 pm

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.


 
Doel
Mar 15, 2010 at 8:18 pm

Hi, can i create a new worksheet on the same .xls file using this?


 
Mark S
Apr 8, 2010 at 11:55 pm

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!


 
Mark S
Apr 9, 2010 at 12:09 am

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.


 
Lori M Olson
Jun 17, 2010 at 2:12 am

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.


 

Reply

Copyright © 2010 Dhaval Parikh All rights reserved. Theme by Laptop Geek.