简体   繁体   中英

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

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

Exporting data with multiple XLSX spreadsheets single sort on Rails

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM