Last modified: Nov 16, 2025 By Alexander Williams
Excel Borders Fills Alignment Python openpyxl Guide
Excel formatting makes spreadsheets readable and professional. Python openpyxl automates this process. This guide covers borders, fills, and alignment.
Getting Started with openpyxl
First, install openpyxl using pip. Then import the necessary modules. Create or load a workbook to begin formatting.
# Install openpyxl if not already installed
# pip install openpyxl
from openpyxl import Workbook
from openpyxl.styles import Border, Side, PatternFill, Alignment
# Create a new workbook
wb = Workbook()
ws = wb.active
ws.title = "Formatting Demo"
Applying Cell Borders
Borders define cell boundaries. They make data tables clear. openpyxl offers various border styles and positions.
Use the Side class to define border style. Then apply it using the Border class. Finally assign to cell borders.
# Define border styles
thin_border = Side(border_style="thin", color="000000")
thick_border = Side(border_style="thick", color="FF0000")
# Create border objects
cell_border = Border(left=thin_border, right=thin_border,
top=thin_border, bottom=thin_border)
header_border = Border(bottom=thick_border)
# Apply borders to cells
ws['A1'].value = "Product"
ws['B1'].value = "Price"
ws['A1'].border = header_border
ws['B1'].border = header_border
# Apply complete border to data cells
for row in ws['A2:B5']:
for cell in row:
cell.border = cell_border
wb.save("borders_demo.xlsx")
Working with Cell Fills
Cell fills add background colors. They highlight important data. Use PatternFill for solid colors and patterns.
Fills make headers stand out. They differentiate data sections. Choose colors that enhance readability.
# Define fill patterns
header_fill = PatternFill(start_color="366092", end_color="366092",
fill_type="solid")
highlight_fill = PatternFill(start_color="FFFF00", end_color="FFFF00",
fill_type="solid")
# Apply fills to cells
ws['A1'].fill = header_fill
ws['B1'].fill = header_fill
# Highlight specific cells
ws['A3'].value = "Special Offer"
ws['A3'].fill = highlight_fill
wb.save("fills_demo.xlsx")
Controlling Cell Alignment
Alignment positions content within cells. It affects text orientation and wrapping. Proper alignment improves spreadsheet layout.
The Alignment class handles text positioning. Control horizontal and vertical alignment. Manage text wrapping and rotation.
# Define alignment options
center_align = Alignment(horizontal="center", vertical="center")
wrap_align = Alignment(wrap_text=True)
right_align = Alignment(horizontal="right")
# Apply alignments
ws['A1'].alignment = center_align
ws['A2'].value = "This is a long text that will wrap in the cell"
ws['A2'].alignment = wrap_align
ws['B2'].value = 99.99
ws['B2'].alignment = right_align
# Adjust column width for wrapped text
ws.column_dimensions['A'].width = 20
ws.row_dimensions[2].height = 40
wb.save("alignment_demo.xlsx")
Complete Formatting Example
Combine borders, fills, and alignment. Create professional-looking reports. This example shows comprehensive formatting.
from openpyxl import Workbook
from openpyxl.styles import Border, Side, PatternFill, Alignment, Font
wb = Workbook()
ws = wb.active
# Define styles
header_fill = PatternFill(start_color="4F81BD", fill_type="solid")
data_fill = PatternFill(start_color="DCE6F1", fill_type="solid")
border_style = Side(border_style="thin")
cell_border = Border(left=border_style, right=border_style,
top=border_style, bottom=border_style)
center_align = Alignment(horizontal="center", vertical="center")
# Create header row
headers = ["Product", "Category", "Price", "Stock"]
for col, header in enumerate(headers, 1):
cell = ws.cell(row=1, column=col)
cell.value = header
cell.fill = header_fill
cell.border = cell_border
cell.alignment = center_align
cell.font = Font(color="FFFFFF", bold=True)
# Add sample data
data = [
["Laptop", "Electronics", 999.99, 15],
["Mouse", "Electronics", 25.50, 42],
["Notebook", "Office", 5.99, 100]
]
for row_num, row_data in enumerate(data, 2):
for col_num, value in enumerate(row_data, 1):
cell = ws.cell(row=row_num, column=col_num)
cell.value = value
cell.border = cell_border
if row_num % 2 == 0: # Alternate row colors
cell.fill = data_fill
if col_num in [3, 4]: # Right-align numeric columns
cell.alignment = Alignment(horizontal="right")
# Auto-adjust column widths
for column in ws.columns:
max_length = 0
column_letter = column[0].column_letter
for cell in column:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
adjusted_width = (max_length + 2)
ws.column_dimensions[column_letter].width = adjusted_width
wb.save("complete_formatting.xlsx")
Advanced Formatting Techniques
Combine formatting with other openpyxl features. Create dynamic reports. Apply conditional formatting programmatically.
Use loops to format large datasets. Apply styles based on cell values. Create professional templates automatically.
For more advanced Excel operations, see our guide on Advanced Number Formatting Python openpyxl Guide. It covers currency, percentages, and custom formats.
Best Practices
Keep formatting consistent across sheets. Use color schemes that are accessible. Test your formatted files in Excel.
Consider performance when formatting large files. Our Handle Large Excel Files Efficiently Python openpyxl guide offers optimization tips.
Combine formatting with other features like Set Column Widths Row Heights Python openpyxl for complete control over spreadsheet appearance.
Common Issues and Solutions
Formatted files might be large. Optimize by reusing style objects. This reduces memory usage significantly.
Colors may appear different in Excel. Test color codes in both applications. Ensure consistency across platforms.
Borders might not apply correctly. Check that all border sides are defined. Verify the border style names are correct.
Conclusion
Python openpyxl provides powerful formatting capabilities. Borders, fills, and alignment create professional spreadsheets. Automate your Excel reporting with confidence.
Start with basic formatting. Gradually incorporate advanced techniques. Your automated Excel files will look professionally designed.
Remember to combine formatting with other openpyxl features. Create comprehensive Excel solutions. Streamline your data reporting workflow effectively.