We will learn how to add a border in Excel using Python in this tutorial. Python provides a powerful library called openpyxl for working with Excel files. You can read from, write to, and modify Excel documents with openpyxl. Specifically, we’ll use it to add a border to our Excel cells. Let’s get started.
Step 1: Install Required Libraries
Before we start, we need to ensure that we have the necessary libraries installed. Specifically, we’ll need openpyxl. If you don’t have it installed, you can do so by running the following command in your command line or terminal:
1 |
pip install openpyxl |
Step 2: Importing Required Libraries
We’ll need to import the openpyxl library. Additionally, we also need some specific modules from openpyxl that help in defining the border style.
1 2 |
from openpyxl import Workbook from openpyxl.styles import Border, Side |
Step 3: Creating Workbook and Worksheet
Let’s first create an Excel workbook and then a worksheet within it:
1 2 |
wb = Workbook() ws = wb.active # active chooses the default 'Sheet' |
Step 4: Defining the Border
We use the Border and Side modules here to define the side style and create a border. You can modify the line style and color as per your needs.
1 2 3 4 5 6 |
thin_border = Border( left=Side(style='thin', color='000000'), right=Side(style='thin', color='000000'), top=Side(style='thin', color='000000'), bottom=Side(style='thin', color='000000') ) |
Step 5: Applying Border to Cells
Let’s add some data to our worksheet and apply the defined border:
1 2 3 4 5 |
for row in range(1,6): for col in range(1,4): cell = ws.cell(row, col) cell.value = 'Test' cell.border = thin_border |
Step 6: Save the Workbook
Finally, save the workbook. If it’s saved successfully, you should see the file in your current directory.
1 |
wb.save("bordered_excel_file.xlsx") |
The Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
from openpyxl import Workbook from openpyxl.styles import Border, Side wb = Workbook() ws = wb.active thin_border = Border( left=Side(style='thin', color='000000'), right=Side(style='thin', color='000000'), top=Side(style='thin', color='000000'), bottom=Side(style='thin', color='000000') ) for row in range(1,6): for col in range(1,4): cell = ws.cell(row, col) cell.value = 'Test' cell.border = thin_border wb.save("bordered_excel_file.xlsx") |
Conclusion
In this tutorial, we learned about openpyxl, a Python library to manipulate Excel documents. We created a border within Excel cells by using the Border and Side objects of the openpyxl library.
The primary purpose was to understand the use of Python in automating Excel-related tasks. Continue your learning journey of Python; explore and discover more every day.