'openpyxl: AttributeError: 'MergedCell' object attribute 'value' is read-only
When i'm trying to fill the cell in existing .xlsx file and then save it to a new one I got message:
import openpyxl
path = "/home/karol/Dokumenty/wzor.xlsx"
wb_obj = openpyxl.load_workbook(path)
sheet_obj = wb_obj.active
new_protokol = sheet_obj
firma = input("Podaj nazwe: ")
nazwa_pliku = "Protokol odczytu"
filename = nazwa_pliku + firma + ".xlsx"
sheet_obj["C1"] = firma
sheet_obj["D1"] = input()
new_protokol.save(filename=filename)
Traceback (most recent call last):
File "/home/karol/PycharmProjects/Protokolu/Main.py", line 16, in <module>
sheet_obj["C1"] = firma
File "/home/karol/PycharmProjects/Protokolu/venv/lib/python3.7/site-packages/openpyxl/worksheet/worksheet.py", line 309, in __setitem__
self[key].value = value
AttributeError: 'MergedCell' object attribute 'value' is read-only
Process finished with exit code 1
How to fix it?
Solution 1:[1]
When you merge cells all cells but the top-left one are removed from the worksheet. To carry the border-information of the merged cell, the boundary cells of the merged cell are created as MergeCells which always have the value 'None'
ws.merge_cells('B2:F4')
top_left_cell = ws['B2']
top_left_cell.value = "My Cell"
Please try this approach, it'll work just fine for you.
Solution 2:[2]
To write in a merge cell, you must write in the cell in the upper left corner. And the error will not come out.
ws['I6']="123123123"
wb.save(filename=path....)
Solution 3:[3]
I also met this error. I deleted my current Excel file and replaced it with a good Excel file, and then the error disappeared.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | imujjwalanand |
Solution 2 | Michael Heil |
Solution 3 | Melanie Lee |