user3231104
user3231104

Reputation: 83

Ruby/Watir : Unable to parse through xls Columns using the spreadsheet GEM

I am using the "Spreadsheet" GEM to parse through data in an xls sheet. The xls I am using has data similar to the one shown below :

I need to parse all the filled cells in one column and then move to the next column. I am using following code to achieve this :

sheet1 = book.worksheet 0
  sheet1.each do |row|
    break if row[0].nil?
    @browser.link(:href => row[1]).when_present.click
  end

How do I ensure the code parses all the cells in the first column and then moves to the next column once it finishes the first ? The code shown above is parsing only the first column.

Upvotes: 2

Views: 302

Answers (1)

Justin Ko
Justin Ko

Reputation: 46836

You could do the following:

sheet1 = book.worksheet 0
0.upto(sheet1.column_count) do |column|
  sheet1.column(column).to_a.compact.each do |cell_text|
    @browser.link(:href => cell_text).when_present.click
  end
end

Explanation:

  • sheet1.column_count tells you how many columns there are.
  • sheet1.column(column) gets a column at the specified index (0-based).
  • sheet1.column(column).to_a gets all of the values in the column. The number of rows in a column is based on the column with the most number of rows. Therefore, some of the columns are likely to have blank value at the end. The .compact is used to remove these.

Upvotes: 2

Related Questions