[SOLVED] How to read a spreadsheet horizontally in Ruby


This Content is from Stack Overflow. Question asked by Samanta Nolasco


I have the following worksheet and i need read thwo situacions:
  1) Alan  PO 129877764 alan@gmail.com 
  2) Alan  PO 129877764 alan@gmail.com 
     Robert QA 119875764 robertqa@gmail.com

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


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

This Question was asked in StackOverflow by Samanta Nolasco and Answered by Jordan Running It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?