Export to Excel in Ruby on Rails
Below code 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>

















Export to excel facility implemented does not work in mozilla and chrome(The data is displayed in the web page itself). Whereas in IE the Run | Save | Cancel box appears and displays correctly in Excel sheet.
Any replies
hi
when i m using this code, it shows an error of
“undefined local variable or method `export_person_url’ for ” can u please suggest a solution.
This code works well in mozilla and chrome. I tested it in both.
Note this code will not work for versions of Excel 2007 and newer. Excel now checks to see if the content type matches the file extension, and will throw up a scary security exception to your users.
how to add a sheet?
Hi wohaizai007,
I did not try this one so no idea abt that.
Thanks
Brijesh Shah
I am new to rails. Is this code generic or required some tweaking based on the applications. Because directly cut-paste is not working in case of my application.
Thanks,
Jnanesh
Hi,
I Export some data from mysql to excel.Some excel document is export correctly. However some of excel document has character problem.Datas type is Turkish.
Character problem Ex:
“Yep Yeni Rakı Bunlar ” and it should be “Yep Yeni Rakı Bunlar ”
Do you have any idea about the problem?
Thx
when i m using this code, it shows an error of
“undefined local variable or method `export_person_url’ for ” can u please suggest a solution.
Hi
You need to define url in routes.rb set url according to your controller and action.
Thanks
Brijesh Shah
Hi Brijesh
I m new to rails.Im trying export the data in the table name abc to the excel sheet.My controller is abcs_controller.rb. Further shd i rename it as “export_abc_url”.shd i add post “/export_abc” to the routes. Kindly do help
Hi Brijesh
I m new to rails.Im trying export the data in the table name abc to the excel sheet.My controller is abcs_controller.rb. Further shd i rename it as “export_abc_url”.shd i add post “/export_abc” to the routes. i m using rail3. i ve included in my routes. “match “export” => ‘abcs#export’
resources :abcs” Kindly do help
Hi
set route as below:
or u can add in abcs resources if u had defined
like
Hi Brijesh.
Thanks. I could overcome the error with your suggestion. i can open the export.html page successfully. when I click the link, it stays on the same page. where does the report.xls get generated? I m using IE7.