Example SQL Report with the Ruby Spreadsheet Gem

By kenglish

If you want to create a Excel reports for your users, this can be done rather easily in Ruby using the Spreadsheet Gem.

def spreadsheet_report(excel_filename, worksheet_name, 
                       column_order, result)
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name => worksheet_name
 
    rownum = 0
    for column in column_order
      sheet1.row(rownum).push column
    end
    for row in result
      rownum += 1
      for column in column_order
        sheet1.row(rownum).push row[column].nil? ? 'N/A' : row[column]
      end
    end
    book.write "#{excel_filename}.xls"
 
end

Here’s what the code would like in your rake task

column_order = ["Name", "DOB", "Rank","Hire Date", 
                "Height", "Weight" ]
 
sql =<<-END
  SELECT name AS Name,
   date_of_birth AS DOB, 
   rank AS Rank,
   hire_date Hire Date,
   height AS Height,
   weight AS  Weight
  FROM fire_fighters
  ORDER BY name
END
 
conn  = ActiveRecord::Base.connection
result    = conn.select_all(sql)
 
excel_filename = "FireFighterReport#{Time.year}" 
worksheet_name = "FireFighter Report #{Time.year}"
spreadsheet_report(excel_filename, worksheet_name, 
                   column_order, result)

Now, that’s easy!

Ruby Spreadsheet Gem Documentation



categoriaMysql, Programming commento1 Comment dataJune 17th, 2009

About... kenglish

This author published 69 posts in this site.

Share

FacebookTwitterEmailWindows LiveTechnoratiDeliciousDiggStumbleponMyspaceLikedin

Comments


Seth Ladd
June 17th, 2009

Slick! What’s the best way to serve that Excel file? Can you stream the bytes or do you have to write it to the file system first?

Leave a comment