使用 openpyxl 将图像插入 Excel

Insert an image into Excel with openpyxl

我的 PC 崩溃了,所以我不得不重新安装所有的库;完成安装后,我意识到一些库更新到新版本并且我的代码不再有效(由于新版本的 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'

有趣的东西。显然,在我拥有的任何版本的 openpyxl 和我现在拥有的版本 (2.5.5) 之间,img.anchor 改变了类型。它现在是一个字符串而不是工作表位置,因此您只需将它设置为位置(在我的例子中:'D2')而不是工作表位置(不要使用 ws['D2'] ).综上所述,当尝试使用 openpyxl 2.5.5 插入图像时,请使用以下内容:

import openpyxl
wb = openpyxl.load_workbook(filename)
ws = wb[sheet_name]
img = openpyxl.drawing.image.Image(img_name)
img.anchor = 'D2' # Or whatever cell location you want to use.
ws.add_image(img)
wb.save(filename)