Insert an image into Excel with openpyxl

kjsfld picture kjsfld · Aug 21, 2018 · Viewed 7.9k times · Source

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'

Answer

kjsfld picture kjsfld · Aug 21, 2018

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)