Excel Export Plugin

Posted by Brian in Products, Rails (February 10th, 2006)

I’m pleased to announce the new Excel Export plugin for Ruby on Rails. This plugin allows Rails developers to easily export their data to an Excel spreadsheet.

To install via SubVersion,

ruby script/plugin install http://svn.napcsweb.com/public/excel

Simple example

Let’s assume we have two models… a Project and a Task. A Project has_many :tasks. In one of our controllers, we can create the following method which will stream a new Microsoft Excel document to the client’s browser.

  def export_project_to_excel
e = Excel::Workbook.new
@project = Project.find(:all)
@tasks = @project.tasks
e.addWorksheetFromActiveRecord "Project", "project", @project
e.addWorksheetFromActiveRecord "Tasks", "task", @tasks
headers['Content-Type'] = "application/vnd.ms-excel"

More Advanced example

This time, let’s create an array of hashes. This way, we can manipulate our data ourselves, instead of letting the plugin do the mapping. This is really useful when you have “has_many” or “belongs to” relationships and you want to export meaningful values instead of the foreign keys.

  def export_book_info_to_excel
    e = Excel::Workbook.new
    books = Book.find(:all)
    array = Array.new
    for book in books
      item = Hash.new
      item["Title"] = book.title
      item["ISBN"] = book.isbn
      item["Author"] = book.author.last_name
      item["Category"] = book.category.name
      item["Total Sales"] = book.sales.size
      array << item
    e.addWorksheetFromArrayOfHashes("Books info", array)
headers['Content-Type'] = "application/vnd.ms-excel"

2 Responses to ' Excel Export Plugin '

Subscribe to comments with RSS or TrackBack to ' Excel Export Plugin '.

  1. on August 7th, 2006 at 8:33 am

    [FOR-536] Port Fortius Excel spreadsheet generation functionality to Fortius Kiosk……

    found another resource: http://blog.napcs.com/2006/02/10/excel-plugin-10/

  2. on August 18th, 2006 at 10:53 pm

    […] Excel Export Plugin is a Rails plugin to do just that. […]

Sorry, the comment form is closed at this time.