How to Set Excel Font Style Using Python

2023-02-26 Python

Table of Contents

In this tutorial, we will talk about how to set font style for a cell or a range of cells in Excel by Python and openpyxl library.

Pandas

Set font style for a cell

Here’s an example of how to change the font style for a cell in an Excel worksheet using Python and the openpyxl library.

import openpyxl
from openpyxl.styles import Font

# Load the workbook
workbook = openpyxl.load_workbook('data/test.xlsx')

# Select the worksheet
worksheet = workbook.active

# Create a Font object with the desired font style
font = Font(name='Bauhaus 93', size=12, bold=True, italic=True)

# Set the font style for a cell
worksheet['A1'].font = font

# Save the changes to the workbook
workbook.save('data/test.xlsx')

Pandas

Set font style for a range of cells

Here’s an example of how to change the font style for a range of cells in an Excel worksheet using Python and the openpyxl library.

import openpyxl
from openpyxl.styles import Font

# Load the workbook
workbook = openpyxl.load_workbook('data/test.xlsx')

# Select the worksheet
worksheet = workbook.active

# Create a Font object with the desired font style
font = Font(name='Arial', size=12, bold=True, italic=True)

# Set the font style for a range of cells
for row in worksheet['A1:D1']:
    for cell in row:
        cell.font = font

# Save the changes to the workbook
workbook.save('data/test.xlsx')

Pandas

Subscribe and be the FIRST reader of our latest articles

* indicates required

Contact us