Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontal text alignment in openpyxl

I'm trying to change the text alignment to the center of 2 merged cells. 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 way to do it?

like image 981
Pythonizer Avatar asked Oct 31 '14 09:10

Pythonizer


2 Answers

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

like image 178
samsemilia7 Avatar answered Nov 16 '22 02:11

samsemilia7


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 copy
alignment_obj = copy(cell.alignment)
alignment_obj.horizontal = 'center'
alignment_obj.vertical = 'center'
cell.alignment = alignment_obj
like image 12
nmz787 Avatar answered Nov 16 '22 00:11

nmz787