Python OpenPyXL Font Underline for Excel Cells

In this Python OpenPyXL tutorial we learn how to set the font underline 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 underline 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 A5 cells.

ws['A1'] = 'Tori Code'
ws['A2'] = 'Tori Code'
ws['A3'] = 'Tori Code'
ws['A4'] = 'Tori Code'
ws['A5'] = 'Tori Code'

Create a new Font object with the underline value is single and set the font for A1 cell.

font1 = Font(underline='single')
ws['A1'].font = font1

Create a new Font object with the underline value is double and set the font for A2 cell.

font2 = Font(underline='double')
ws['A2'].font = font2

Create a new Font object with the underline value is singleAccounting and set the font for A3 cell.

font3 = Font(underline='singleAccounting')
ws['A3'].font = font3

Create a new Font object with the underline value is doubleAccounting and set the font for A4 cell.

font4 = Font(underline='doubleAccounting')
ws['A4'].font = font4

Then save the Workbook as font_underline.xlsx file.

wb.save('font_underline.xlsx')

The complete Python program as below.

font_underline.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'
ws['A5'] = 'Tori Code'

font1 = Font(underline='single')
ws['A1'].font = font1

font2 = Font(underline='double')
ws['A2'].font = font2

font3 = Font(underline='singleAccounting')
ws['A3'].font = font3

font4 = Font(underline='doubleAccounting')
ws['A4'].font = font4

wb.save('font_underline.xlsx')

Execute the above Python program we will get the Excel file font_underline.xlsx as below screenshot.

Python OpenPyXL Font Underline for Excel Cells

Happy Coding 😊