Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Downloading data as xls or Excel without a Gem
# 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
def download_choclates
@choclates = Choclate.all
respond_to do |format|
format.html { render :partial => 'download_choclates' }
# 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/"
headers['Content-Disposition'] = "attachment; filename=filename.xls"
headers['Cache-Control'] = ''
# Partial to be rendered
# _download_choclates.html.erb
<table border="1">
<th>Created At</th>
<th>Updated At</th>
<% @choclates.each do |choclate| %>
<td><%= %></td>
<td><%= choclate.description %></td>
<td><%= choclate.price %></td>
<td><%= %></td>
<td><%= choclate.created_at %></td>
<td><%= choclate.updated_at %></td>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment