Back to Python
2026-01-276 min read

Excel Format Fonts (Python Programming)

Learn Excel Format Fonts (Python Programming) step by step with clear examples and exercises.

Title: Excel Format Fonts (Python Programming)

Explore how to manipulate font styles in Microsoft Excel using Python programming! This tutorial will guide you through the core concept, provide a worked example, list common mistakes, offer practice questions, and answer frequently asked questions. Let's dive into why this matters, prerequisites, and get started!

Why This Matters

Understanding Excel format fonts is essential for data analysis and presentation purposes. By automating these tasks using Python, you can save time, reduce errors, and create professional-looking reports with ease. This skill is valuable for various fields such as finance, business, research, and more.

A well-designed report not only presents the information clearly but also helps to convey the intended message effectively. Manipulating font styles in Excel using Python can help you achieve this goal efficiently.

Prerequisites

To follow this tutorial, you should have a basic understanding of:

  1. Python programming language syntax and data structures (variables, functions, loops, and conditional statements).
  2. Microsoft Excel basics (creating worksheets, formatting cells, etc.).
  3. Familiarity with the openpyxl library for working with Excel files in Python. If you're not familiar with it yet, check out our Python Excel Tutorial first.
  4. Basic understanding of Excel formatting options such as font color, style, and size.

Core Concept

To manipulate font styles in Excel using Python, we'll use the openpyxl library. First, install it if you haven't already:

pip install openpyxl

Now let's create a simple Python script to change font colors and styles in an Excel file:

import openpyxl

Load the workbook (.xlsx) and select the worksheet by name

wb = openpyxl.load_workbook('example.xlsx')

ws = wb['Sheet1']

Change font color of cell A1 to red

cell = ws['A1']

cell.font = openpyxl.styles.Font(color='RED')

Change font style of cell B1 to bold and underline

cell = ws['B1']

cell.font = openpyxl.styles.Font(bold=True, underline='single')

Save the workbook back to disk

wb.save('example.xlsx')

In this example, we loaded an existing Excel file named `example.xlsx`, selected the first worksheet called 'Sheet1', and changed the font color of cell A1 to red and the font style of cell B1 to bold and underlined. Finally, we saved the changes back to the original file.

### Understanding openpyxl styles
The `openpyxl` library provides a rich set of style options for working with Excel files. To access them, create an instance of the `Font` class and modify its properties as needed:

- `color`: font color (e.g., 'RED', 'GREEN')
- `bold`, `italic`, `underline`, etc.: boolean values to enable or disable various styles
- `font_name`: specify a custom font name (e.g., 'Arial', 'Calibri')
- `size`: set the font size (e.g., 12, 14)

You can find more details about available style options in the [openpyxl documentation](https://openpyxl.readthedocs.io/en/stable/styles.html).

### Working with multiple styles
To apply multiple styles to a single cell, create a `Font` instance for each style and combine them using the `+` operator:

cell = ws['A1']

font_red = openpyxl.styles.Font(color='RED')

font_bold = openpyxl.styles.Font(bold=True)

cell.font = font_red + font_bold

In this example, we created separate instances for red and bold styles and combined them using the `+` operator to apply both styles to cell A1.

Worked Example

Now let's create a Python script that reads an Excel file, applies various font styles to specific cells based on their content, and saves the changes back to the original file:

import openpyxl
from openpyxl.styles import Font

Load the workbook (.xlsx) and select the worksheet by name

wb = openpyxl.load_workbook('example.xlsx')

ws = wb['Sheet1']

Define a function to apply font styles based on cell content

def format_cell(cell):

if 'RED' in cell.value:

cell.font = Font(color='RED')

elif 'BOLD' in cell.value:

cell.font = Font(bold=True)

elif 'UNDERLINE' in cell.value:

cell.font = Font(underline='single')

Iterate through all cells in the worksheet and apply font styles

for row in ws.iter_rows():

for cell in row:

format_cell(cell)

Save the workbook back to disk

wb.save('example.xlsx')

In this example, we defined a function called `format_cell()` that takes a cell object as an argument and applies font styles based on its content. We then iterated through all cells in the worksheet and applied the appropriate font styles using this function.

### Customizing the format_cell() function
You can customize the `format_cell()` function to suit your needs by adding more conditions or modifying existing ones. For example, you might want to change the color based on a specific range of values:

def format_cell(cell):

if 'RED' in cell.value:

cell.font = Font(color='RED')

elif cell.value >= 100:

cell.font = Font(bold=True, color='GREEN')

elif cell.value < 50:

cell.font = Font(underline='single', color='YELLOW')

In this updated version of the function, we added a condition to change the font color to green for values greater than or equal to 100 and underline the font for values less than 50.

Common Mistakes

Forgetting to save the workbook

Remember to call wb.save('example.xlsx') at the end of your script to save any changes made to the Excel file.

Using incorrect syntax for style properties

Ensure that you're using the correct syntax for setting style properties, such as bold=True, underline='single', etc.

Not importing openpyxl.styles

Don't forget to import the openpyxl.styles module at the beginning of your script: from openpyxl.styles import Font.

Practice Questions

  1. Write a Python script that sets the font size of all cells in column A to 14.
  2. Create a function called format_header() that applies bold and center alignment to all header rows (row 1) in an Excel file.
  3. Modify the format_cell() function from the worked example to change the font name based on the cell's content (e.g., 'Arial' for numbers, 'Calibri' for text).
  4. Write a Python script that applies different font styles (color, bold, italic, underline) to specific cells in an Excel file based on their values.
  5. Create a function called format_table() that formats an entire table (defined by row and column ranges) with custom font styles in an Excel file.

FAQ

Q: Can I use other libraries besides openpyxl for working with Excel files in Python?

A: Yes! Other popular libraries include pandas, xlrd, and xlwt. Each has its own strengths and weaknesses, so choose the one that best suits your needs.

Q: How can I handle conditional formatting (e.g., highlighting cells based on their values) in Excel using Python?

A: To achieve conditional formatting with openpyxl, you can use the ConditionalFormatRule class to create rules for cell formatting based on specific conditions. Check out the openpyxl documentation for more details.

Q: How can I read data from an Excel file into a Python list or DataFrame?

A: To read data from an Excel file into a Python list, you can use a simple loop to iterate through the rows and columns. For more advanced data manipulation and analysis, consider using the pandas library. Check out our Python Excel Tutorial for more details on both approaches.

Q: How can I create or add new worksheets to an existing Excel file using Python?

A: To create a new worksheet in an Excel file, use the create_sheet() method of the workbook object:

wb = openpyxl.Workbook()
ws1 = wb.active # default worksheet
ws2 = wb.create_sheet('NewSheet')

To add a new worksheet at a specific position, use the insert_sheets() method:

wb.insert_sheets(ws3, before=ws1) # inserts 'ws3' before 'ws1'
Excel Format Fonts (Python Programming) | Python | XQA Learn