Add Color to Excel Cells Using Python

If you want to add color to Excel cells and make data more visually appealing, you need to know the way to manipulate Excel files using Python code.

There are several Python libraries, where you can achieve this, but we are going to focus on two of them: Openpyxl and XlsxWriter.

Installing Required Libraries

Now, it’s time to install the required libraries. You can install both using the PIP installer.

Color Formatting with XlsxWriter

XlsxWriter is another Python library used for creating Excel files. It also provides functionality for formatting cells, including adding color.

XlsxWriter also creates a file, so there is no need to create it manually.

Here are the steps to add color to Excel cells using XlsxWriter:

  1. Import the xlsxwriter module:
  1. Create a workbook:
  1. Create a worksheet:
  1. Create a cell format:
  1. Select the cell to add the format:
  1. Save the workbook:

Full code:

Color Formatting with Openpyxl

Openpyxl is a Python library that allows users to read and modify Excel files. It also provides functionality for formatting cells, including adding color.

Openpyxl doesn’t create a file, so you have to create it manually or run the previous XlsxWriter code.

Here are the steps to add color to Excel cells using Openpyxl:

  1. Import the openpyxl module and the necessary styles module:
  1. Load the Excel workbook:
  1. Select the worksheet:
  1. Create a pattern fill:
  1. Select the cell to add the fill:
  1. Add text to a cell:
  1. Apply the fill to the cell:
  1. Save the workbook:

This is the full code you can copy:

Result

If you open the Excel file, you can see that both cells are filled by different Python libraries:

Table

Description automatically generated

Conclusion

As you can see, you can easily manipulate Excel using Python. I showed you both ways to do it, but XlsxWriter is the better way as the code is shorter and it can create Excel files, and not only read them.