使用openpyxl将图像插入Excel

时间:2018-08-21 16:59:25

标签: python-3.x openpyxl insert-image

我的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'

1 个答案:

答案 0 :(得分:0)

好玩的东西。显然,在我拥有的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)