How to write in merged cell in Excel using `openpyxl` library?

Submitted 3 years, 7 months ago
Ticket #167
Views 4378
Language/Framework Python
Priority Low
Status Closed

I am using openpyxl library to write in existing Excel file in separate cells.

How do I write some text in Excel merged cell?

ERROR AttributeError: 'MergedCell' object attribute 'value' is read-only

when cells are merged:

CODE:

wb = openpyxl.load_workbook(filename=src)
        for row in df_short.itertuples():
            ws = wb[row.sheet]
            try:
                cell = 'N'+str(row.id)
                ws[cell] = '=HYPERLINK("%s","#%s")' % (row.txt_path, row.txt)
Submitted on Sep 13, 20
add a comment

1 Answer

Verified

import time
from openpyxl import Workbook
from openpyxl.styles import Alignment

book = Workbook()
sheet = book.active

sheet['A1'] = 56
sheet['A2'] = 43

now = time.strftime("%x")
sheet['A3'] = now

sheet.merge_cells('A1:B2')

cell = sheet.cell(row=1, column=1)
cell.value = 'Be Awesome'
cell.alignment = Alignment(horizontal='center', vertical='center')


book.save("sample1.xlsx")

Submitted 3 years, 6 months ago


Latest Blogs