DEV Community

Leon Davis
Leon Davis

Posted on

How to Manipulate Images in Excel with Python: Insert, Extract, and Compress

In the realm of automated reporting and data visualization, Excel files often require more than just raw numbers. Incorporating images—such as company logos, product thumbnails, or signature stamps—is essential for creating professional, polished documents. However, manually adjusting images across hundreds of spreadsheets is a tedious, error-prone task.

This article demonstrates how to efficiently manage images in Excel using Python. We will cover the full lifecycle of image management: inserting images into specific cells, extracting them to your local disk, deleting unwanted graphics, and performing advanced manipulations like compression and resizing.

Prerequisites

To get started, ensure you have the Spire.XLS library installed. This tool allows for deep manipulation of Excel documents without requiring Microsoft Office to be installed on your machine.

pip install Spire.XLS
Enter fullscreen mode Exit fullscreen mode

Inserting Images into Excel

One of the most common requirements is adding a static image, like a logo, to a specific location within a worksheet. The following example demonstrates how to insert an image, define its dimensions, and fine-tune its position using column and row offsets.

from spire.xls import * 
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Add a picture to a specific cell (Row 1, Column 3)
imgPath = "C:\\Users\\Administrator\\Desktop\\logo.png"
picture = sheet.Pictures.Add(1, 3, imgPath)

# Set the picture width and height
picture.Width = 150
picture.Height = 150

# Adjust the column width and row height to accommodate the picture
sheet.Columns[2].ColumnWidth = 25
sheet.Rows[0].RowHeight = 135

# Set the distance between the cell border and the image
picture.LeftColumnOffset = 90
picture.TopRowOffset = 20

# Save to file
workbook.SaveToFile("output/InsertImage.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

Extracting Images from Excel

Have you ever received a spreadsheet filled with embedded product photos that you needed to save to your hard drive? Manually right-clicking and saving each image is inefficient.

from spire.xls import *
from spire.xls.common import *

# Create a Workbook instance
workbook = Workbook()

# Load an Excel file
workbook.LoadFromFile("Test.xlsx")

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Get all images in the worksheet
for i in range(sheet.Pictures.Count - 1, -1, -1):
    pic = sheet.Pictures[i]
    # Save each image as a PNG file
    pic.Picture.Save(f"ExtractImages\\Image-{i:d}.png", ImageFormat.get_Png())

workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

Deleting Images

In many automation scenarios, you may need to sanitize a document by removing all existing graphics before adding new ones, or simply clearing clutter. You can easily achieve this by accessing the picture index and invoking the .Remove() method.

from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\InsertImage.xlsx")

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Delete all pictures from the worksheet
for i in range(sheet.Pictures.Count - 1, -1, -1):
    sheet.Pictures[i].Remove()

# Save to file
workbook.SaveToFile("output/DeleteImage.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

Advanced Image Manipulation

Beyond basic insertion and deletion, Spire.XLS offers granular control over image properties. These advanced techniques are vital for optimizing file size and layout.

Compressing Images

High-resolution images can drastically increase the file size of an Excel workbook, making it difficult to share. You can compress images programmatically to reduce file size while maintaining acceptable visual quality.

from spire.xls import * 
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel document
workbook.LoadFromFile("C:/Users/Administrator/Desktop/Images.xlsx")

# Loop through the worksheets in the document
for sheet in workbook.Worksheets:
    # Loop through the images in the worksheet
    for picture in sheet.Pictures:
        # Compress the image (Quality level 0-100)
        picture.Compress(50)

# Save the file
workbook.SaveToFile("output/CompressImages.xlsx", ExcelVersion.Version2016)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

Resizing Images

If you need to scale images dynamically—for instance, reducing all product photos to 50% of their original size—you can modify the Width and Height properties directly.

from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load the Excel document
workbook.LoadFromFile("C:/Users/Administrator/Desktop/Image.xlsx")

# Get a specific worksheet
sheet = workbook.Worksheets[0]

# Get a specific picture from the worksheet
picture = sheet.Pictures[0]

# Resize the picture (e.g., halve the dimensions)
picture.Width = int(picture.Width / 2)
picture.Height = int(picture.Height / 2)

# Save to file
workbook.SaveToFile("output/ResizeImage.xlsx", ExcelVersion.Version2016)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

Moving Images

You can also programmatically rearrange the layout of a spreadsheet by moving images to different coordinates. This is done by updating the TopRow and LeftColumn properties.

from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load the Excel document
workbook.LoadFromFile("C:/Users/Administrator/Desktop/Image.xlsx")

# Get a specific worksheet
sheet = workbook.Worksheets[0]

# Get a specific picture from the worksheet
picture = sheet.Pictures[0]

# Reset the position of the picture
picture.TopRow = 5
picture.LeftColumn = 6

# Save to file
workbook.SaveToFile("output/MoveImage.xlsx", ExcelVersion.Version2016)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

Conclusion

Automating image handling in Excel significantly enhances productivity, particularly when generating bulk reports or data catalogs. Whether you are building a product inventory sheet or cleaning up a financial dashboard, these Python scripts provide a robust, scalable solution.

Key Takeaways:

  • Use Pictures.Add() to insert images with precision.

  • Use Pictures.Remove() to clean up documents.

  • Use picture.Compress() to optimize file size for sharing.

  • Always call workbook.Dispose() after your operations to release system resources effectively.

Top comments (0)