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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Evilmuffin
  • 214
  • 4
  • 14
  • Please read "[ask]" including the linked pages and "[mcve]". 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. – the Tin Man Sep 26 '16 at 17:38
  • 4
    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. – engineersmnky Sep 26 '16 at 17:53
  • Thanks engineersmnky! – Evilmuffin Sep 26 '16 at 18:25
  • @engineersmnky, shouldn't it be `ws.rows.last.row_index`? – Giuseppe Aug 25 '18 at 05:59
  • @Giuseppe 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_index` – engineersmnky Aug 25 '18 at 14:20

1 Answers1

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

mld.oscar
  • 438
  • 6
  • 6
  • 4
    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. – knut Apr 16 '21 at 12:59