This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This gist demonstrates - How to download data from database in excel or xls format in Ruby on Rails
# Tested with - Ruby 1.9.3, rails 3.2.1, db - postgres
class DownloadsController < ApplicationController
before_filter :define_header, :except => :index
def index
...
end
def download_choclates
@choclates = Choclate.all
respond_to do |format|
format.html { render :partial => 'download_choclates' }
end
end
private
# sets the header. You can specify the file name
# For my project I am sending the name of the file in params
# so I use
# headers['Content-Disposition'] = "attachment; filename=#{params[:name]}.xls"
def define_header
headers['Content-Type'] = "application/vnd.ms-excel"
headers['Content-Disposition'] = "attachment; filename=filename.xls"
headers['Cache-Control'] = ''
end
end
# Partial to be rendered
# _download_choclates.html.erb
<table border="1">
<tr>
<th>Id</th>
<th>Description</th>
<th>Price</th>
<th>Feedback</th>
<th>Created At</th>
<th>Updated At</th>
</tr>
<% @choclates.each do |choclate| %>
<tr>
<td><%= choclate.id %></td>
<td><%= choclate.description %></td>
<td><%= choclate.price %></td>
<td><%= choclate.feedback %></td>
<td><%= choclate.created_at %></td>
<td><%= choclate.updated_at %></td>
</tr>
<% end %>
</table>
Wednesday, June 20, 2012
Ruby on Rails - Downloading data as xls or excel without using a Gem
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment