Python OpenPyXL Font Vertical Align for Excel Cells
In this Python OpenPyXL tutorial we learn how to set the font vertical align style for Excel cells using the OpenPyXL package Font class.
How to install the OpenPyXL package
To install the OpenPyXL package using the command below.
pip install openpyxl
How to set font vertical align for the Excel cells
Import the Workbook and Font from the OpenPyXL package.
from openpyxl import Workbook
from openpyxl.styles import Font
Create a new Workbook object.
wb = Workbook()
Get the default active Worksheet object.
ws = wb.active
Assign value from A1 to A4 cells.
ws['A1'] = 'Tori Code'
ws['A2'] = 'Tori Code'
ws['A3'] = 'Tori Code'
ws['A4'] = 'Tori Code'
Create a new Font object with the vertAlign value is superscript and set the font for A1 cell.
font1 = Font(vertAlign='superscript')
ws['A1'].font = font1
Create a new Font object with the vertAlign value is subscript and set the font for A2 cell.
font2 = Font(vertAlign='subscript')
ws['A2'].font = font2
Create a new Font object with the vertAlign value is baseline and set the font for A3 cell.
font3 = Font(vertAlign='baseline')
ws['A3'].font = font3
Then save the Workbook as font_vertical_align.xlsx file.
wb.save('font_vertical_align.xlsx')
The complete Python program as below.
font_vertical_align.py
from openpyxl import Workbook
from openpyxl.styles import Font
wb = Workbook()
ws = wb.active
ws['A1'] = 'Tori Code'
ws['A2'] = 'Tori Code'
ws['A3'] = 'Tori Code'
ws['A4'] = 'Tori Code'
font1 = Font(vertAlign='superscript')
ws['A1'].font = font1
font2 = Font(vertAlign='subscript')
ws['A2'].font = font2
font3 = Font(vertAlign='baseline')
ws['A3'].font = font3
wb.save('font_vertical_align.xlsx')
Execute the above Python program we will get the Excel file font_vertical_align.xlsx as below screenshot.
Happy Coding 😊