Spire.Office Knowledgebase Page 25 | E-iceblue

Incorporating external content into PowerPoint presentations can significantly enhance their impact and relevance. OLE (Object Linking and Embedding) objects provide an efficient way to embed or link various types of external files, such as Excel spreadsheets, Word documents, and PDF files, directly into PowerPoint slides. This functionality not only allows for seamless integration of dynamic data but also enables users to maintain a live connection to the original files. In this article, we will introduce how to insert, extract, or remove OLE objects in PowerPoint presentations in Python using Spire.Presentation for Python.

Install Spire.Presentation for Python

This scenario requires Spire.Presentation for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Presentation

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Presentation for Python on Windows

Insert OLE Objects into a PowerPoint Presentation in Python

Spire.Presentation for Python provides the ISlide.Shapes.AppendOleObject() method, which allows you to insert various external files (such as Word documents, Excel spreadsheets, PDF files, PowerPoint presentations, and ZIP archives) as OLE objects into PowerPoint slides. The detailed steps are as follows.

  • Create an object of the Presentation class.
  • Access the desired slide using the Presentation.Slides[index] property.
  • Add an OLE object to the slide using the ISlide.Shapes.AppendOleObject() method.
  • Set the icon for the OLE object using the IOleObject.SubstituteImagePictureFillFormat.Picture.EmbedImage property.
  • Specify the object type using the IOleObject.ProgId property.
  • Save the presentation using the Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create an object of the Presentation class
ppt = Presentation()

try:
    # Get the first slide
    slide = ppt.Slides[0]

    # Initialize the top position for the first object
    currentTop = 60
    # Spacing between OLE objects
    verticalSpacing = 20  

    # Add an Excel icon to the presentation
    excelImageStream = Stream("icons/excel-icon.png")
    oleImage = ppt.Images.AppendStream(excelImageStream)
    # Define the position of the Excel OLE object
    excelRec = RectangleF.FromLTRB(100, currentTop, oleImage.Width + 100, currentTop + oleImage.Height)
    # Add an Excel file to the slide as an OLE object
    oleStream = Stream("Budget.xlsx")
    oleObject = slide.Shapes.AppendOleObject("excel", oleStream, excelRec)
    oleObject.SubstituteImagePictureFillFormat.Picture.EmbedImage = oleImage
    oleObject.ProgId = "Excel.Sheet.12"

    # Update the top position for the next object
    currentTop += oleImage.Height + verticalSpacing

    # Add a Word icon to the presentation
    wordImageStream = Stream("icons/word-icon.png")
    wordOleImage = ppt.Images.AppendStream(wordImageStream)
    # Define the position of the Word OLE object
    wordRec = RectangleF.FromLTRB(100, currentTop, wordOleImage.Width + 100, currentTop + wordOleImage.Height)
    # Add a Word file to the slide as an OLE object
    wordStream = Stream("Document.docx")
    wordOleObject = slide.Shapes.AppendOleObject("word", wordStream, wordRec)
    wordOleObject.SubstituteImagePictureFillFormat.Picture.EmbedImage = wordOleImage
    wordOleObject.ProgId = "Word.Document.12"

    # Update the top position for the next object
    currentTop += wordOleImage.Height + verticalSpacing

    # Add a PDF icon to the presentation
    pdfImageStream = Stream("icons/pdf-icon.png")
    pdfOleImage = ppt.Images.AppendStream(pdfImageStream)
    # Define the position of the PDF OLE object
    pdfRec = RectangleF.FromLTRB(100, currentTop, pdfOleImage.Width + 100, currentTop + pdfOleImage.Height)
    # Add a PDF file to the slide as an OLE object
    pdfStream = Stream("Report.pdf")
    pdfOleObject = slide.Shapes.AppendOleObject("pdf", pdfStream, pdfRec)
    pdfOleObject.SubstituteImagePictureFillFormat.Picture.EmbedImage = pdfOleImage
    pdfOleObject.ProgId = "Acrobat.Document"

    # Update the top position for the next object
    currentTop += pdfOleImage.Height + verticalSpacing

    # Add a zip package icon to the presentation
    zipImageStream = Stream("icons/zip-icon.png")
    zipOleImage = ppt.Images.AppendStream(zipImageStream)
    # Define the position of the zip package OLE object
    zipRec = RectangleF.FromLTRB(100, currentTop, zipOleImage.Width + 100, currentTop + zipOleImage.Height)
    # Add a zip file to the slide as an OLE object
    zipOleStream = Stream("Example.zip")
    zipOleObject = slide.Shapes.AppendOleObject("zip", zipOleStream, zipRec)
    zipOleObject.ProgId = "Package"
    zipOleObject.SubstituteImagePictureFillFormat.Picture.EmbedImage = zipOleImage

    # Save the PowerPoint presentation
    ppt.SaveToFile("AddOLEObjects.pptx", FileFormat.Pptx2010)

finally:
    excelImageStream.Close()
    oleStream.Close()
    wordImageStream.Close()
    wordStream.Close()
    pdfImageStream.Close()
    pdfStream.Close()
    zipImageStream.Close()
    zipOleStream.Close()
    ppt.Dispose()

Insert OLE Objects into a PowerPoint Presentation in Python

Extract OLE Objects from a PowerPoint Presentation in Python

Spire.Presentation for Python enables you to extract the embedded OLE objects from a PowerPoint presentation and save them for further use. The detailed steps are as follows.

  • Create an object of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Iterate through all slides in the presentation and all shapes on each slide.
  • Check if the shape is an OLE object.
  • Get the data of the OLE object using the IOleObject.Data property.
  • Identify the type of the OLE object using the IOleObject.ProgId property and save the OLE object data to its original format.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create an object of the Presentation class
presentation = Presentation()

try:
    # Load the PowerPoint presentation
    presentation.LoadFromFile("AddOLEObjects.pptx")

    # Define output file paths for different types of OLE objects
    output_files = {
        "Acrobat.Document": "ExtractedOLEs/ExtractOLEObject.pdf",  
        "Excel.Sheet.12": "ExtractedOLEs/ExtractOLEObject.xlsx",  
        "Word.Document.12": "ExtractedOLEs/ExtractOLEObject.docx",
        "Package": "ExtractedOLEs/ExtractOLEObject.zip"
    }

    # Iterate through each slide in the presentation
    for slide in presentation.Slides:
        # Iterate through each shape in the slide
        for shape in slide.Shapes:
            # Check if the shape is an OLE object
            if isinstance(shape, IOleObject):
                ole_object = shape
                # Retrieve the data of the OLE object
                ole_data_stream = ole_object.Data

                # Determine the appropriate output file based on the OLE object's ProgId
                output_file = output_files.get(ole_object.ProgId)
                if output_file:
                    # Save the OLE object data to the corresponding output file
                    ole_data_stream.Save(output_file)
                    # Close stream
                    ole_data_stream.Close()

finally:
    presentation.Dispose()

Extract OLE Objects from a PowerPoint Presentation in Python

Remove OLE Objects from a PowerPoint Presentation in Python

If you need to remove unwanted OLE objects from a PowerPoint presentation to streamline your slides, you can use the ISlide.Shapes.Remove() method. The detailed steps are as follows.

  • Create an object of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Iterate through all slides in the presentation and all shapes on each slide.
  • Check if the shape is an OLE object.
  • Store the OLE objects in a list and then remove them from the slide using the ISlide.Shapes.Remove() method.
  • Save the presentation using the Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create an object of the Presentation class
presentation = Presentation()

try:
    # Load the PowerPoint presentation
    presentation.LoadFromFile("AddOLEObjects.pptx")

    # Iterate through each slide in the presentation
    for slide in presentation.Slides:
        # Create a list to store shapes that are OLE objects
        ole_shapes = []

        # Iterate through each shape in the slide
        for shape in slide.Shapes:
            # Check if the shape is an OLE object
            if isinstance(shape, IOleObject):
                ole_shapes.append(shape)

        # Remove all OLE objects from the slide
        for ole_object in ole_shapes:
            slide.Shapes.Remove(ole_object)

    # Save the modified PowerPoint presentation
    presentation.SaveToFile("RemoveOLEObjects.pptx", FileFormat.Pptx2010)

finally:
    presentation.Dispose()

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Charts in Excel are powerful tools that transform raw data into visual insights, making it easier to identify trends and patterns. Often, you may need to manage or adjust these charts to better suit your needs. For instance, you might need to extract the data behind a chart for further analysis, resize a chart to fit your layout, move a chart to a more strategic location, or remove outdated charts to keep your workbook organized and clutter-free. In this article, you will learn how to extract, resize, move, and remove charts in Excel in Python using Spire.XLS for Python.

Install Spire.XLS for Python

This scenario requires Spire.XLS for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.XLS

If you are unsure how to install, please refer to this tutorial: How to Install Spire.XLS for Python on Windows

Extract the Data Source of a Chart in Excel in Python

Spire.XLS for Python provides the Chart.DataRange property, which allows you to define or retrieve the cell range used as the data source for a chart. After retrieving this range, you can access the data it contains for further processing or analysis. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Access the worksheet containing the chart using the Workbook.Worksheets[index] property.
  • Get the chart using the Worksheet.Charts[index] property.
  • Get the cell range that is used as the data source of the chart using the Chart.DataRange property.
  • Loop through the rows and columns in the cell range and get the data of each cell.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("ChartSample.xlsx")

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

# Get the chart
chart = sheet.Charts[0]

# Get the cell range that the chart uses
cellRange = chart.DataRange

# Iterate through the rows and columns in the cell range
for i in range(len(cellRange.Rows)):
    for j in range(len(cellRange.Rows[i].Columns)):
        # Get the data of each cell
        print(cellRange[i + 1, j + 1].Value + "  ", end='')
        
    print("")

workbook.Dispose()

Extract the Data Source of a Chart in Excel in Python

Resize a Chart in Excel in Python

Resizing a chart allows you to adjust its dimensions to fit specific areas of your worksheet or enhance its readability. With Spire.XLS for Python, you can adjust the chart's dimensions using the Chart.Width and Chart.Height properties. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Access the worksheet containing the chart using the Workbook.Worksheets[index] property.
  • Get the chart using the Worksheet.Charts[index] property.
  • Adjust the chart’s dimensions using the Chart.Width and Chart.Height properties.
  • Save the result file using the Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("ChartSample.xlsx")

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

# Get the chart
chart = sheet.Charts[0]

# Resize the chart
chart.Width = 450
chart.Height = 300

# Save the result file
workbook.SaveToFile("ResizeChart.xlsx", ExcelVersion.Version2013)
workbook.Dispose()

Resize a Chart in Excel in Python

Move a Chart in Excel in Python

Moving a chart lets you reposition it for better alignment or to relocate it to another sheet. You can use the Chart.LeftColumn, Chart.TopRow, Chart.RightColumn, and Chart.BottomRow properties to specify the new position of the chart. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Access the worksheet containing the chart using the Workbook.Worksheets[index] property.
  • Get the chart using the Worksheet.Charts[index] property.
  • Set the new position of the chart using the Chart.LeftColumn, Chart.TopRow, Chart.RightColumn, and Chart.BottomRow properties.
  • Save the result file using the Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("ChartSample.xlsx")

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

# Get the chart
chart = sheet.Charts[0]

# Set the new position of the chart
chart.LeftColumn = 1
chart.TopRow = 7
chart.RightColumn = 9
chart.BottomRow = 30

# Save the result file
workbook.SaveToFile("MoveChart.xlsx", ExcelVersion.Version2013)
workbook.Dispose()

Move a Chart in Excel in Python

Remove a Chart from Excel in Python

Removing unnecessary or outdated charts from your worksheet helps keep your document clean and organized. In Spire.XLS for Python, you can use the Chart.Remove() method to delete a chart from an Excel worksheet. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Access the worksheet containing the chart using the Workbook.Worksheets[index] property.
  • Get the chart using the Worksheet.Charts[index] property.
  • Remove the chart using the Chart.Remove() method.
  • Save the result file using the Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("ChartSample.xlsx")

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

# Get the chart
chart = sheet.Charts[0]

# Remove the chart
chart.Remove()

# Save the result file
workbook.SaveToFile("RemoveChart.xlsx", ExcelVersion.Version2013)
workbook.Dispose()

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Excel manipulation is a crucial aspect of many modern web applications, from data analysis to report generation. Node.js, with its non-blocking I/O model and rich ecosystem, is an excellent choice for backend development. When combined with Spire.XLS for JavaScript, you can unlock a world of possibilities for handling Excel files efficiently.

This guide will walk you through the process of integrating Spire.XLS for JavaScript into your Node.js projects, covering everything from initial setup to generating a simple Excel document.

Benefits of Using Spire.XLS for JavaScript in Node.js Projects

Node.js is a great option for developing scalable network applications. When paired with Spire.XLS for JavaScript, you get a robust solution for handling Excel files. Here are some key features and benefits of using Spire.XLS for JavaScript in Node.js projects:

  • Comprehensive Excel Support: Spire.XLS for JavaScript supports a wide range of Excel features, including formulas, charts, pivot tables, and more.
  • High Performance: The library is optimized for speed, ensuring that your application remains responsive even when handling large datasets.
  • Cross-Platform Compatibility: With Node.js, you can run your application on any platform that supports JavaScript, including Windows, macOS, and Linux.
  • Secure and Reliable: The library is designed to be secure, with features like data validation and encryption to protect your data.

By leveraging the strengths of both Node.js and Spire.XLS for JavaScript, you can build powerful applications that handle Excel files with ease.

Set Up Your Environment

Step 1

Download and install Node.js from the official website. Make sure to choose the version that matches your operating system.

After the installation is complete, you can verify that Node.js and npm are installed correctly, along with the version numbers, by entering the following commands in CMD:

node -v 
npm -v 

Install Node.js

Step 2

Create a Node.js project in your IntelliJ IDEA.

Create a Node.js project

Install Jest in your project to write and run tests for your code, by running the following command in Terminal:

npm install --save-dev jest

Install jest

Create a JavaScript file named "jest.config.js" in your project, and include the following configuration in it.

module.exports = {
    testTimeout: 20000,
    testEnvironment: 'node',
    transform: {},
    testMatch: ['<rootDir>/*.js'],
    moduleFileExtensions: [ 'json', 'node', 'tsx', 'ts', 'js', 'jsx','mjs'],
};

Configure jest

Add a "fonts" folder and a "lib" folder to your project.

Add folders in Node.js project

Integrate Spire.XLS for JavaScript in Your Project

Download Spire.XLS for JavaScript and unzip it to a location on your disk. Inside the lib folder, you will find the Spire.Xls.Base.js and Spire.Xls.Base.wasm files.

Obtain Spire.XLS for JavaScript library

Copy these two files into the "lib" folder in your Node.js project.

Copy library to Node.js project

Place the font files you plan to use into the "fonts" folder in your project.

Add font files to node.js project

Create and Save Excel Files Using JavaScript

Add a JavaScript file in your project to generate a simple Excel document from JavaScript code.

JavaScript code for creating an Excel file

Here is the entire JavaScript code:

  • JavaScript
// Import the library
const { Module, spirexls } = require("./lib/Spire.Xls.Base.js");

// Define a test case
test('testCase', async () => {
    await new Promise((resolve) => {
        Module.onRuntimeInitialized = () => {
            createExcel();
            resolve();
        };
    });
});

// Create a custom function
function createExcel (){

    // Load fonts
    spirexls.copyLocalPathToVFS("fonts/","/Library/Fonts/");

    // Specify output file name and path
    const outFileName = "HelloWorld.xlsx";
    const outputPath=  "result/" + outFileName;

    // Create a workbook
    let workbook = Module.spirexls.Workbook.Create();

    // Add a sheet
    let sheet =  workbook.Worksheets.Add("MySheet");

    // Write data to a specific cell
    sheet.Range.get("A1").Text = "Hello World";

    // Auto-fit column width
    sheet.Range.get("A1").AutoFitColumns();

    // Save the workbook to a file
    workbook.SaveToFile({fileName:outFileName, version:spirexls.ExcelVersion.Version2016});
    spirexls.copyFileFromFSToLocalStorage(outFileName, outputPath);

    // Dispose resources
    workbook.Dispose();
}

Once you run the code, you will find the generated Excel file in the designated file path.

Excel file generated by JavaScript code.

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

page 25