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:
1 |
pip install openpyxl |
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:
1 2 3 |
from openpyxl import load_workbook workbook = load_workbook(filename="sample.xlsx") sheet = workbook.active |
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:
1 2 3 4 5 |
from openpyxl.styles import Border, Side thin_border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin')) |
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:
1 |
sheet['A1'].border = thin_border |
Step 5: Save your changes
After adding all your borders, save your outcome back to your Excel file:
1 |
workbook.save(filename="sample.xlsx") |
If you follow all the steps correctly, your Excel cell ‘A1’ will now have a thin border around it.
The Full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
from openpyxl import load_workbook from openpyxl.styles import Border, Side workbook = load_workbook(filename="sample.xlsx") sheet = workbook.active # Creating a border style thin_border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin')) sheet['A1'].border = thin_border workbook.save(filename="sample.xlsx") |
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.