Monday 7 September 2009

Reading Microsoft Office Excel file in ruby without installing MSOffice

There are two ways one can read Excel file in Ruby; first using Win32OLE control of excel. In that case MS office has to be installed in the machine.

Second option is to use parseexcel library. In this case MS office installation is not required. This library is available as standard gem from the ruby forge website.

Simply install the parseexcel by running following command:
gem install parseexcel

To use this library inlcude
require 'parseexcel'

And then a xls file can be loaded by simply calling

@workbook = Spreadsheet::ParseExcel.parse(file_name)

@workbook.worksheet(worksheet_no) will return intended worksheet.

And reading content of a cell is simply:
cell = worksheet.cell(row, col)
if cell != nil
contents = cell.to_s('latin1')
end
And following code spits out all cells of a worksheet:

worksheet.each do |row|
j=0
i=0
if row != nil
row.each do |cell|
if cell != nil
contents = cell.to_s('latin1')
puts "Row: #{j} Cell: #{i}> #{contents}"
end
i = i+1
end
end
end

No comments:

Post a Comment