Ruby Roo Gem-将Excel xlsx表读入Hash

时间:2018-10-16 09:55:45

标签: ruby excel roo-gem

我被困住了-我需要将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}, ...]

但是当我尝试以下代码时,出现错误:“ main:Object(NameError)的未定义局部变量或方法`sheet'”

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

请帮助, 预先谢谢你

1 个答案:

答案 0 :(得分:0)

工作表上

# 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"}]