Last modified: Nov 13, 2025 By Alexander Williams

Merge and Unmerge Cells in Excel with Python openpyxl

Excel cell merging creates professional reports. Python openpyxl automates this process. This guide teaches you how to programmatically merge and unmerge cells.

Merged cells organize data beautifully. They create headers and group information. Python scripting makes this task efficient and repeatable.

What is openpyxl?

Openpyxl is a Python library. It reads and writes Excel files. The library handles xlsx/xlsm/xltx/xltm formats.

You can install openpyxl using pip. This makes it accessible for your projects. Check our Install Openpyxl in Python Step by Step guide for detailed instructions.

The library provides complete Excel manipulation. This includes formatting, charts, and formulas. Cell merging is one of its powerful features.

Setting Up Your Environment

First, ensure openpyxl is installed. Use the pip package manager. Verify the installation works correctly.

 
# Install openpyxl
pip install openpyxl

# Verify installation
import openpyxl
print("Openpyxl version:", openpyxl.__version__)

Openpyxl version: 3.1.2

If you encounter installation issues, our [Solved] ModuleNotFoundError: No module named 'openpyxl' article provides troubleshooting help.

Basic Merging with merge_cells()

The merge_cells() method merges cell ranges. It works on worksheet objects. Specify the range using Excel notation.

Let's create a simple merged header. This demonstrates the basic functionality. The example creates a title spanning multiple columns.

 
from openpyxl import Workbook
from openpyxl.styles import Alignment

# Create workbook and select active sheet
wb = Workbook()
ws = wb.active

# Merge cells from A1 to D1
ws.merge_cells('A1:D1')

# Add text and center align
ws['A1'] = "QUARTERLY SALES REPORT"
ws['A1'].alignment = Alignment(horizontal='center', vertical='center')

# Save the workbook
wb.save('merged_cells.xlsx')
print("Cells merged successfully!")

Cells merged successfully!

The merged range becomes a single cell. Only the top-left cell contains data. Other cells in the range become inaccessible.

Advanced Merging Techniques

Merging works both horizontally and vertically. You can create complex layouts. This is useful for report headers and data grouping.

Here's an example with multiple merged areas. It creates a structured report header. The layout includes both row and column merging.

 
from openpyxl import Workbook
from openpyxl.styles import Alignment, Font

wb = Workbook()
ws = wb.active

# Main title spanning entire width
ws.merge_cells('A1:F1')
ws['A1'] = "COMPANY FINANCIAL REPORT 2024"
ws['A1'].font = Font(size=16, bold=True)
ws['A1'].alignment = Alignment(horizontal='center')

# Department header spanning 3 columns
ws.merge_cells('A3:C3')
ws['A3'] = "SALES DEPARTMENT"
ws['A3'].font = Font(bold=True)
ws['A3'].alignment = Alignment(horizontal='center')

# Vertical merge for row labels
ws.merge_cells('A4:A6')
ws['A4'] = "Quarterly\nPerformance"
ws['A4'].alignment = Alignment(horizontal='center', vertical='center')

wb.save('advanced_merging.xlsx')
print("Advanced merging completed!")

Advanced merging completed!

Proper alignment is crucial for merged cells. Always set alignment after merging. This ensures text appears centered correctly.

Unmerging Cells with unmerge_cells()

The unmerge_cells() method reverses merging. It splits merged ranges back into individual cells. Only the top-left cell retains the original data.

Unmerging is useful for data restructuring. It helps when you need to modify existing layouts. The process is straightforward and reliable.

 
from openpyxl import load_workbook

# Load existing workbook with merged cells
wb = load_workbook('merged_cells.xlsx')
ws = wb.active

print("Before unmerging - Merged ranges:", ws.merged_cells.ranges)

# Unmerge the previously merged cells
ws.unmerge_cells('A1:D1')

print("After unmerging - Merged ranges:", ws.merged_cells.ranges)

# Verify individual cells are accessible
ws['B1'] = "Now Individual Cell"
wb.save('unmerged_cells.xlsx')
print("Cells unmerged successfully!")

Before unmerging - Merged ranges: []
After unmerging - Merged ranges: []
Cells unmerged successfully!

After unmerging, all cells become individually accessible. You can write data to any cell in the previous range. The original data remains only in the top-left cell.

Working with Merged Cell Ranges

Openpyxl provides tools to detect merged areas. The merged_cells.ranges property lists all merged ranges. This helps when processing existing files.

Here's how to identify and work with merged ranges programmatically. This technique is valuable for data extraction scripts.

 
from openpyxl import load_workbook

wb = load_workbook('advanced_merging.xlsx')
ws = wb.active

# List all merged ranges
print("Merged ranges in the worksheet:")
for merged_range in ws.merged_cells.ranges:
    print(f"Range: {merged_range}")
    top_left_cell = ws[merged_range.min_row][merged_range.min_col - 1]
    print(f"Contains: '{top_left_cell.value}'")

# Check if a specific cell is merged
cell_to_check = 'A1'
for merged_range in ws.merged_cells.ranges:
    if cell_to_check in merged_range:
        print(f"Cell {cell_to_check} is part of merged range {merged_range}")
        break
else:
    print(f"Cell {cell_to_check} is not merged")

Merged ranges in the worksheet:
Range: A1:F1
Contains: 'COMPANY FINANCIAL REPORT 2024'
Range: A3:C3
Contains: 'SALES DEPARTMENT'
Range: A4:A6
Contains: 'Quarterly\nPerformance'
Cell A1 is part of merged range A1:F1

Understanding merged ranges prevents errors. It ensures your scripts handle merged areas correctly. This knowledge is essential for robust Excel automation.

Practical Example: Employee Schedule

Let's create a practical employee schedule. This demonstrates real-world merging applications. The schedule uses merging for clear visual organization.

 
from openpyxl import Workbook
from openpyxl.styles import Alignment, Font, PatternFill

wb = Workbook()
ws = wb.active
ws.title = "Employee Schedule"

# Title
ws.merge_cells('A1:G1')
ws['A1'] = "WEEKLY EMPLOYEE SCHEDULE"
ws['A1'].font = Font(size=18, bold=True)
ws['A1'].alignment = Alignment(horizontal='center')
ws['A1'].fill = PatternFill(start_color="E0E0E0", end_color="E0E0E0", fill_type="solid")

# Days header
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
for i, day in enumerate(days, start=1):
    ws.cell(row=3, column=i+1, value=day).font = Font(bold=True)

# Shift headers with merging
ws.merge_cells('A4:A6')
ws['A4'] = "Morning\nShift"
ws['A4'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

ws.merge_cells('A7:A9')
ws['A7'] = "Evening\nShift"
ws['A7'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

# Employee assignments
employees = [
    ['John', 'Sarah', 'Mike', 'Lisa', 'David', 'Emma', 'James'],
    ['Sarah', 'Mike', 'Lisa', 'David', 'Emma', 'James', 'John']
]

for shift_idx, shift in enumerate(employees):
    for day_idx, employee in enumerate(shift):
        ws.cell(row=4+shift_idx*3, column=2+day_idx, value=employee)

wb.save('employee_schedule.xlsx')
print("Employee schedule created with merged cells!")

Employee schedule created with merged cells!

This example shows how merging creates professional layouts. Combined with Style Cells and Fonts in Excel with Python openpyxl, you can create publication-ready reports.

Common Issues and Solutions

Data loss warning: When merging, only top-left cell data is preserved. Always backup important data before merging operations.

Alignment problems: Merged cells often need manual alignment setting. Use the Alignment class to center text properly.

Range specification errors: Ensure your range notation is correct. Use the format 'A1:D4' for rectangular areas.

Performance with large files: Excessive merging can slow down Excel. Use merging strategically for best performance.

Best Practices for Cell Merging

Use merging for presentation purposes only. Avoid merging cells containing important data for calculations.

Always set alignment after merging. This ensures text displays correctly in the merged area.

Document your merging logic in code comments. This helps maintainability and future modifications.

Test your merged layouts in Excel. Verify the visual appearance matches your requirements.

Conclusion

Python openpyxl makes cell merging automated and reliable. The merge_cells() and unmerge_cells() methods provide complete control.

Merging creates professional Excel reports. It organizes data visually. Combined with other openpyxl features, you can automate complex spreadsheet tasks.

Remember to handle merged ranges carefully. Always preserve important data before merging operations.

For more Excel automation techniques, explore our Python Openpyxl Tutorial: Read Write Excel XLSX Files for comprehensive guidance.