Insert image in openpyxl

Is it possible to insert an image (jpeg, png, etc.) using openpyxl?

Basically, I want to place the generated image with a diagram below it.

I don't see anything in the documentation, which seems to be a bit missing compared to code maturity.

+16
source share
5 answers

The following inserts the image into cell A1. Adjust the location of the image according to your needs or process the creation of the PIL image yourself and pass it Image()

 import openpyxl wb = 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 openpyxl wb = 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') 
+17
source

In current versions of openpyxl (at least prior to 2.4.5) you need to call Image as follows:

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

Using the Anthon example:

 import openpyxl wb = 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') 
+10
source

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

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

 import openpyxl from openpyxl import load_workbook from openpyxl import Workbook from openpyxl.drawing.image import Image from openpyxl.utils import coordinate_from_string openpyxl_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 image png_loc = r'c:\users\me\opengraph-icon-200x200.png' # test.xlsx already exists in my current directory wb = load_workbook('test.xlsx') ws = wb.active my_png = openpyxl.drawing.image.Image(png_loc) ws.add_image(my_png, 'B3') wb.save('test.xlsx') 

Results:

enter image description here

+5
source

This code worked for me:

 import openpyxl wb = openpyxl.Workbook() ws = wb.worksheets[0] ws.merge_cells('A1:A3') img = openpyxl.drawing.image.Image('image.jpg') row_number = 1 col_idx = 1 cell = ws.cell(row=row_number, column=col_idx) ws.add_image(img) wb.save('output.xlsx') 
+1
source

To add, I used openpyxl == 2.5.6 (with Python3.65), and I had to use img.anchor('A1') instead of img.anchor(ws.cell('A1')) .

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

All Articles