ruby-on-railsrubyspreadsheetaxlsx

Rails axlsx_rails gem. Insert new row between existing rows


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?


Solution

  • 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_at(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_at(sheet.rows.length-1)
    

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

    More docs here.