Created
June 17, 2012 03:22
-
-
Save athap/2943284 to your computer and use it in GitHub Desktop.
Downloading data as xls or Excel without a Gem
This file contains hidden or 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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment