4

I am generating .xlsx files using axlsx_rails gem based on axlsx. I am receiving rows as array and drawing them like this:

# Workbook, sheet and styles creations left... 
data["config"].each do |item|
    sheet.add_row item.each_with_index.map{|row, index| row["value"]}, :style => row_style       
end

Then I need to insert a new row between for example 2nd and 3rd rows. I wonder how I can achieve this?

Gustavo Mori
  • 8,319
  • 3
  • 38
  • 52
vvahans
  • 1,849
  • 21
  • 29

2 Answers2

5

It seems there ought to be a better way to do this, but you can add a row, delete it, and insert it elsewhere:

sheet.add_row %w{this row is inserted}
sheet.rows.insert 2, sheet.rows.delete(sheet.rows.length-1)

sheet.rows.insert requires an Axlsx::Row object. You can create one separately, but the initializer requires a worksheet parameter, and it adds the row to the worksheet implicitly:

new_row = Axlsx::Row.new sheet, %w{this row is inserted}
sheet.rows.last # => returns new_row
# so we still have to do the same thing
sheet.rows.insert 2, sheet.rows.delete(sheet.rows.length-1)

You may as well use the first. YMMV with complicated worksheets.

More docs here.

noel
  • 2,095
  • 14
  • 14
1

sheet.rows.insert [index], sheet.rows.delete(sheet.rows.last) #index is the row that you want to insert ont

ebram khalil
  • 8,252
  • 7
  • 42
  • 60