You may know how create a report in Ruby using the Active Record, but that's only half the battle. Reports aren't any good if the users they're intended for can't read them. This article will explain how to adjust reports so that they're more user-friendly to their intended audience. It is excerpted from chapter four of the book Practical Reporting with Ruby and Rails, written by David Berube (Apress; ISBN: 1590599330).
Creating Reports on the Desktop - Generating an Excel Spreadsheet (Page 2 of 4 )
You can generate Excel spreadsheet documents--which, incidentally, can also be opened in the OpenOffice.org spreadsheet application--using the spreadsheet-excel gem. Install this gem by using the following command:
gem install spreadsheet-excel
Tip If you want to generate Excel-compatible spreadsheets from HTML documents, see Chapter 16. The method described in that chapter is a bit of a hack, and you get less control over your output formatting, but it's extremely easy to implement. The method shown in this chapter offers greater control, such as the ability to arrange your Excel document into multiple sheets.
The following code creates a spreadsheet with "Hello, world!" in the upper-left corner:
This code is reasonably straightforward. You require the code (using the library file name spreadsheet/excel) and include the module, create a new workbook, and then add a sheet to it. Note that each spreadsheet (workbook) can have multiple worksheets, which behave similarly to tabs in a tabbed web browser, such as Mozilla Firefox or Opera. After that, you write the phrase "Hello, world!" to 0,0--the upper-left corner--and then close the workbook, which writes it to the indicated file. You can do other actions as well, such as format cells and columns, as we'll examine next.