/to_spreadsheet

Render XLS from Rails using existing views

Primary LanguageRubyOtherNOASSERTION

to_spreadsheet is a gem that lets you render xls from your existing haml/erb views from Rails (>= 3.0).

Installation

Add it to your Gemfile:

gem 'to_spreadsheet'

Usage

In your controller:

class MyThingiesController < ApplicationController
  respond_to :xls, :html

  def index
    @my_thingies = MyThingie.all
    respond_with(@my_thingies)
  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= thingie.id
        %td= thingie.name
  %tfoot
    %tr
      %td(colspan="2") #{my_thingies.length}

In your index.xls.haml:

= render 'my_thingies', :my_thingies => @my_thingies

In your index.html.haml:

= link_to 'Download XLS', my_thingies_url(:format => :xls)
= render 'my_thingies', :my_thingies => @my_thingies

Formatting

You can use class names on td/th for typed values. Here is the list of class to type mapping:

| /float/    | Float format      |
| /num|int/  | Number format     |
| /datetime/ | DateTime format   |
| /date/     | Date format       |
| /time/     | Time format       |

Worksheets

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 <caption> element if it exists.