Python Write Excel xlsx File with Merged Cells using OpenPyXL

In this Python openpyxl tutorial we learn how to write Excel xlsx files with merged cells using the openpyxl package.

How to install the openpyxl package

To install the openpyxl package using the command below.

pip install openpyxl

How to write Excel xlsx file with merged cells

Import the Workbook from the openpyxl package.

from openpyxl import Workbook

Create a new Workbook object.

wb = Workbook()

Get the default active Worksheet object.

ws = wb.active

Merge cells from B2 to D2.

ws.merge_cells('B2:D2')

Assign value for the merged cell.

ws['B2'] = 'Tori Code'

Save the Workbook as merge_cells.xlsx file.

wb.save('merge_cells.xlsx')

The complete Python program as below.

write_excel_file_merge_cells.py

from openpyxl import Workbook

wb = Workbook()

ws = wb.active

ws.merge_cells('B2:D2')

ws['B2'] = 'Tori Code'

wb.save('merge_cells.xlsx')

Execute the above Python program we will get the Excel file merge_cells.xlsx as below screenshot.

Python Write Excel xlsx File with Merged Cells using openpyxl

Happy Coding 😊