Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 503
Alexander Avatar asked Aug 01 '19 15:08

Alexander


1 Answers

Use the following code where ws is the sheet object.

    ws.cell(cells).value = 'Whatever you want it to be'

replace cells with the top-left cell of the merged block. I usually keep this as rows and columns. So B1 would be represented as row = 1, column = 2.

After the value =

Put any string or integer of what you want to place inside the cell.

like image 64
Anonymous Avatar answered Oct 04 '22 20:10

Anonymous