gpt4 book ai didi

ruby - 如何将 Roo Excel 工作表中的数组放入二维数组中

转载 作者:数据小太阳 更新时间:2023-10-29 09:03:39 26 4
gpt4 key购买 nike

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

我有一个“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 block 之外声明数组。每次运行该 block 时,您都将其重置为 [] 。在这种情况下,您将只追加到一个数组。

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

关于ruby - 如何将 Roo Excel 工作表中的数组放入二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29258945/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com