rubyexcelroo-gem

Ruby Roo Gem - read Excel xlsx sheet into Hash


I'm stuck - I need to read Excel sheet into hash, I decided to go with the ROO gem, but I can't understand documentation. Please see below:

I got excel spreadsheet:

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

I'd like to get this into array of hashes:

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

Now in roo documentation I found this:

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}, ...]

But when I try the following code, I got an error: " 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)

I know I need to define sheet somehow, but first I can't find any examples in documentation,. and second:

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

I don't mind to use any other gem that has better documentation and can work with both xls and xslx documents

Please help, Thank you in advance


Solution

  • Work on 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"}]