Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Branch: master
Fetching contributors…

Cannot retrieve contributors at this time

88 lines (43 sloc) 2.29 KB


I first used the good “arydjmal/to_xls” plugin but it doesn't allow collections of multiples objects from different classes and can't export associations attributes of a class.

With to_excel gem you can export multiples collections of objects of different classes, moreover you have the possibility of exporting associations's attributes (recursively).


Basic usage

@users = User.all

With one collection. All columns are exported with default humanized attributes names for excel columns :


If you don't want excel header :

@users.to_excel headers => false

Personalized header

header = ['User Id', 'User name']
[@users].to_excel(:map => { User => [:id,:name], :headers => header)

To restrict attributes :

[@users].to_excel(:map => {User => [:age, :id, :name]}) #User is the class of users objects.

Multiples collections of different classes

Suppose you have two classes : User and Computer, with Computer has_one :user

@users = [ => 'Dupont', :age => 25)]
@computers =[ => 'Apple', :portable => true, :user => @users.first)]

You can export in the same file users and computers (in this order)

[@users, @computers].to_excel(:map => { User => [:id,:name], Computer => [:id, :brand,]})

You can export nested attributes, for example name of user of computer

In order to export the name column of the user of the computer, include [:user,:name] in the attribute list of key Computer :

[@users, @computers].to_excel(:map => { User => [:id,:name], Computer => [:id, :brand, [:user, :name]]})

You can export value of a instance method

Suppose Computer class has an instance method macintosh? You can export the column values as if it was an attribute :

[@computers].to_excel(:map => {Computer => [:id, :macintosh?]})

Controller side

class UsersController < ....

   send_data [@users, @computers].to_excel(:map => { User => [:id,:name], Computer => [:id, :brand,]})


If you want to use it with respond_to, you may have to include in initializes/mime_types :

Mime::Type.register "application/", :xls


No dependency.


sudo gem install to_excel

Copyright © 2010 Philippe Cantin, released under the MIT license.

Jump to Line
Something went wrong with that request. Please try again.