Project

al-to_xls

0.0
No commit activity in last 3 years
No release in over 3 years
Transform an Array or Hash into a excel file using the spreadsheet gem.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Runtime

 Project Readme

to_xls gem¶ ↑

This gem transform an Array or Hash into a excel file using the spreadsheet gem.

Usage¶ ↑

@users = User.all

@users.to_xls
@users.to_xls(:headers => false)
@users.to_xls(:columns => [:name, :role])
@users.to_xls(:columns => [:name, {:company => [:name, :address]}])
@users.to_xls(:columns => [:name, {:company => [:name, :address]}], :headers => [:name, :company, :address])

When invoked on a Hash each value is output to a separate sheet named after the corresponding key. Options for each sheet can be specified using key/values in the options hash.

{ :users => @users, :posts => @posts }.to_xls

{ :users => @users, :posts => @posts }.to_xls(:users => { :columns => [:name, :role] }, :posts => { :headers => [:title, :content] })

In order to send a file from the controller, you can save it on your server first:

@users.to_xls.write '/path/to/file/users.xls'
send_file '/path/to/file/users.xls'

Alternatively you can use the method to_xls_data and send_data

send_data @users.to_xls_data, :filename => 'users.xls'

The method to_xls_data accepts the same parameters as to_xls.

Requirements¶ ↑

In config/initializers/mime_types.rb register the custom mime type.

Mime::Type.register "application/vnd.ms-excel", :xls

How to use¶ ↑

In the controller where you want to export to excel, add the format.xls line.

class UserController < ApplicationController

  def index
    @users = User.all

    respond_to do |format|
      format.html
      format.xml { render :xml => @users }
      format.xls { send_data @users.to_xls_data, :filename => 'users.xls' }
    end
  end
end

Dependencies¶ ↑

spreadsheet gem

Install¶ ↑

Include next gems in your environment.rb config file:

  config.gem 'to_xls'