1

我被困住了 - 我需要将 Excel 表读入哈希,我决定使用 ROO gem,但我无法理解文档。请看下面:

我得到了excel电子表格:

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)

我知道我需要以某种方式定义工作表,但首先我在文档中找不到任何示例。第二:

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

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

请帮忙,提前谢谢

4

1 回答 1

4

在工作表上工作

# 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"}]
于 2018-10-16T11:45:05.680 回答