openpyxl icon indicating copy to clipboard operation
openpyxl copied to clipboard

Styling merged cells

Open vinraspa opened this issue 1 year ago • 1 comments

The example given in the doc:

>>> from openpyxl.styles import Border, Side, PatternFill, Font, GradientFill, Alignment
>>> from openpyxl import Workbook
>>>
>>> wb = Workbook()
>>> ws = wb.active
>>> ws.merge_cells('B2:F4')
>>>
>>> top_left_cell = ws['B2']
>>> top_left_cell.value = "My Cell"
>>>
>>> thin = Side(border_style="thin", color="000000")
>>> double = Side(border_style="double", color="ff0000")
>>>
>>> top_left_cell.border = Border(top=double, left=thin, right=thin, bottom=double)
>>> top_left_cell.alignment = Alignment(horizontal="center", vertical="center")
>>>
>>> wb.save("styled.xlsx")

does not work for bottom and right borders.

image

vinraspa avatar Oct 04 '23 11:10 vinraspa

For me, the code works if I move merging the cells to after doing all the styling as shown below:

>>> from openpyxl.styles import Border, Side, PatternFill, Font, GradientFill, Alignment
>>> from openpyxl import Workbook
>>>
>>> wb = Workbook()
>>> ws = wb.active
>̶>̶>̶ ̶w̶s̶.̶m̶e̶r̶g̶e̶_̶c̶e̶l̶l̶s̶(̶'̶B̶2̶:̶F̶4̶'̶)̶
>>>
>>> top_left_cell = ws['B2']
>>> top_left_cell.value = "My Cell"
>>>
>>> thin = Side(border_style="thin", color="000000")
>>> double = Side(border_style="double", color="ff0000")
>>>
>>> top_left_cell.border = Border(top=double, left=thin, right=thin, bottom=double)
>>> top_left_cell.alignment = Alignment(horizontal="center", vertical="center")
>>>
>>> ws.merge_cells('B2:F4')
>>>
>>> wb.save("styled.xlsx")

id-hkj avatar Mar 10 '24 17:03 id-hkj