Horizontal text alignment in openpyxl

Pythonizer picture Pythonizer · Oct 31, 2014 · Viewed 40.8k times · Source

I'm tryign to change the text alignment to the center of 2 merged sells, I've found some answers that didn't work for my case

currentCell = ws.cell('A1')
currentCell.style.alignment.horizontal = 'center' #TypeError: cannot set horizontal attribute
#or
currentCell.style.alignment.vertical = Alignment.HORIZONTAL_CENTER #AttributeError: type object 'Alignment' has no attribute 'HORIZONTAL_CENTER'

both didn't work, is there any other ways to do it?

Answer

samsemilia7 picture samsemilia7 · Jul 29, 2015

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

from openpyxl.styles import Alignment

currentCell = ws.cell('A1') #or currentCell = ws['A1']
currentCell.alignment = Alignment(horizontal='center')

hope this will help you