How to read a spreadsheet horizontally in Ruby

Viewed 58

I have the following worksheet and I need to read the situation:

  • A query that returns me only Alan PO 129877764 alan@gmail.com
  • A query that returns me only Robert QA 119875764 robertqa@gmail.com

One query bringing a record without the code, situation and tab field, and another query bringing all the rows without the code, situation and tab field.

code situation tab name job tel e-mail
8 Executed existing hydrometer Alan PO 129877764 alan@gmail.com
9 Not Executed valid reading Robert QA 119875764 robertqa@gmail.com

I can't get the values ​​of row 1. If I start the row with 1 I get them all, if I start the row with 2 I get the values ​​of row 2 together with nil. See this image:

enter image description here

sheet.each 2 do |row| 
  puts "#{row[3,3]}"
  break if row[1].nil?
 end    
  
 book.io.close
1 Answers

The each method is useful if you want to loop over every row in the sheet. If you want to access a single row directly by its index you can do so like you would an array, i.e. with []:

row1 = sheet.rows[1]
p row1
# => #<Spreadsheet::Excel::Row:...>

Once you have a Row object you can access its fields like you would an array as well, for example to get columns 3–6 (counting from 0):

p row1[3..6]
# => ["Alan", "PO", 129877764, "alan@gmail.com"]

More succinctly, to get the data you mentioned you could do this:

p sheet.rows[1][3..6]
# => ["Alan", "PO", 129877764, "alan@gmail.com"]
p sheet.rows[2][3..6]
# => ["Robert", "QA", 119875764, "robertqa@gmail.com"]
Related