DEV Community

Allen Yang
Allen Yang

Posted on

Insert and Manage OLE Objects in Excel with Python

Insert and Manage OLE Objects in Excel with Python

OLE (Object Linking and Embedding) objects are a powerful data embedding mechanism in Excel that allows external documents—such as Word files, PDF documents, PowerPoint presentations, audio files, and more—to be embedded directly into worksheets. This makes Excel not just a spreadsheet tool but a container for multiple types of documents. In automated report generation, data archiving, and document management scenarios, inserting and extracting OLE objects programmatically can significantly improve efficiency. This article provides a detailed guide on how to insert, extract, and manage OLE objects in Excel worksheets using Python.

Why Manage OLE Objects Programmatically

Compared with manually inserting objects in Excel, a programmatic approach offers the following advantages:

  • Batch embedding: Embed multiple external documents into worksheets in a single pass without manual operation
  • Automated archiving: Bind associated documents with data storage, ensuring data and contextual documents are not separated
  • Document extraction: Batch extract embedded documents from worksheets for subsequent processing or conversion
  • Workflow integration: Integrate OLE object operations into data processing pipelines for end-to-end automation

Environment Setup

This article uses Spire.XLS for Python, which provides a comprehensive API for manipulating Excel workbooks and worksheets, including OLE object insertion and extraction.

pip install Spire.XLS
Enter fullscreen mode Exit fullscreen mode

Once installed, import the relevant modules in your script to begin working.

Inserting OLE Objects

The core of inserting an OLE object is providing the source file path and a preview image for display. The following code demonstrates how to embed an Excel file as an OLE object into a worksheet:

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


def GenerateImage(fileName):
        book = Workbook()
        book.LoadFromFile(fileName)
        book.Worksheets[0].PageSetup.LeftMargin = 0
        book.Worksheets[0].PageSetup.RightMargin = 0
        book.Worksheets[0].PageSetup.TopMargin = 0
        book.Worksheets[0].PageSetup.BottomMargin = 0
        return book.Worksheets[0].ToImage(1, 1, 19, 5)

inputFile = "./Data/InsertOLEObjects.xls"
outputFile = "InsertOLEObjects.xlsx"

# Create a workbook and get the first worksheet
workbook = Workbook()
ws = workbook.Worksheets[0]
ws.Range["A1"].Text = "Here is an OLE Object."

# Generate a preview image and insert the OLE object
image = GenerateImage(inputFile)
oleObject = ws.OleObjects.Add(inputFile, image, OleLinkType.Embed)
oleObject.Location = ws.Range["B4"]
oleObject.ObjectType = OleObjectType.ExcelWorksheet

# Save the file
workbook.SaveToFile(outputFile, ExcelVersion.Version2010)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

Key steps in the code:

  1. Generate a preview image: The GenerateImage() function loads the source file and converts its first page to an image, which serves as the visual placeholder for the OLE object in the worksheet.
  2. Add the OLE object: The OleObjects.Add() method accepts three parameters — the source file path, the preview image, and the link type. OleLinkType.Embed means the object is embedded in the workbook (rather than externally linked).
  3. Set position and type: The Location property specifies the anchor cell for the OLE object in the worksheet, and the ObjectType property sets the type of the embedded object (in this case, an Excel worksheet).

Inserting Audio Files as OLE Objects

In addition to document files, OLE objects also support embedding multimedia files such as audio. The following code demonstrates how to embed a WAV audio file into a worksheet:

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


inputFile = "./Data/WAVFileSample.wav"
inputimg = "./Data/SpireXls.png"
outputFile = "InsertWavFileOLEObject.xlsx"

# Create a workbook and get the first worksheet
workbook = Workbook()
sheet = workbook.Worksheets[0]

# Use a custom image as preview and add the audio OLE object
with Stream(inputimg) as fs:
    oleObject = sheet.OleObjects.Add(inputFile, fs, OleLinkType.Embed)

# Set position and object type
oleObject.Location = sheet.Range["B4"]
oleObject.ObjectType = OleObjectType.Package

workbook.SaveToFile(outputFile, ExcelVersion.Version2010)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

The main differences from inserting document files are:

  • Preview image source: An external image file (SpireXls.png) is used as the preview image through a Stream object, rather than being auto-generated from the source file.
  • Object type: OleObjectType.Package indicates that the file is embedded as a generic package object, suitable for non-document file types such as audio and video.

Extracting OLE Objects

In document management and data archiving scenarios, extracting embedded OLE objects from Excel worksheets is a common requirement. The following code demonstrates how to extract different types of embedded documents from a worksheet:

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


def WriteAllBytes(fname: str, data):
    fp = open(fname, "wb")
    for d in data:
        fp.write(d)
    fp.close()

inputFile = "./Data/ExtractOle2.xlsx"

workbook = Workbook()
workbook.LoadFromFile(inputFile)
sheet = workbook.Worksheets[0]

# Check if the worksheet contains OLE objects
if sheet.HasOleObjects:
    for obj in sheet.OleObjects:
        type = obj.ObjectType
        # Extract Word document
        if type is OleObjectType.WordDocument:
            WriteAllBytes("ExtractedWord.docx", obj.OleData)
        # Extract PDF document
        elif type is OleObjectType.AdobeAcrobatDocument:
            WriteAllBytes("ExtractedPDF.pdf", obj.OleData)
        # Extract PowerPoint document
        elif type is OleObjectType.PowerPointSlide:
            WriteAllBytes("ExtractedPPT.pptx", obj.OleData)

workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

Core logic of the extraction process:

  • Detect OLE objects: The HasOleObjects property first checks whether the worksheet contains any OLE objects, avoiding unnecessary iteration.
  • Type identification: The ObjectType property identifies the specific type of each OLE object, such as WordDocument, AdobeAcrobatDocument, or PowerPointSlide.
  • Data extraction: The OleData property returns the raw binary data of the OLE object, which is written to the corresponding file using the WriteAllBytes() function.

Getting Original Document Names of OLE Objects

Each OLE object retains the original document name information, which is useful for tracking the source of embedded documents:

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

inputFile = "Data/ExtractOleObjectName.xlsx"

# Create a workbook and load the file
workbook = Workbook()
workbook.LoadFromFile(inputFile)

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

information = ""

# Iterate through all OLE objects and get original document names
for ole in sheet.OleObjects:
    ole_name = ole.OriginName
    information += ole_name + "\r\n"

print(information)

workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

The OriginName property returns the original file name used when the OLE object was embedded. By iterating through all OLE objects and collecting name information, you can quickly generate an inventory of embedded documents.

Practical Tips

Batch Extracting and Categorizing OLE Objects

In practice, a worksheet may contain multiple types of OLE objects. The following code shows how to batch extract and save them by category:

type_mapping = {
    OleObjectType.WordDocument: ".docx",
    OleObjectType.AdobeAcrobatDocument: ".pdf",
    OleObjectType.PowerPointSlide: ".pptx",
    OleObjectType.ExcelWorksheet: ".xlsx"
}

if sheet.HasOleObjects:
    for index, obj in enumerate(sheet.OleObjects):
        ext = type_mapping.get(obj.ObjectType, ".bin")
        filename = f"ole_object_{index}{ext}"
        WriteAllBytes(filename, obj.OleData)
        print(f"Extracted: {filename} (type: {obj.ObjectType})")
Enter fullscreen mode Exit fullscreen mode

By using a type mapping dictionary to convert ObjectType to file extensions, you can automatically assign correct suffixes to extracted files, making them easier to open and process later.

Iterating Across Multiple Worksheets

When multiple worksheets in a workbook contain OLE objects, you need to iterate through all worksheets for extraction:

for sheet_index in range(workbook.Worksheets.Count):
    sheet = workbook.Worksheets[sheet_index]
    if sheet.HasOleObjects:
        for obj in sheet.OleObjects:
            print(f"Worksheet {sheet_index + 1}: {obj.OriginName} - {obj.ObjectType}")
Enter fullscreen mode Exit fullscreen mode

This code scans the entire workbook and reports the name and type of each OLE object in every worksheet, which is useful for document auditing and content inventory scenarios.

Conclusion

This article provided a detailed walkthrough of the complete workflow for managing OLE objects in Excel worksheets with Python, covering four core operations: inserting document objects, inserting multimedia files, extracting embedded documents, and retrieving object information.

Key takeaways:

  1. Use the OleObjects.Add() method to insert OLE objects, providing the source file path, preview image, and link type
  2. Set the object type via the ObjectType property — use specific type enums for documents and Package for multimedia files
  3. Use HasOleObjects for detection and the OleData property to extract the raw binary data of embedded documents
  4. Retrieve the original document name through the OriginName property to track embedding sources

With these skills, you can integrate OLE object management into document processing workflows, enabling automatic embedding, batch extraction, and categorized archiving of external documents, effectively improving the automation level of document management.

Top comments (0)