6

I need to read and write (-> transform) Excel files on a Linux server, which of course does not have Excel installed. For Python there exists http://www.python-excel.org/. Is there something similar for Ruby? Processing of the latest Office format is probably not required. Just old xls files should be enough.

Achim
  • 15,415
  • 15
  • 80
  • 144
  • possible duplicate of [Ruby: Parse Excel 95-2003 files?](http://stackoverflow.com/questions/1579635/ruby-parse-excel-95-2003-files) – mikej Feb 07 '11 at 10:55

1 Answers1

11

I agree with Gonzih, and I use roo fairly regularly. It allows me to read, write, and write using a template file. The project is fairly well documented on their site.

I always use something like:

input = Excel.new(path)
output = Array.new
input.default_sheet = input.sheets[sheet]
start.upto(input.last_row) do |row|
  output << input.row(row)
end

p output
=> a nested array representing the spreadsheat.

p output[0]
=> [row1_column_a, row1_column_b...]

to read a spreadsheet. note that the roo gem requires you to use Excelx.new instead of Excel.new if your file is a .xlsx.

to write you can:

book = Spreadsheet::Workbook.new
write_sheet = book.create_worksheet
row_num = 0
input.each do |row|
  write_sheet.row(row_num).replace row
  row_num +=1
end
book.write "/path/to/save/to.xls"

where input is an array structured just like output was

rm-rf
  • 1,313
  • 1
  • 15
  • 24