Python Forum

Full Version: in openpyxl, how to set the font to 'centred'?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have the following code to set the font in my excel table using openpyxl:

ft1 = Font(name='Arial', size=20)

for sheet in targetFileSheetNames:
    targetFileActiveSheet = targetFile[sheet]
    maxRow = targetFileActiveSheet.max_row
    maxCol = targetFileActiveSheet.max_column
    for colNum in range(2, maxCol + 1, 1):
        for rowNum in range(1, maxRow + 1):
            targetFileActiveSheet.cell(row=rowNum, column=colNum).font = ft1
I would also like to have the text in the middle of the cell. I can't see how to set that.

Could someone please give me a tip? (I know that centre in American is 'center' Big Grin !
Try this:
rows = range(1, 44)
columns = range(1, 10)
for row in rows:
    for col in columns:
        sheet.cell(row, col).alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
Phil
Thanks for that, almost there, but something is not right:

Quote:Traceback (most recent call last):
File "./setTheFontv1.py", line 52, in <module>
targetFileActiveSheet.cell(row=rowNum, column=colNum).alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
NameError: name 'Alignment' is not defined

Maybe I need to load some other module? I have:

import os, openpyxl
from openpyxl.styles import PatternFill
from openpyxl.styles import Font
from openpyxl.utils import get_column_letter

Got it! I needed

from openpyxl.styles import Alignment
then

alignment = Alignment(horizontal='center',
                          vertical='bottom',
                          text_rotation=0,
                          wrap_text=False,
                          shrink_to_fit=True,
                          indent=0)
and in the for-loop

targetFileActiveSheet.cell(row=rowNum, column=colNum).alignment = alignment
awesome!