Adding Images
Here are resources for more information about Pillow:
00:00 While it’s not super common, images are sometimes needed in spreadsheets that you will produce to include something like a company header, a product, or something similar.
00:09
Fortunately, openpyxl
will let you add images, and it’s a relatively straightforward process. You will need to install another library, Pillow
, however, to process the image with Python. So, inside your environment, go ahead and pip install Pillow
.
00:25
I’ve included an image in the resources (Supporting Material) for this course called rp.png
, which is just the Real Python logo. Feel free to use that or any image that you have available. To do this, I’m going to make a new file called openpyxl_image.py
.
00:47
I’m going to do an import. So, from openpyxl import load_workbook
, and then you’re going to from openpyxl.drawing.image
import Image
. Make sure that Image
is capitalized.
01:01
Okay. And what should feel pretty familiar now is you’re going to define a workbook
—that’s going to be load_workbook()
. And for this one, go ahead and use the "hello_world.xlsx"
spreadsheet. Then, say sheet
is the active sheet off of that. All right, so now you can say something like logo = Image()
and then pass in the filename. In this case, it’ll be "rp.png"
.
01:26
To make sure this doesn’t take over the whole spreadsheet, you can set some properties. Say the logo.height
is going to be 150
and the logo.width
—also set that to 150
. All right.
01:38
Now, you have your worksheet and you can .add_image()
, pass in the image and where you want it to go. And in our case, because you already have data in A1 and B1, go ahead and put this in "A3"
.
01:51
Take the workbook and save it and pass in a filename
. You could do something like "hello_world_logo.xlsx"
. Save this, and run it again.
02:03
So, going into the directory, open up the new hello_world_logo.xlsx
. All right. Let’s see what we get. And yeah! Look at that. hello world! is still in A1 and B1, and starting in A3 is a logo.
02:17
So, good job! That’s all there is adding images to your worksheets. In the next video, you’re going to see how to add charts, which can really help automate reporting when using openpyxl
.
Become a Member to join the conversation.
sjoerd on March 29, 2021
Hello Joe, This was a good explanation of inserting an image. I am now trying to find if there is an option to adapt the cell-size to the set image-size, so that when I put an image in F3 that the image fills up the dimension of the cell and not overlaps with other cells. Is this possible? I haven’t been able to find it yet.