我的电脑崩溃了,所以我不得不重新安装我所有的库;完成安装后,我意识到一些库更新到了新版本,我的代码不再有效(由于 openpyxl 的新版本)。
我正在尝试将图像插入 Excel 文件,但我不明白正在发生的错误消息。其他问题似乎是针对旧版本的 openpyxl(我的原始代码适用),但不适用于当前版本的 openpyxl。感谢您帮助我了解如何修复我的代码。:)
原始代码(有效):
import openpyxl
wb = openpyxl.load_workbook(filename)
ws = wb.get_sheet_by_name(sheet_name)
img = openpyxl.drawing.image.Image(img_name)
img.anchor(ws['D2'])
ws.add_image(img)
wb.save(filename)
当前代码(不起作用):
import openpyxl
wb = openpyxl.load_workbook(filename)
ws = wb[sheet_name]
img = openpyxl.drawing.image.Image(img_name)
img.anchor(ws.cell(row=2,column=4))
ws.add_image(img)
wb.save(filename)
错误信息:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-9efc1289cc73> in <module>()
----> 1 img.anchor(ws.cell(row=2,column=4))
TypeError: 'str' object is not callable
有什么提示吗?
谢谢
编辑:显然, img.anchor 现在是字符串;我不知道它曾经是什么,但显然不是字符串(因为没有错误消息。更改为以下内容现在设置了锚点,但我收到了不同的错误消息。
设置锚点:
img.anchor = ws.cell(row=2,column=4)
ws.add_image(img)
但它现在在尝试保存时崩溃:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-13-2cfd938ccf60> in <module>()
1 img.anchor = ws.cell(row=2,column=4)
2 ws.add_image(img)
----> 3 wb.save(filename)
AttributeError: 'Cell' object has no attribute 'upper'