How to Add Borders in Excel Using Python OpenPyxl

When working with Excel worksheets using Python, there might be times you want to add borders to your cells to make certain data stand out or simply to make your worksheet look neat and organized. Fortunately, the openpyxl module in Python makes this easy to accomplish.

With openpyxl, you can read/write Excel xlsx/xlsm/xltx/xltm files. It is a popular choice for Python developers who want to work with Excel worksheets. The great part – the openpyxl module provides a ‘border’ member in its module to handle cell borders.

Step 1: Install openpyxl

If you haven’t already done so, you will need to install the openpyxl module. It can be done using pip, a packet manager in Python:

Once you have installed openpyxl, you can proceed to load your Excel file. Remember, the file must be in .xlsx format.

Step 2: Load your Excel file

Begin by loading your Excel workbook using openpyxl:

Replace “sample.xlsx” with the name of your Excel file. Ensure this file is in the same directory as the Python script you will be running.

Step 3: Set Border Styles

Openpyxl allows various border styles for individual sides of a cell. First, we have to import the Border, and Side classes:

In the above example, we set a thin border. There are various other border styles such as dashed, dotted, and more

Step 4: Applying the Border to a Cell

Now let’s apply the border to a specific cell in the worksheet:

Step 5: Save your changes

After adding all your borders, save your outcome back to your Excel file:

If you follow all the steps correctly, your Excel cell ‘A1’ will now have a thin border around it.

The Full code:

Conclusion:

Working with Excel sheets in Python has never been easier with the openpyxl module. As you have seen, adding borders to your cells greatly enhances the visual aspect of your sheets. Feel free to experiment with other border styles until you get your desired look.