Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails AXLSX gem trying to merge cells of last row created

I have an axlsx file with some logic in there that creates rows. I have a check in there, that when a certain condition is met, i want to merge the last cells created. How can i do this?

The only way that i've seen how to merge cells is by specifying the cells to merge like this:

sheet.merge_cells "A2:B2"

but if i have a dynamic sheet, how can i merge cells of the last row created?

like image 523
Catfish Avatar asked Feb 16 '23 10:02

Catfish


2 Answers

Axlsx merge_cells accepts a string, as in your example, or an array of cells. To that extent, you can use the rows, cols and their cells collections to find, and pass in an array of cells you want to merge.

Something like:

sheet.merge_cells sheet.rows.last.cells

For reference, here's the documentation on Worksheet#merge_cell

# Creates merge information for this worksheet.
# Cells can be merged by calling the merge_cells method on a worksheet.
# @example This would merge the three cells C1..E1    #
#        worksheet.merge_cells "C1:E1"
#        # you can also provide an array of cells to be merged
#        worksheet.merge_cells worksheet.rows.first.cells[(2..4)]
#        #alternatively you can do it from a single cell
#        worksheet["C1"].merge worksheet["E1"]
# @param [Array, string] cells
def merge_cells(cells)
  merged_cells.add cells
end
like image 123
randym Avatar answered Mar 25 '23 02:03

randym


This one is kind of generic solution

 current_row = sheet.rows.count + 1
 merge_parameter= "A#{current_row}:F#{current_row}"
 sheet.merge_cells(merge_parameter)
like image 36
NIshank Avatar answered Mar 25 '23 00:03

NIshank