When I tried to add multiple row headers to an excel in rails using Axlsx gem, I am able to make scenario 1. But, what I required is scenario 2, how do I do it?
Asked
Active
Viewed 1,224 times
1 Answers
0
The solution was to use merge_cells
method and center the cell itself horizontally and vertically.
require 'axlsx'
package = Axlsx::Package.new
package.workbook do |workbook|
workbook.add_worksheet name: 'merged_cells' do |sheet|
# define your styles
center = workbook.styles.add_style :alignment => { :horizontal => :center, :vertical => :center }
# fill the cells
sheet.add_row %w(A B C C), :style =>[center, center, center, center]
sheet.add_row %w(A B E F), :style =>[center, center, center, center]
sheet.add_row %w(A B G H), :style =>[center, center, center, center]
# merge cells
sheet.merge_cells "A1:A3"
sheet.merge_cells "B1:B3"
sheet.merge_cells "C1:D1"
end
end
package.serialize 'merged_cells.xlsx'
To spare some space, instead of:
sheet.add_row %w(A B C C), :style =>[center, center, center, center]
you could rewrite that to:
sheet.add_row %w(A B C C), :style => [center]*4
or even to:
sheet.add_row %w(A B C C), style: [center]*4

Volodymyr Balytskyy
- 577
- 1
- 7
- 19