Insert image in openpyxl Insert image in openpyxl python python

Insert image in openpyxl


The following inserts an image in cell A1. Adjust the image location to your needs or handle the creation of the PIL image yourself and hand that to Image()

import openpyxlwb = openpyxl.Workbook()ws = wb.worksheets[0]img = openpyxl.drawing.image.Image('test.jpg')img.anchor = 'A1'ws.add_image(img)wb.save('out.xlsx')

In older versions of openpyxl the following works:

import openpyxlwb = openpyxl.Workbook()ws = wb.worksheets[0]img = openpyxl.drawing.Image('test.jpg')img.anchor(ws.cell('A1'))ws.add_image(img)wb.save('out.xlsx')


In current versions of openpyxl (up to 2.4.5 at least) you have to call Image like this:

img = openpyxl.drawing.image.Image('test.jpg')

Using Anthon's example:

import openpyxlwb = openpyxl.Workbook()ws = wb.worksheets[0]img = openpyxl.drawing.image.Image('test.jpg')img.anchor(ws.cell('A1'))ws.add_image(img)wb.save('out.xlsx')


Providing a full update on how to do this. This solution uses openpyxl version 2.4.5.

I downloaded an image to my local directory, opened an existing workbook and saved with the image inserted.

import openpyxlfrom openpyxl import load_workbookfrom openpyxl import Workbookfrom openpyxl.drawing.image import Imagefrom openpyxl.utils import coordinate_from_stringopenpyxl_version = openpyxl.__version__print(openpyxl_version)  #to see what version I'm running# downloaded a .png to local directory manually from# "https://www.python.org/static/opengraph-icon-200x200.png"#change to the location and name of your imagepng_loc = r'c:\users\me\opengraph-icon-200x200.png'# test.xlsx already exists in my current directory wb = load_workbook('test.xlsx')ws = wb.activemy_png = openpyxl.drawing.image.Image(png_loc)ws.add_image(my_png, 'B3')wb.save('test.xlsx')

Results:

enter image description here