How To Set Cell Styles Using OpenPyX – Background Pattern Fill

Method

You can set cell background fill using either gradient fill or pattern fill, using the `GradientFill` and `PatternFill` classes respectively.

  • Pattern Fill

Use the `PatternFill` class to create a pattern fill object.

from openpyxl.styles.fills import PatternFill

PatternFill(patternType=None,fgColor=<openpyxl.styles.colors.Color object>

Parameters: rgb=’00000000′, indexed=None, auto=None, theme=None, tint=0.0, type=’rgb’, bgColor=<openpyxl. styles.colors.Color object>

Parameters: rgb=’00000000′, indexed=None, auto=None, theme=None, tint=0.0, type=’rgb’, fill_type=None, start_color=None, end_color= None)

Where:

patternType、fill_type—The pattern fill type, its value must be one of the following: “darkDown”、“gray0625”、“mediumGray”、“darkHorizontal”、“lightVertical”、“darkGrid”、“lightGray”、“darkTrellis”、“darkVertical”、“lightGrid”、“solid”、“lightDown”、“lightUp”、“darkUp”、“darkGray”、“lightTrellis”、“lightHorizontal”、“gray125”、None。

fgColor、start_color—Foreground color, the value of fgColor must be a Color object.

bgColor、end_color—Background color, the value of bgColor must be a Color object.

 

When **fill_type** is set to None, no fill will be applied.

When **fill_type** is set to ‘Solid’, it will be a solid color fill.

Sample Code

#Cell Style: Pattern Fill

#Import load_workbook function
from openpyxl import Workbook

#Create a new workbook
wb=Workbook()
#Get the active worksheet
ws=wb.active

#Import PatternFill class
from openpyxl.styles import PatternFill
from openpyxl.styles.colors import Color

#Pattern fill
ws['B2'].fill=PatternFill(fill_type=None, \
            start_color='FFFF00', end_color='000000')
ws['C2'].fill=PatternFill(fill_type='solid', \
            start_color='00FF00')
ws['E2'].fill=PatternFill(fill_type='lightGrid', \
            start_color='FFFF00', end_color='000000')
fill=PatternFill(fill_type='lightTrellis', \
            fgColor=Color(rgb='00FF00'), bgColor=Color(rgb='0000FF'))
ws.column_dimensions['B'].fill=fill
fill=PatternFill(fill_type='lightGray', \
            fgColor=Color(rgb='FFFF00'), bgColor=Color(rgb='0000FF'))
ws.row_dimensions[4].fill = fill

wb.save('test.xlsx')
wb.close()
Set Cell Styles Using OpenPyX - Background Pattern Fill

Leave a Reply

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