Add border to range of cells in openpyxl Python

This tutorial is based on the task to add borders to a range of cells in openpyxl in Python. For this first of all, you need to make sure you have openpyxl installed on your system or not. To install run the below command in your terminal-

pip install openpyxl

You can check: How to install openpyxl in Python

Now the next step is to import this openpyxl module you have just installed on your system,, you guessed it right- just write import openpyxl and then import border, side, from openpyxl.styles module and Workbook.

The code for the above two lines

from openpyxl import Workbook
import openpyxl
from openpyxl.styles import Border,Side

The next step is to load the workbook, we will do it using-


We now need to define the border type and its color, we can choose any of the border-type from {'thin', 'dotted', 'thick', 'dashDotDot', 'mediumDashDot', 'double', 'hair', 'dashed', 'mediumDashed', 'medium', 'slantDashDot', 'mediumDashDotDot', 'dashDot'} and any hex color code.

bottom=Side(border_style='thick', color="A52A2A")

We have now defined the border for the top and bottom, we can also do it in the same way for the left and right sides of the cell.

Now its time to implement it to a range of cells, this can be done using a for loop –

for cell in range:
    for x in cell:

We have completed our task to add a border to the range of cells, we just need to save it and start our excel file to see the changes, we will do this by-"Border.xlsx")

This will show changes to your file, you can modify it according to your needs.

The output will look like this-

Add border to range of cells in openpyxl Python

I hope you enjoyed reading this tutorial and that you found it helpful for your task too.

Leave a Reply

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