to_spreadsheet is a gem that lets you render xls from your existing haml/erb views from Rails (>= 3.0).
Add it to your Gemfile:
gem 'to_spreadsheet'
In your controller:
# my_thingies_controller.rb
class MyThingiesController < ApplicationController
respond_to :xls, :html
def index
@my_thingies = MyThingie.all
respond_to do |format|
format.html {}
format.xlsx { render :xlsx => :index, :filename => "thingies_index" }
end
end
end
In your view partial:
# _my_thingie.haml
%table
%caption My thingies
%thead
%tr
%td ID
%td Name
%tbody
- my_thingies.each do |thingie|
%tr
%td.number{ xls_style: '{sz:14,format_code:"0000%"}' }= thingie.id
%td= thingie.name
%tfoot
%tr
%td(colspan="2") #{my_thingies.length}
See axlsx’s README for info and syntax on styles. If a TR has a style, it’s merged with any TD styles under it.
In your index.xls.haml:
# index.xls.haml
= render 'my_thingies', :my_thingies => @my_thingies
In your index.html.haml:
# index.html.haml
= link_to 'Download XLS', my_thingies_url(:format => :xls)
= render 'my_thingies', :my_thingies => @my_thingies
You can use class names on td/th for typed values. Here is the list of class to type mapping:
CSS class | Format |
---|---|
decimal or float | Decimal |
num or int | Integer |
datetime | DateTime |
date | Date |
time | Time |
Every table in the view will be converted to a separate sheet.
The sheet title will be assigned to the value of the table’s element if it exists.