Ruby Roo Gem - 将 Excel xlsx sheet 读入 Hash

Ruby Roo Gem - read Excel xlsx sheet into Hash

我卡住了 - 我需要将 Excel sheet 读入散列,我决定使用 ROO gem,但我无法理解文档。请看下面:

我得到了excel传播sheet:

Fruits   Qty   Location
apples   5     Kitchen
pears    10    Bag
plums    15    Backpack

我想将其放入哈希数组中:

myhash =[
{Fruits: "apples", Qty: 5, Location: "Kitchen"},
{Fruits: "pears", Qty: 10, Location: "Bag"},
{Fruits: "plums", Qty: 15, Location: "Backpack"}
}

现在在 roo 文档中我发现了这个:

Use sheet.parse to return an array of rows. Column names can be a String or a Regexp.

sheet.parse(id: /UPC|SKU/, qty: /ATS*\sATP\s*QTY\z/)
# => [{:id => 727880013358, :qty => 12}, ...]

但是当我尝试下面的代码时,我得到了一个错误:“undefined local variable or method `sheet' for main:Object (NameError)”

require 'roo'
workbook = Roo::Spreadsheet.open './fruits.xlsx'
workbook.default_sheet = workbook.sheets.first
sheet.parse(Fruits: "Fruits", Qty: "Qty", Location:"Location", clean:true)

我知道我需要以某种方式定义 sheet,但首先我无法在文档中找到任何示例。第二个:

Almost all methods have an optional argument sheet. If this parameter is omitted, the default_sheet will be used.

我不介意使用任何其他具有更好文档并且可以同时使用 xls 和 xslx 文档的gem

请帮忙, 提前谢谢你

继续sheet

# Open the workbook
wb = Roo::Spreadsheet.open '/Users/ankur/Desktop/wb.xlsx'
# Get first sheet
sheet = wb.sheet(0)
# Call #parse on that
sheet.parse(Fruits: "Fruits", Qty: "Qty", Location:"Location", clean:true)
#=> [{:Fruits=>"apples", :Qty=>5, :Location=>"Kitchen"}, {:Fruits=>"pearls", :Qty=>10, :Location=>"Bag"}, {:Fruits=>"plums", :Qty=>15, :Location=>"Bagpack"}]

在 Rails

上使用多个 XLSX 电子表格单一排序导出数据
ods.sheets

out_put = ['Info', 'Sheet 2', 'Sheet 3']

ods.each do |sheet|

ods.default_sheet = sheet

 ods.each_with_index do |name, sheet|

   p sheet.row(1)
 end 
end