How do I get the row index after I do an .add_row using the axlsx gem?
Asked Answered
F

1

6

I'm using the axlsx gem to create a XLSX file and have the following line in my code:

ws.add_row( "xyz" )

Is there a way to get the row index of the row I had just added? I might have to add a row later.

Forefather answered 26/9, 2016 at 17:18 Comment(5)
Please read "How to Ask" including the linked pages and "minimal reproducible example". Please add the minimum code demonstrating what you're doing. It sounds like you're incrementally adding rows but it might be easier to store the changes in an array, then process the array and add them all at once. Using an array you could easily add/change/delete prior to committing the data.Separation
Yes you can use ws.rows.last.index right after the add_row to get the index of that row. Please note that the index of a row starts at zero because ruby uses zero indexing but excel uses indexing starting at 1 so depending on how you intend to use this you may need to add +1 to the index.Rowel
Thanks engineersmnky!Forefather
@engineersmnky, shouldn't it be ws.rows.last.row_index?Lauzon
@Lauzon the method name has since changed. Two years ago it was index but now you are correct in 3.0.0. pre it should be row_indexRowel
M
10

I use these two methods for doing it:

wb = xlsx_package.workbook

wb.add_worksheet(name: 'sheet 1') do |sheet|
  sheet.add_row ['foo', 'bar']
  my_first_row = sheet.add_row ['aladdin', 'rules']
  my_second_row = sheet.add_row ['hello', 'world']

  # Method 1
  sheet.rows.index(my_first_row) # will return 1
  sheet.rows.index(my_second_row) # will return 2

  # Method 2
  my_first_row.row_index # will return 1
  my_second_row.row_index # will return 2
end

Regards

Metopic answered 6/11, 2017 at 19:38 Comment(1)
One hint: If you use the index to build excel-cooredinats, you must add 1. Example: sheet.merge_cells('A%i:D%i' % [row.row_index+1,row.row_index+1]). Ruby starts to count with 0, Excel starts with 1.Amathiste

© 2022 - 2024 — McMap. All rights reserved.