How To Set Background Color In Excel Using Python

In this tutorial, we will learn how to set the background color of cells in an Excel worksheet using Python. We will achieve this by leveraging the power of the openpyxl library. The openpyxl module allows Python to read and modify Excel files without any additional software or dependencies.

First, ensure you have the following prerequisites installed:
– Python (version 3.x is preferred)
– openpyxl library

If you do not have the openpyxl library, you can install it using the following pip command:

Now let’s start with the steps required to set the background color of cells in Excel.

Step 1: Import the openpyxl library

Step 2: Create or open an existing Excel file

To create a new workbook or open an existing Excel file, use the following code snippet:

To open an existing workbook, use the following code snippet:

Step 3: Set the background color in a cell

We now have our workbook and sheet handles stored in the variables “wb” and “ws,” respectively. Use the following code snippet to set the background color of a cell:

In the above code snippet, we have imported the PatternFill class from the openpyxl.styles module. Using this class, we can create a fill object with the desired background color. The start_color and end_color parameters accept color codes in hexadecimal format. Finally, we apply the fill object to the desired cell using the cell.fill property of the cell.

Full code

After executing the above code, you will see an Excel file named “my_excel_file.xlsx” in your current working directory. Opening the file, you will notice that the background color of cell A1 has been set to yellow.

Output

Conclusion

In this tutorial, we learned how to set the background color of cells in Excel using the openpyxl library with Python.

This method can be useful for highlighting important data, creating custom templates, or applying conditional formatting to your worksheets. Remember to explore the openpyxl official documentation to discover more features and possibilities.