How to add color to Excel cells using Python

The openpyxl Python library provides various different modules to read and modify Excel files. Using this module, we can work on the Excel workbooks very easily and efficiently. In this section, we will discuss how we can add the background color to Excel cells in Python using the openpyxl library.

Program to add color to Excel cells in Python

Note: Before starting programming, create an Excel file with some data, or you can choose any of your existing Excel files.

Example:

openpyexlinput

 Step1: Import the openpyxl Library and modules to the Python program for adding color to the cell.

import openpyxl
from openpyxl.styles import PatternFill

Note: openpyxl.styles provides various different functions that style your cells in many different ways, like changing the color, font, alignment, border, etc.

 

Step2: Connect/Link your Excel workbook file and corresponding workbook’s working Sheet with the Python Program.

wb = openpyxl.load_workbook("//home//codespeedy//Documents//MyWorkBook.xlsx") #path to the Excel file
ws = wb['Sheet1'] #Name of the working sheet

 

Step3: Call the PaternFill() function with the Pattern type and foreground color parameters of your choice.

fill_cell = PatternFill(patternType='solid', 
                            fgColor='C64747') #You can give the hex code for different color

 

Step4: Lastly, fill the cell with color by using the name of the particular cell of the working sheet, and save the changes to the workbook.

ws['B2'].fill = fill_cell # B2 is the name of the cell to be fill with color
wb.save("//home//codespeedy//Documents//MyWorkBook.xlsx")

 

Here is the complete Python Program:

import openpyxl 
from openpyxl.styles import PatternFill

wb = openpyxl.load_workbook("//home//codespeedy//Documents//MyWorkBook.xlsx")
ws = wb['Sheet1'] #Name of the working sheet

fill_cell1 = PatternFill(patternType='solid', 
                           fgColor='FC2C03')
fill_cell2 = PatternFill(patternType='solid', 
                           fgColor='03FCF4') 
fill_cell3 = PatternFill(patternType='solid', 
                           fgColor='35FC03') 
fill_cell4 = PatternFill(patternType='solid', 
                           fgColor='FCBA03')  

ws['B2'].fill = fill_cell1
ws['B3'].fill = fill_cell2
ws['B4'].fill = fill_cell3
ws['B5'].fill = fill_cell4

wb.save("//home//sanamsahoo0876//Documents//MyWorkBook.xlsx")

Now, close the Excel application and reopen it to see the changes.

Output:

How to add color to Excel cells using Python

Hope this article has helped you understand adding color to the Excel cells using Python easily.

You can also read, Python Program to Merge Excel Cells using openpyxl

One response to “How to add color to Excel cells using Python”

  1. Virendra says:

    Yes, it helped. This is a simple method. Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *