本文介绍了openpyxl: AttributeError: 'MergedCell' 对象属性 'value' 是只读的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试在现有 .xlsx 文件中填充单元格,然后将其保存到一个新文件时,我收到消息:

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

如何解决?

推荐答案

当您合并单元格时,除左上角的所有单元格都将从工作​​表中删除.为了携带合并单元格的边界信息,合并单元格的边界单元格被创建为MergeCells,其值总是'None'

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.

这篇关于openpyxl: AttributeError: 'MergedCell' 对象属性 'value' 是只读的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 11:52