To add color to Excel cells we will be using the Openpyxl Python Library. The Openpyxl module allows us to read and modify Excel files using Python.
Approach 1:
Using the Openpyxl module, even small tasks can be done very efficiently and easily in excel.
Input File:
Only declare the excel name with .xlsx form if the file exists in the same folder as where the code exists. If the file exists in another folder then the linking has to be done by giving the entire path source.
Installing the OpenPyxl module: In order to install the openpyxl module via pip run the below command in the terminal of the user’s choice:
pip install openpyxl
Example:
Python3
import openpyxl from openpyxl.styles import PatternFill wb = openpyxl.load_workbook( "GFGCoursePrices.xlsx" ) ws = wb[ 'Sheet1' ] |
To fill the color in the cell you have to declare the pattern type and fgColor. Now create a working sheet variable and initialize it with the current sheet you are working on using the syntax
Python3
colors = [ '00660066' , '00FFFFCC' , '00FF0000' , '0000FF00' , '00660066' ] fillers = [] for color in colors: temp = PatternFill(patternType = 'solid' , fgColor = color) fillers.append(temp) |
Here we need to keep in mind that colors value has to be strictly hex values not like ‘Blue’ ,’yellow’ , ‘red’ etc. It will not work. Otherwise, we will encounter an error like below:
Finally, you have to save changes using the .save() function. To fill each cell, you have to use the .fill() function depicted by the following syntax.
Python3
cell_ids = [ 'B2' , 'B3' , 'B4' , 'B5' , 'A2' ] for i in range ( 5 ): ws[cell_ids[i]].fill = fillers[i] wb.save( "GFGCoursePrices.xlsx" ) |
Output:
Approach 2:
We can also take the help of Color method of the openpyxl.styles.colors. Here we can pass integer values (0-63) and while coloring them we need to pass them as the value of a keyworded argument indexed.
Python3
import openpyxl from openpyxl.styles import PatternFill from openpyxl.styles.colors import Color wb = openpyxl.load_workbook( "Lazyroar.xlsx" ) ws = wb[ 'Sheet1' ] # Color Indexes, ranges from 0-63 colors = [ 6 , 3 , 48 , 37 , 28 ] fillers = [] for color in colors: temp = PatternFill(patternType = 'solid' , fgColor = Color(indexed = color)) fillers.append(temp) cell_ids = [ 'B2' , 'B3' , 'B4' , 'B5' , 'A2' ] for i in range ( 5 ): ws[cell_ids[i]].fill = fillers[i] wb.save( "Lazyroar.xlsx" ) |
Output: