Back to Python
2026-01-097 min read

Excel Format Colors (Python Programming)

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

Why This Matters

Excel format colors play an essential role in data visualization and understanding. By automating the process of changing cell colors using Python's openpyxl library, we can create more engaging and informative Excel files. This skill is valuable in various scenarios such as:

  1. Automated Data Analysis: Automate the formatting of large datasets to make them easier to visualize and interpret.
  2. Custom Report Generation: Tailor reports to specific requirements or brand guidelines by programmatically controlling Excel's appearance.
  3. Debugging and Visualizing Code Output: Generate Excel files with colored cells representing different data types, functions, or variables for a better understanding of code output.
  4. Solving Real-world Problems: In many industries like finance, marketing, and research, the ability to automate formatting in Excel using Python can significantly improve productivity and efficiency.

Prerequisites

To follow this lesson, you will need:

  1. Basic understanding of Python programming concepts (variables, functions, loops, conditional statements)
  2. Familiarity with the openpyxl library for working with Excel files in Python
  3. Python 3.x installed on your system
  4. The openpyxl library installed (pip install openpyxl)
  5. Basic understanding of Excel file structure and format
  6. Knowledge of how to navigate an Excel file using Python (e.g., accessing cells, creating/modifying worksheets)
  7. Familiarity with the concept of cell styles and formats in Excel
  8. Understanding of basic data manipulation techniques in Python (e.g., list comprehensions, functions)

Core Concept

Manipulating Excel format colors with openpyxl involves working with the Cell and Style objects. To change cell colors, we will use the PatternFill class from the openpyxl.styles module.

First, let's import the necessary modules:

from openpyxl import Workbook
from openpyxl.styles import PatternFill

Next, create a new Excel workbook:

wb = Workbook()
ws = wb.active

Now, let's define the color we want to use for our cells:

red_fill = PatternFill(start_color='FF0000', end_color='FF0000', fill_type='solid')

To set a cell's background color, apply the red_fill to its style:

ws['A1'].style = red_fill

Save the workbook to a file:

wb.save('colored_cell.xlsx')

You can now open the colored_cell.xlsx file and see that cell A1 has been filled with red color.

Cell Styles

Excel cell styles are predefined formatting options that you can apply to cells in a workbook. To create a new style, use the Style class from the openpyxl.styles module:

red_style = ws.add_style(PatternFill(start_color='FF0000', end_color='FF0000', fill_type='solid'), font_italic=True)
ws['A2'].style = red_style

In this example, we've created a new style called red_style that includes both the red background color and italic text. We then applied this style to cell A2.

Worked Example

Let's create a simple Excel file containing student names, scores, grades, and their corresponding colored cells:

from openpyxl import Workbook
from openpyxl.styles import PatternFill

wb = Workbook()
ws = wb.active

Define color patterns for different grade ranges

failing_fill = PatternFill(start_color='FFD7CE', end_color='FFD7CE', fill_type='solid') # Failing grade (<60)

warning_fill = PatternFill(start_color='FFFFC7', end_color='FFFFC7', fill_type='solid') # Warning grade (60-69)

passing_fill1 = PatternFill(start_color='FFEBCD', end_color='FFEBCD', fill_type='solid') # Passing grade (70-74)

passing_fill2 = PatternFill(start_color='C9F0C9', end_color='C9F0C9', fill_type='solid') # Good grade (75-84)

excellent_fill = PatternFill(start_color='A6E22E', end_color='A6E22E', fill_type='solid') # Excellent grade (85-100)

Set headers and data

header_format = ws['A1']:['D1']

header_format.font = 'Arial'

header_format.fill = PatternFill(start_color='FFF2CC', end_color='FFF2CC', fill_type='solid')

header_format[0].value = "Student"

header_format[1].value = "Score"

header_format[2].value = "Grade"

header_format[3].value = "Color"

data = [

["John", 85, 'B', passing_fill2],

["Sarah", 70, 'C-', warning_fill],

["Mike", 65, 'D-', failing_fill],

["Emily", 90, 'A', excellent_fill]

]

for row in data:

ws.append(row)

Format cells based on score range

for i in range (2, len(data)+1):

if data[i-1][1] >= 85:

ws[f"A{i}"].fill = excellent_fill

elif data[i-1][1] >= 75 and data[i-1][1] < 85:

ws[f"A{i}"].fill = passing_fill2

elif data[i-1][1] >= 60 and data[i-1][1] < 75:

ws[f"A{i}"].fill = passing_fill1

elif data[i-1][1] >= 60:

ws[f"A{i}"].fill = warning_fill

else:

ws[f"A{i}"].fill = failing_fill

ws['A2'].value = "Score Range"

ws['B2'].value = "Grade"

ws['C2'].value = "Color"

Save the workbook to a file

wb.save('grades.xlsx')


After running this code, you will find an Excel file named `grades.xlsx` with colored cells based on student scores and grades.

### Cell Style Application

To apply cell styles, first create the style as shown in the previous section, then set it for individual cells or ranges using the `style` attribute:

bold_style = ws.add_style(font_italic=True)

ws['A1'].style = bold_style


In this example, we've created a new style called `bold_style` that includes italic text. We then applied this style to cell A1.

Common Mistakes

  1. Forgetting to import the openpyxl library: Make sure to include from openpyxl import Workbook and from openpyxl.styles import PatternFill.
  2. Not defining color patterns before using them: Color patterns should be defined before they are applied to cells.
  3. Incorrect cell reference: Be careful with cell references, especially when looping through data or formatting multiple cells at once.
  4. Not saving the workbook after changes: Don't forget to call wb.save() to save your changes.
  5. Using the wrong fill type for patterns: Make sure the fill_type is set to 'solid' when defining color patterns.
  6. Inconsistent cell formatting: Ensure that all cells within a specific range have the same format, including font style and size, alignment, and borders.
  7. Not handling edge cases: Be aware of edge cases such as empty cells or cells with non-numeric values when working with data manipulation and formatting.
  8. Not closing the workbook properly: Always close the workbook after saving to ensure that all changes are written to the file.
  9. Misusing cell styles: Make sure you understand how to create, apply, and modify cell styles effectively.
  10. Ignoring Excel limitations: Be aware of Excel's limitations regarding the number of rows, columns, and formatting options in a single workbook or worksheet.

Practice Questions

  1. Write a Python script that creates an Excel file with three columns: "Name", "Age", and "Color". Use conditional formatting based on age ranges (0-18, 19-30, 31+) to set the cell background color.
  2. Modify the previous example to include a fourth column for gender ("Male" or "Female") and change the color patterns based on both age and gender.
  3. Write a Python script that reads an Excel file with student data (name, score, grade) and calculates the average score for each grade. Save the results in a new Excel file.
  4. Create an Excel file containing a list of countries and their capitals. Use Python to change the background color of cells based on whether the capital is located in Europe or another continent.
  5. Write a script that reads an Excel file with sales data (product, quantity sold, price) and calculates the total revenue for each product. Sort the products by total revenue and save the results in a new Excel file.

FAQ

  1. How can I set different font styles for my cells? You can use the Font object from the openpyxl.styles module to define and apply font styles, such as bold, italic, and underline.
  2. Can I change the text color of my cells? Yes, you can set the text color by using the TextColor property of the Font object.
  3. How do I create a pattern fill with multiple colors? To create a gradient fill, you can use the LinearGradientFill or DiagonalGradientFill classes instead of PatternFill.
  4. Why are my cell colors not showing up in the Excel file? Make sure that your color patterns have been defined before they are applied to cells and that you've saved the workbook after making changes. Also, check if the fill type is set to 'solid'.
  5. How can I create a new worksheet in my Excel file? To add a new worksheet, use wb.create_sheet(title="Sheet2"). You can replace "Sheet2" with any desired title for your new worksheet.
  6. How can I read data from an Excel file using Python? Use the openpyxl library's load_workbook() function to load an existing workbook, and then access cells by their coordinates or iterate through rows and columns.
  7. Can I use openpyxl to create charts in my Excel files? Yes, you can create charts using the Chart object from the openpyxl.chart module. First, make sure you have the required data in your worksheet, then create a chart, and add it to the worksheet using the add_chart() method.
  8. How can I apply conditional formatting rules to cells? Use the ConditionalFormatRule object from the openpyxl.styles.borders module to define custom rules for conditional formatting, such as cell value comparisons or data bars. Then, apply these rules to individual cells or ranges using the conditional_formats attribute of the Worksheet object.
  9. How can I handle missing values (e.g., NaN) in my data? To handle missing values, you can use Python's built-in functions like isnan() to check for missing values and replace them with appropriate values or ignore them during calculations.
  10. What are some best practices when working with openpyxl? Some best practices include:
  • Keeping your code organized and modular
  • Using meaningful variable names
  • Documenting your code
  • Testing your scripts thoroughly
  • Handling edge cases effectively
  • Being aware of Excel limitations and optimizing your code accordingly.
Excel Format Colors (Python Programming) | Python | XQA Learn