pythonpython-3.xexcelopenpyxl

openpyxl merged column is not centered


I'm trying to center a text along a merged column. I saw some examples and saw this was the way

ws.merge_cells('A1:Q1')

ws['A1'] = tableTitle

title_cell = ws['A1']
title_cell.font = bold_font
title_cell.fill = title_fill
title_cell.alignment = title_alignment


the result I get is not centered at all.

text not centered


Solution

  • The following code will do as you are attempting

    import openpyxl
    from openpyxl.styles import Font, PatternFill, Alignment
    
    xlfile = 'foo.xlsx'
    tableTitle = '3-Month Forecast Report starting 2024-09-19'
    bold_font = Font(bold=True)
    title_fill = PatternFill(start_color='90B4E2', end_color='90B4E2', fill_type='solid')
    title_alignment = Alignment(horizontal='center', vertical='center')
    
    wb = openpyxl.load_workbook(xlfile)
    ws = wb.active
    
    ws.merge_cells('A1:Q1')
    
    ws['A1'] = tableTitle
    
    title_cell = ws['A1']
    title_cell.font = bold_font
    title_cell.fill = title_fill
    title_cell.alignment = title_alignment
    
    wb.save(xlfile)
    

    enter image description here