Horizontal text alignment in openpyxl Horizontal text alignment in openpyxl python python

Horizontal text alignment in openpyxl


yes, there is a way to do this with openpyxl:

from openpyxl.styles import AlignmentcurrentCell = ws.cell('A1') #or currentCell = ws['A1']currentCell.alignment = Alignment(horizontal='center')

hope this will help you


This is what finally worked for me with the latest version from PIP (2.2.5)

    # center all cells    for col in w_sheet.columns:        for cell in col:            # openpyxl styles aren't mutable,            # so you have to create a copy of the style, modify the copy, then set it back            alignment_obj = cell.alignment.copy(horizontal='center', vertical='center')            cell.alignment = alignment_obj

Update:

As of openpyxl version 2.4.0 (~2016) the .copy() method is deprecated for StyleProxy objects.

Try changing the last two lines to:

from copy import copyalignment_obj = copy(cell.alignment)alignment_obj.horizontal = 'center'alignment_obj.vertical = 'center'cell.alignment = alignment_obj


None of the other solutions worked for me, since my solution requires openpyxl, and at least in 2.1.5 cell.alignment can't be set directly.

from openpyxl.styles import Style, Alignmentcell = ws.cell('A1')cell.style = cell.style.copy(alignment=Alignment(horizontal='center')) 

The above copies the current style and replaces the alignment.You can also create a whole new style - with any values not specified taking the default values from https://openpyxl.readthedocs.org/en/latest/styles.html

cell.style = Style(alignment=Alignment(horizontal='center'),font=Font(bold=True))# or - a tidier wayvals = {'alignment':Alignment(horizontal='center'),        'font':Font(bold=True),       }new_style = Style(**vals)cell.style = new_style