how to create borders in excel by python

databicky
Contributor II

how to create borders in excel by python like the following format.

in the ex column if i entered the value as data means it should be center between those rows.​

Anonymous
Not applicable

@Mohammed sadamusean​ :

You can use the openpyxl library in Python to create borders in Excel. Here is an example code snippet that creates a border around a range of cells and centers the text in a specific column:

import openpyxl
from openpyxl.styles import Border, Side, Alignment
 
# Load the Excel workbook
wb = openpyxl.load_workbook('example.xlsx')
 
# Select the worksheet
ws = wb.active
 
# Create a border for the range of cells A1:C5
border = Border(left=Side(style='thin'), 
                right=Side(style='thin'), 
                top=Side(style='thin'), 
                bottom=Side(style='thin'))
 
for row in range(1, 6):
    for col in range(1, 4):
        cell = ws.cell(row=row, column=col)
        cell.border = border
        
# Center align the values in column E
for row in range(1, 6):
    cell = ws.cell(row=row, column=5)
    cell.alignment = Alignment(horizontal='center')
 
# Save the workbook
wb.save('example.xlsx')

In this example, we load an existing workbook, select the active worksheet, create a border for the range of cells A1:C5, and center align the values in column E. Finally, we save the workbook.