← Back to home

to_csv plugin: Better Excel Compatibility

June 10, 2008

A couple of days ago I blogged about how to export to MS Excel. I took an example from a client’s app, in which they are the final-users, and I know for sure they only use Excel 2003.

But if your app needs some sort of export feature, and you don’t know how the users are going to use the data, I would go with CSV. Why? As far as I know every spreadsheet app can open it, including Numbers and Office 2000 (which don’t handle XML-based xls files), plus they might use it with report tools unrelated to excel. And as a bonus it is much easier to use.

The Solution

Last night I wrote a very simple plugin called to_csv that gives you the ability to call to_csv to a collection of activerecords. The builder options are the same as to_json / to_xml, except for the :include.


@users = User.all

# defaults are export header and all fields except id, and timestamps

@users.to_csv(:only => [:last_name, :role])
@users.to_csv(:timestamps => true, :id => true, :header => false)
@users.to_csv(:except => [:last_name, :role])
@users.to_csv(:except => :role, :methods => [:name, :admin?])

Real life example

In the controller where you want to export to csv, add the format.csv line (as of rails 2.1 it is not necessary to register the csv myme_type)

class UserController < ApplicationController
  def index
    @users = User.all
    respond_to do |format|
      format.xml { render :xml => @users }
      format.csv { send_data @users.to_csv }

That’s it. No myme_type to register, no views to create, just install the plugin, and add format.csv { send_data collection.to_csv } to the controller’s respond_to block that you want to give export capabilities.


./script/plugin install git://github.com/arydjmal/to_csv.git


I got ideas and influence from Mike Clarks recipe#35 in Rails Recipes book, some anonymous pastie, and whoever wrote to_xml/to_json builders.


Does not work on a single activerecord, ie, User.first.to_csv. Cannot style output like xls.


I modified the plugin so now it uses the fastercsv library instead of the old CSV library. SO if you don’t have the gem installed type:

sudo gem install fastercsv

← Back to home