Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 962
zumber Avatar asked Oct 16 '22 07:10

zumber


1 Answers

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.

like image 83
imujjwalanand Avatar answered Oct 21 '22 00:10

imujjwalanand