How to add PIL images to Excel sheet using Pandas?

Viewed 777

I have a list of PIL images, which look like this

[
 <PIL.Image.Image image mode=RGBA size=695x500 at 0x1E7275D2DF0>,
 <PIL.Image.Image image mode=RGBA size=695x500 at 0x1E7275F8970>,
 <PIL.Image.Image image mode=RGBA size=695x500 at 0x1E729B7A490>
]

And I'd like to take each PIL.Image from the list and add it to the excel file as the original image using Pandas. Is that possible?

Current output is:

enter image description here

What I want is the PIL.image replaced with the actual image.

1 Answers

As pointed out in the comments, you need an engine to do this, such as openpyxl or xlswriter, and store your PIL images in your working directory, so that you can insert them to an excel file (as a .png, for example).

Install xlswriter in your environment. For instance, pip install xlswriter and then you can do something like this:

import pandas as pd
from PIL import Image

images = [Image.new('RGB', (200, 200)) for _ in range(3)] # 3 empty PIL images

writer = pd.ExcelWriter('excel_file.xlsx', engine='xlsxwriter')
workbook  = writer.book
worksheet = workbook.add_worksheet()

for i, image in enumerate(images):
    image.save(f"img_{i}.png", "PNG") # Save your image before inserting
    worksheet.insert_image(0, 6*i, f"img_{i}.png")
    
writer.save()

You'd have to change 0, 6*i to an appropriate row, column pair depending on where you want them to be, and so they don't overlap.

Related