Insert an image into Excel with openpyxl

烂漫一生 提交于 2021-02-07 20:19:24

问题


My PC crashed and so I had to reinstall all of my libraries; after finishing the install, I realized that some libraries updated to a new version and my code no longer works (due to a new version of openpyxl).

I am trying to insert an image into an Excel file, but I do not understand the error messages that are occurring. Other questions seem to be for older versions of openpyxl (for which my original code worked), but do not work for the current version of openpyxl. Your assistance in helping me understand how to fix my code is appreciated. :)

Original code (which works):

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)

Current code (which doesn't work):

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)

Error message:

---------------------------------------------------------------------------
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

Any hints?

Thanks

EDIT: Apparently, img.anchor is now the string; I have no idea what it used to be but apparently was not a string (since there wasn't an error message. Changing to the following now sets the anchor, but I get a different error message.

Sets anchor:

img.anchor = ws.cell(row=2,column=4)
ws.add_image(img)

But it now crashes when trying to save:

---------------------------------------------------------------------------
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:


Fun stuff. Apparently, between whatever version of openpyxl I had and the one I have now (2.5.5), img.anchor changed types. It is now a string instead of a worksheet location, so you need to simply set it to the location (in my case: 'D2') instead of the worksheet location (DON'T USE ws['D2']). To sum up, when trying to insert an image with openpyxl 2.5.5, use the following:

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)


来源:https://stackoverflow.com/questions/51953494/insert-an-image-into-excel-with-openpyxl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!