Rails to Excel

How do you go from a Rails model to a Comma Seperated Value (CSV) file that you can import to Excel? First install Ruports (Ruby Reports)
$ sudo gem install ruport
Then just extend ActiveRecord:
# in config/environment.rb
require 'ruport'

class ActiveRecord::Base
    def self.to_csv
      data_set = Ruport::DataSet.new(self.column_names)
      self.find_all.each do |row|
        data_set << row.attributes
      end
      data_set.to_csv
    end
end
Now you, too, can do magic!
>> Contact.to_csv #=> A string of CSV data

3 Responses to “Rails to Excel”

gregory Says: #
require "ruport/rails"
class ActiveRecord::Base
acts_as_reportable
def self.to_csv
to_ds.to_csv
end
end

🙂

AQ Says: #

I had no idea about acts_as_reportable. Is their any documentation on it besides RDoc?
I guess either way this proves the idiom that anything you think is elegant in ruby can be done easier and with less lines of code.

gregory Says: #

http://reporting.stonecode.org/ruport-cookbook-pre.pdf

I will actually release this document when I finish it 🙂

to_ds and formatted_table work with ActiveRecord.find, too 🙂

About

QuirkeyBlog is Aaron Quint's perspective on the ongoing adventure of Code, Life, Work and the Web.

twitter/@aq.

instagram/@quirkey.

github/quirkey.

QuirkeyBlog is proudly powered by WordPress

Categories

  • No categories