Insert Image in Excel sheet by openpyxl

By using openpyxl.drawing.image module, you may insert images to the Excel sheet using Python programs.

How to insert an image in an Excel sheet by openpyxl library

By using openpyxl.drawing.image module, you may insert images to the Excel sheet using Python programs.

The image path is specified in the image attribute and add_image attribute of the sheet object is used to add an image to the specified cell.

See the examples below for better understanding.

An example to insert image in C5 cell

We will insert a logo file in .png format into a sheet.

Python program:

Result:

openpyxl-image-sheet

As you execute this program, it may produce the following error:

“ImportError: You must install Pillow to fetch image objects”

You may install the Pillow by using this command:

pip install pillow

How did it work?

  • We included the openpyxl library
  • We also imported the Image from openpyxl.drawing.image
  • A workbook object is created and an active sheet is specified.
  • Then we assigned the image path (located in the same directory where the Python code file is located).
  • This is followed by using the add_image attribute of the sheet object where we specified the image and cell (C5).
  • Saved the workbook.

Setting the height and width of image

You may also set the image size by using the height and width of the image.

See the example where we used the same image as above except its size is changed:

Output:

openpyxl-image-size

Placing image based on x and y coordinates

Rather than placing the image in a cell, you may place an image based on horizontal and vertical positions.

In the example below, we will place the image by specifying:

  • Horizontal distance (x) = 100
  • Vertical distance (y) = 10

You can change the number as per need.

The code:

Output:

openpyxl-image-emu

 

This solution is courtesy of an answer in Stack Overflow.