2

I am using the roo-gem in ruby to get excel sheet cell values.

I have a file 'ruby.rb' with:

require 'spreadsheet'
require 'roo'

xls = Roo::Spreadsheet.open('test_work.xls')
xls.each do |row|
  p row
end

my output in the terminal when I run ruby 'ruby.rb' is:

["id", "header2", "header3", "header4"]
["val1", "val2", "val3", "val4"]
["val1", "val2", "val3", "val4"]

when I add:

require 'spreadsheet'
require 'roo'

xls = Roo::Spreadsheet.open('test_work.xls')
xls.each do |row|
  two_dimensional = []
  two_dimensional << row
  p two_dimensional
end

I get:

[["id", "header2", "header3", "header4"]]
[["val1", "val2", "val3", "val4"]]
[["val1", "val2", "val3", "val4"]]

What I want is:

[["id", "header2", "header3", "header4"],
["val1", "val2", "val3", "val4"],
["val1", "val2", "val3", "val4"]]

How would I go about doing this.

Thanks!

Mike
  • 31
  • 6
  • you realize that `xls` already has this structure before the loop right? if `xls.each { |row| p row }` comes out as you have described then `xls` is already the multidimensional array that you want. if you really wanted to add this unneeded complexity then `xls.map { |row| row}` will do this too. – engineersmnky Mar 25 '15 at 15:54

2 Answers2

2

Just declare the array outside the each block. You're resetting it to [] every time the block is run. In that case, you will only append to one array.

two_dimensional = []
xls = Roo::Spreadsheet.open('test_work.xls')
xls.each do |row|
  two_dimensional << row
  p two_dimensional
end
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
1

You can also try

require 'rubygems'
require 'roo'

class InputExcelReader
$INPUTPATH = 'C:\test_input_excel.xlsx'
excel_data_array = Array.new()

workbook = Roo::Spreadsheet.open($INPUTPATH)
worksheets = workbook.sheets
puts worksheets
puts "Found #{worksheets.count} worksheets"

worksheets.each do |worksheet|
    puts "Reading: #{worksheet}"
    num_rows = 0
    workbook.sheet(worksheet).each_row_streaming do |row|
        if(num_rows>0)
            puts "Reading the row no: #{num_rows}"
            row_cells = row.map { |cell| 
                puts "Reading cells"
                cell.value              
            }
            excel_data_array.push(row_cells)            
        end
        num_rows += 1
    end
    puts excel_data_array.to_s
end
end
javalearner_heaven
  • 483
  • 1
  • 6
  • 21