In this post we will be creating a Python script that will add a colored border to a cell within a spreadsheet using openpyxl. Openpyxl is a library that allows us to interact with Excel files in Python. It provides a range of tools for reading, writing, manipulating, and formatting Excel data. This makes it a useful tool for data analysis and reporting tasks.
See the sample of Python code below where we use the openpyxl library to add a colored border around a cell within an already existing Excel spreadsheet. We start by loading our existing Excel file called example.xlsx
and assign it to a variable named workbook
. Next we retrieve the active worksheet from the workbook. A new Border
object is then created with Side
objects for each side. Here the border style for each side is set to ‘double’ and a color is also assigned. We then select cell B2 of the worksheet
and assign it to the variable cell
. The border style for our cell
is then set to the border_style
defined earlier. Finally the changes made to the Excel file are saved using the save()
method.
import openpyxl
from openpyxl.styles import Border, Side
workbook = openpyxl.load_workbook('example.xlsx')
worksheet = workbook.active
border_style = Border(left=Side(style='double', color='FF0000'),
right=Side(style='double', color='00FF00'),
top=Side(style='double', color='0095FF'),
bottom=Side(style='double', color='FF00DD'))
cell = worksheet['B2']
cell.border = border_style
workbook.save('example.xlsx')
See an image of the colored border for our cell below.

Take a look at some of our other content around the Python programming language by clicking here.