简体   繁体   中英

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)

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.

ws.merged_cells would return a list contains all the merged cells' location, such as this:

In [6]: mgs = ws.merged_cells

In [7]: mgs
Out[7]: <MultiCellRange [B1:C1 D1:J1 K1:L1 M1:N1]>

In [8]: for ms in mgs:
   ...:     print(ms)
   ...:
B1:C1
D1:J1
K1:L1
M1:N1

If you want to set a new value to a merged cell, you have to unmerge it first, then change the value of the first sub-cell, finally merge them again. A full example:

In [1]: import openpyxl

In [2]: wb = openpyxl.load_workbook('demo.xlsx')

In [3]: ws = wb.active

In [4]: m_cells = ws.merged_cells

In [5]: m_cells
Out[5]: <MultiCellRange [B1:C1 D1:J1 K1:L1 M1:N1]>

In [6]: coo = m_cells.ranges[0].coord

In [7]: coo
Out[7]: 'B1:C1'

In [8]: ws.unmerge_cells(coo)

In [9]: ws['B1'] = 'New Value'

In [10]: ws.merge_cells(coo)

Additional info:

ws.merged_cells would return a MultiCellRange type object but not a list, you should use .ranges attribute to get a list that contains CellRange type object.

The CellRange type object could not be used in ws.unmerge_cells() , you have to use .coord attribute to get the str type which ws.unmerge_cells(str) could calls.

A wrapped function

def mod_cell(merged_cell, new_value):
    """
    Set new value to a merged_cell
    :param merged_cell: Merged cell to modify, ws.merged_cells.ranges[x]
    :param new_value: New value
    :return:
    """
    # Unmerge
    coo = merged_cell.coord
    ws.unmerge_cells(coo)
    # Set new value to the first sub-cell
    first_cell = ws.cell(row=merged_cell.left[0][0], column=merged_cell.left[0][1])
    first_cell.value = new_value
    # Merge again
    ws.merge_cells(coo)

If you are open to using another excel library, your issue is not encountered with xlwings which lets Python control excel. Differences between xlwings vs openpyxl Reading Excel Workbooks . Note xlwings requires Excel to be installed on your machine while openpyxl does not.

The below sets the value of already merged cell A1 with no problems.

import xlwings as xw

wb = xw.Book('myproject.xlsm')
sh = wb.sheets[0]
sh.range('A1').value = 'hello'

Result:

在此处输入图片说明

I had this exact error and solution for conda environment within python3.5 was

conda install -c conda-forge openpyxl=2.5.14 -y

Similarly for pip3 environments:

pip3 install openpyxl==2.5.14 -y

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM