如何将 Roo excel sheet 中的数组放入二维数组中

How to put arrays from Roo excel sheet in two dimensional array

我正在使用 ruby 中的 roo-gem 来获取 excel sheet 单元格值。

我有一个文件 'ruby.rb' 包含:

require 'spreadsheet'
require 'roo'

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

当我 运行 ruby 'ruby.rb' 我在终端的输出是:

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

当我添加:

require 'spreadsheet'
require 'roo'

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

我得到:

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

我想要的是:

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

我该怎么做。

谢谢!

只需在 each 块外声明数组。每次区块为 运行 时,您都将其重置为 []。在这种情况下,您将仅附加到 one 数组。

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

你也可以试试

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