Python – Resizes excel cells to fit the image

Resizes excel cells to fit the image… here is a solution to the problem.

Resizes excel cells to fit the image

When I write an image

to an excel file, I need to make the image fit in one excel cell. I know the size of the image in pixels, but I don’t know how to adjust the height and width of excel cells using xlsxwriter so that my image fits perfectly in the cell.

Solution

Provides an example of how to use PIL (Python Image Library – Link to docs Shrink the image and use xlsxwriter to place it in a .xlsx file. With this example, you can learn how to resize an image using PIL, and then use worksheet.set_column() and worksheet.set_row() to resize cells to fit the size of the image.

Very effective, you can resize an image, resize an Excel cell, or both. Some testing may be required to be suitable.

To make this answer reproducible, I downloaded the image to a local directory using the urllib module (which module is not needed if you are 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()

Expected output:

Expected test.xlsx

Related Problems and Solutions