Home » excel » python – resize excel cell to fit an image

python – resize excel cell to fit an image

Posted by: admin May 14, 2020 Leave a comment

Questions:

when I write an image to an excel file, I need to make the image fit one excel cell. I know the size(in pixel) of the image, but I have no idea how to use xlsxwriter to adjust the height and width of the excel cell so that my image fits the cell perfectly.

How to&Answers:

Providing an example of how you could scale down an image using PIL (Python Imaging Library – Link to docs) and then place it in an .xlsx file using xlsxwriter. With this example, you can see how you can adjust the size of your image using PIL and then using worksheet.set_column() and worksheet.set_row() you can adjust the cell size to accomodate the size of your image.

So effectively, you can adjust the size of your image, adjust the size of the excel cell or do both. It might take a little testing to get the right fit.

To make this answer reproducible I used urllib module to download an image to the local directory (that module is not necessary if you’re using a local file).

import urllib.request
from PIL import Image
import xlsxwriter
import os

url = 'https://upload.wikimedia.org/wikipedia/en/thumb/4/43/Ipswich_Town.svg/255px-Ipswich_Town.svg.png'

urllib.request.urlretrieve(url, "local_100_perc.png")

with Image.open("local_100_perc.png") as img:
    width_100 = img.width
    height_100 = img.height

width_30 = int(round(width_100 * 0.3, 0))
img = Image.open('local_100_perc.png')
wpercent = (width_30/float(width_100))
hsize = int((float(height_100)*float(wpercent)))
img = img.resize((width_30,hsize), Image.ANTIALIAS)
img.save('local_30_perc.png') 

workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()
worksheet.set_column('A:B', 10)
worksheet.set_row(1, 70)
worksheet.write('A2', 'Image:')
worksheet.insert_image('B2', 'local_30_perc.png')

workbook.close()

With expected Output:

Expected test.xlsx