Python openpyxl – Add image to spreadsheet

In this post we will be creating a Python script that will add an image to an existing Excel spreadsheet using the openpyxl library. Openpyxl is a library that allows us to interact with Excel files in Python. It provides a range of tools for reading, writing, manipulating, and formatting Excel data. This makes it a useful tool for data analysis and reporting tasks.

See the sample of Python code below where we use the openpyxl library to add an image to an already existing Excel spreadsheet. We start by loading our existing Excel file called example.xlsx and assign it to a variable named workbook. Next we retrieve the active worksheet from the workbook. Now we create an Image object from the image file named ‘image.png’. The add_image method is called on the worksheet object, this takes two arguments. The first argument is our Image object and the second is the cell where the top-left corner of the image should be placed. Finally the changes made to the Excel file are saved using the save() method.

import openpyxl
from openpyxl.drawing.image import Image

workbook = openpyxl.load_workbook('example.xlsx')

worksheet = workbook.active

img = Image('image.png')
worksheet.add_image(img, 'C3')

workbook.save('example.xlsx')

See an image of our spreadsheet below.

Python openpyxl - Add image to spreadsheet

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply