Setting Background Color of Excel Cell, Rows, Cols by openpyxl PatternFill

The openpyxl library has a class that can be used to set the background colors of Excel cells, rows or columns.

How to set background color in Excel Sheets by openpyxl

The openpyxl library has a class that can be used to set the background colors of Excel cells, rows, or columns.

The class name is PatternFill which has many options to set the background color by using its arguments. These include:

  • fill_type
  • start_color
  • end_color

The value for the start and end color must be hexadecimal to represent RGB (red, green, blue). For example, the green color is represented by 008040 value.

The fill_type argument has many values. The list is provided below along with its output to give you an idea. Let us start with a basic example of using PatternFill class.

An example of Setting Excel cell background color

For the first example, we will use five different cells and set their background colors. Following is the sample sheet that we will work on:


We will set different colors for each cell as shown in the example below with the code. The cells are B2, B3, B4, B5 and B6.

Python Program:



An example of setting background of rows

In this example, we will set the background color of four rows. For that, we will use the iter_rows function and provide its arguments so that it changes only the 2nd to 5th row colors. Have a look at the code and output below:

The code:

Result sheet:


Changing background of every other (even) row example

The following example changes the background color of even rows in the Excel sheet:

Python Code:



You can see the color of even rows is set to grey.

An example of changing column background color

Similarly, you may change the background color of the column by using iter_cols function. See an example below where we changed the color of the second column in our sample sheet:

The code:



You saw the background color of the 3rd column is changed after the first row.

Using all fill type values example

As mentioned earlier, the fill_type parameter has many possible values. In all our above examples,  we used solid value for fill_type.

Following is the list of possible values:

  • ‘none’
  • ‘solid’
  • ‘darkDown’
  • ‘darkGray’
  • ‘darkTrellis’
  • ‘darkGrid’
  • ‘darkHorizontal’
  •  ‘darkUp’
  • ‘darkVertical’
  • ‘lightGrid’
  • ‘gray0625’
  • ‘gray125’
  • ‘lightDown’
  • ‘lightGray’
  •  ‘lightHorizontal’
  • ‘lightTrellis’
  • ‘lightUp’
  • ‘lightVertical’
  • ‘mediumGray’


In the following example, we used all possible values and the Excel cell contains the name of each value along with its application.

See the name and corresponding output in the sheet below:

The code: