Python Forum
in openpyxl, how to set the font to 'centred'?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
in openpyxl, how to set the font to 'centred'?
#1
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 !
Reply
#2
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
Reply
#3
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
Reply
#4
awesome!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  can openpyxl read font colors mperemsky 3 1,775 May-09-2023, 11:18 AM
Last Post: MindKeeper
  Load external font and does not show font in the window ATARI_LIVE 16 8,218 Feb-05-2021, 10:36 PM
Last Post: EthanPayne
  Add DSIG to TTF font using ttx font tool Adrian 1 3,796 Nov-11-2017, 12:05 PM
Last Post: Adrian

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020