Back to Python
2026-01-277 min read

Excel Formatting (Python Programming)

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

Why This Matters

Excel is an essential tool for data analysis and visualization across various fields like finance, research, and business. Automating Excel formatting tasks using Python can significantly boost productivity and consistency in your data presentation. In this tutorial, we will delve into the use of the openpyxl library to format Excel files programmatically.

Prerequisites

Before diving into the core concept, ensure you have a basic understanding of:

  1. Python programming language
  2. Basic Excel concepts (rows, columns, cells, formatting options)
  3. The openpyxl library for working with Excel files in Python
  4. Familiarity with Python's file handling and data structures like lists, tuples, and dictionaries
  5. Understanding of conditional statements and loops in Python
  6. Knowledge of exception handling in Python

If you're not familiar with these topics, consider reviewing the following resources:

Core Concept

To format Excel files using Python, we'll use the openpyxl library. First, install it via pip:

pip install openpyxl

Now let's create a simple Python script to format an Excel file:

  1. Import necessary libraries:
from openpyxl import Workbook, load_workbook
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
  1. Create or load the workbook:

To create a new workbook

wb = Workbook()

To load an existing workbook

wb = load_workbook('example.xlsx')


3. Access the active worksheet:

ws = wb.active


4. Format cells using different styles:

- Change font color:

font = Font(color='00FF00', underline='single') # Green, underlined font

ws['A1'].font = font


- Set cell background color:

fill = PatternFill(start_color='FFBDB7', end_color='FFBDB7', fill_type='solid')

ws['A2'].fill = fill


- Align text in the center:

alignment = Alignment(horizontal='center')

ws['A3'].alignment = alignment


- Apply borders to cells:

border = Border(left=Side(style='thin', color='000000'), right=Side(style='thin', color='000000'), top=Side(style='thin', color='000000'), bottom=Side(style='thin', color='000000'))

ws['A1'].border = border


- Format a range of cells:

cell_range = ws['A1':'E5'] # Define the cell range to format

font = Font(color='FFD700', bold=True) # Set font style for the range

for cell in cell_range:

cell.font = font


- Apply conditional formatting:

from openpyxl.worksheet.datavalidation import DataValidation, NumberRule

Define a rule for highlighting cells with values greater than 50

greater_than_rule = DataValidation(type='number', operator='>=', formula1=50)

Apply the rule to cells in column B (column index 2) from row 2 to the end

ws.add_data_validation(greater_than_rule, 'B2:B')


5. Save the workbook:

wb.save('formatted_example.xlsx')

Worked Example

Let's format an Excel file containing a table of student grades. We will apply different styles to headers, total rows, and low-performing students.

  1. Import necessary libraries:
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
from openpyxl.utils import get_column_letter
  1. Create a new workbook and access the active worksheet:
wb = Workbook()
ws = wb.active
  1. Define constants for style names:
header_font = Font(bold=True, color='008B8B')
total_font = Font(bold=True, color='FFD700')
low_performance_font = Font(color='FF0000')
border_style = Side(border_style='thin', color='000000')
fill_highlight = PatternFill(start_color='FFFF66', end_color='FFFF66', fill_type='solid')
  1. Write the data into the worksheet:
data = [
['Student', 'Math', 'English', 'Science'],
['Alice', 95, 85, 92],
['Bob', 70, 65, 75],
['Charlie', 80, 90, 88],
['David', 100, 98, 99]
]

for row in data:
ws.append(row)
  1. Format headers and total rows:

Header formatting

ws[1].font = header_font

ws[1].fill = fill_highlight

Total row formatting

total_row = len(data)

ws[f'{get_column_letter(len(data[0]))}{total_row}'].value = 'Total'

ws[f'{get_column_letter(len(data[0]))}{total_row}'].font = total_font

Apply borders to total row and headers

for col in range(1, len(data[0])+1):

ws.cell(row=total_row, column=col).border = Border(top=border_style, left=border_style, right=border_style)

ws.cell(row=1, column=col).border = Border(bottom=border_style, left=border_style, right=border_style)


6. Identify low-performing students and format their cells:

low_performance_threshold = 75

for row in range(2, len(data)):

if any([value < low_performance_threshold for value in data[row][1:]]):

for col in range(2, len(data[0])+1):

ws.cell(row=row, column=col).font = low_performance_font


7. Save the workbook:

wb.save('student_grades.xlsx')

Common Mistakes

  1. Forgetting to import necessary libraries
  2. Not specifying the correct font color (hexadecimal format)
  3. Applying styles to the wrong cell or range of cells
  4. Failing to save the workbook after formatting
  5. Using an outdated version of openpyxl, resulting in missing features or compatibility issues
  6. Forgetting to close the workbook after saving it (in case you're using a new workbook)
  7. Not handling exceptions when working with Excel files
  8. Incorrectly defining cell ranges for formatting operations
  9. Misunderstanding conditional formatting rules and applying them incorrectly
  10. Not properly setting the formula for conditional formatting rules

Practice Questions

  1. Write a Python script to format an Excel file containing a list of employees, where their names are in column A and their salaries are in column B. Apply bold font for headers, center-align text, and set a background color for all cells in column A using the PatternFill class.
  2. Modify the previous example to highlight employees with a salary greater than 50,000 using a custom color of your choice.
  3. Write a Python script to create an Excel file containing a table of sports scores. The table should have headers (Team, Score1, Score2) and data for multiple games. Apply different styles for headers, total rows, and the team with the highest score in each game.
  4. Write a Python script that reads an Excel file into a Pandas DataFrame, applies formatting using the Styler object, and saves the DataFrame as an Excel file.
  5. Create a Python script that reads multiple Excel files from a directory, formats them using the same styles (e.g., bold headers, centered text), and saves the formatted files in another directory.
  6. Write a Python script to merge cells in an Excel file using Python and openpyxl.
  7. Create a Python script that reads an Excel file, calculates the average score for each student, and writes the results into a new worksheet in the same workbook.
  8. Write a Python script to create a bar chart for the total scores of each team in an Excel file using openpyxl-chart.
  9. Modify the previous example to include conditional formatting rules that highlight cells containing incorrect data (e.g., negative values or missing data).
  10. Write a Python script to automate the process of formatting and saving multiple Excel files from a directory, while also creating a summary file that contains the total scores for each team.

FAQ

Q: How can I set conditional formatting rules in Excel files using Python?

A: Openpyxl does not support conditional formatting natively. You can use the xlwings library for this purpose.

Q: What are some other libraries for working with Excel files in Python?

A: Apart from openpyxl, you can also use xlrd, xlwt, and pandas for various tasks related to Excel files.

Q: How can I read an Excel file into a Pandas DataFrame and apply formatting using the Styler object?

A: You can use the read_excel() function from pandas to load the Excel file as a DataFrame, then style it using the apply() method on the DataFrame's Styler object.

Q: Is it possible to merge cells in an Excel file using Python and openpyxl?

A: Yes, you can merge cells using the merge_cells() method from the Alignment class.

Q: How can I create charts (e.g., bar charts, pie charts) in an Excel file using Python and openpyxl?

A: Openpyxl does not support creating charts natively. However, you can use the pygal library for charting purposes or combine openpyxl with other libraries like openpyxl-chart.

Q: How can I handle large Excel files (e.g., millions of rows) using Python and openpyxl?

A: To work with large Excel files efficiently, consider breaking the data into smaller chunks, processing them separately, and then merging the results. You can also use the chunksize parameter in the load_workbook() function to load only a specified number of rows at a time.

Q: Can I use openpyxl to create an Excel file with multiple worksheets?

A: Yes, you can create multiple worksheets within a workbook using the create_sheet() method.

Q: How can I handle errors when working with Excel files in Python using openpyxl?

A: You can use exception handling to catch and handle errors that may occur while reading or writing Excel files using openpyxl.

Q: Is it possible to apply custom number formats (e.g., currency format, date format) to cells in an Excel file using Python and openpyxl?

A: Yes, you can apply custom number formats using the NumberFormat class from the openpyx

Excel Formatting (Python Programming) | Python | XQA Learn