Skip to main content

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

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()

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()

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()

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()

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()

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()

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.

 

Comments

Popular posts from this blog

3 Ways to Generate Word Documents from Templates in Java

A template is a document with pre-applied formatting like styles, tabs, line spacing and so on. You can quickly generate a batch of documents with the same structure based on the template. In this article, I am going to show you the different ways to generate Word documents from templates programmatically in Java using Free Spire.Doc for Java library. Prerequisite First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file. <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>...

Insert and Extract OLE objects in Word in Java

You can use OLE (Object Linking and Embedding) to include content from other programs, such as another Word document, an Excel or PowerPoint document to an existing Word document. This article demonstrates how to insert and extract embedded OLE objects in a Word document in Java by using Free Spire.Doc for Java API.   Add dependencies First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file.     <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>    ...

Simple Java Code to Convert Excel to PDF in Java

This article demonstrates a simple solution to convert an Excel file to PDF in Java by using free Excel API – Free Spire.XLS for Java . The following examples illustrate two possibilities to convert Excel to PDF:      Convert the whole Excel file to PDF     Convert a particular Excel Worksheet to PDF Before start with coding, you need to Download Free Spire.XLS for Java package , unzip it and import Spire.Xls.jar file from the lib folder in your project as a denpendency. 1. Convert the whole Excel file to PDF Spire.XLS for Java provides saveToFile method in Workbook class that enables us to easily save a whole Excel file to PDF. import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ExcelToPDF {     public static void main(String[] args){         //Create a Workbook         Workbook workbook = new Workbook();   ...