rubyrubyxl

rubyXL iterate through specific column from xslx


i am new to ruby and rubyXL and have (maybe) a simple question. I have an Excel File which i parse with RubyXL.

then i want to save all values from column B into an array. And i don't know how to get this done. Maybe someone can help me?

@workbook = RubyXL::Parser.parse(path)
.
.
.
@excelColumnB = Array.new
#only iterate column B (1)    
@workbook.worksheets[0].each[1] { |column|
  column.cells.each { |cell|
    val = cell && cell.value
    excelColumnB.push(val)
    puts val
  }
}
return excelColumnB

i know that the example is wrong. I tried many things.


Solution

  • The each[1] is your main problem. You can't index an iterator that way, it's syntactically incorrect. The block variable contains a row, not a column.

    Try this:

    @workbook.worksheets[0].each { |row|
      val = row[1].value
      @excelColumnB << val
      puts val
    }
    

    But I recommend a more succinct way to create your array:

    @col_b = workbook.worksheets[0].collect {|row| row[1].value}