【问题标题】:Insert an image into Excel with openpyxl使用 openpyxl 将图像插入 Excel
【发布时间】:2018-08-21 16:59:25
【问题描述】:

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

【问题讨论】:

  • 总是值得阅读您正在使用的库版本的文档。

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


【解决方案1】:

有趣的东西。显然,在我拥有的任何版本的 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)

【讨论】:

  • 嘿。尽管这无关紧要,但在保存工作簿时出现以下错误。我想在这里覆盖一个工作簿:File "/home/divij/Desktop/Divij/Personal/Upwork/Hua/venv/lib/python3.6/site-packages/openpyxl/drawing/image.py", line 33, in _import_image img = PILImage.open(img) File "/home/divij/Desktop/Divij/Personal/Upwork/Hua/venv/lib/python3.6/site-packages/PIL/Image.py", line 2638, in open fp.seek(0) ValueError: I/O operation on closed file.
  • 我有同样的行为,我正在编辑一个 excel 文件,当我尝试保存编辑后的文件时出现此错误。
  • 我也可以确认这种行为。最近开始,以前没有发生过。
猜你喜欢
  • 1970-01-01
  • 2017-08-10
  • 2011-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多