A column chart in PowerPoint is a graphical representation of data that uses bars or columns to show comparisons between categories. It is commonly used to display financial data, statistics, and other quantitative information. Each column represents a category, and the height of the column corresponds to the value associated with that category. Column charts are easy to create and customize within PowerPoint, allowing users to quickly visualize their data.

In this article, you will learn how to programmatically create column charts in a PowerPoint document 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

Create a Clustered Column Chart in PowerPoint in Python

A clustered column chart is a type of bar graph where the bars (or columns) are grouped together in clusters or segments, with each cluster representing a category and the height of the columns within the cluster reflecting the value of a data point for that category.

To add a clustered column chart in PowerPoint using Spire.Prensetion for Python, you can use the ISlide.Shapes.AppendChartInit(type: ChartType, rectangle RectangleF, init bool) method and specify the chart type as ColumnClustered. This method returns an object of IChart class, which you can use to set the chart data, title, series labels, category labels, series values and other attributes.

The following are the steps to create a clustered column chart in PowerPoint in Python.

  • Create a Presentation object.
  • Get the first slide using Prenstion.Slides[] property.
  • Add a clustered column chart to the side using ISlide.Shapes.AppendChartInit(type: ChartType, rectangle RectangleF, init bool).
  • Add text and numbers to the chart sheet as chart data using IChart.ChartData property.
  • Set series labels, category labels, series values and other attributes using the properties of the IChart class.
  • Save the document to a PowerPoint file using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation object
presentation = Presentation()

# Set slide size type
presentation.SlideSize.Type = SlideSizeType.Screen16x9

# Get the first slide
slide = presentation.Slides[0]

# Add clustered column chart
rect = RectangleF.FromLTRB(40, 80, 700, 450)
chart = slide.Shapes.AppendChartInit(ChartType.ColumnClustered, rect, False)

# Set chart title
chart.ChartTitle.TextProperties.Text = "Soda Soft Drink Sales"
chart.ChartTitle.TextProperties.IsCentered = True
chart.ChartTitle.Height = 25
chart.HasTitle = True

# Insert text to chart as series labels
chart.ChartData[0,0].Text = "Product"
chart.ChartData[0,1].Text = "Store A"
chart.ChartData[0,2].Text = "Store B"

# Insert text to chart as category labels
chart.ChartData[1,0].Text = "Diet Coke"
chart.ChartData[2,0].Text = "Mountain Dew"
chart.ChartData[3,0].Text = "Diet Pesi"
chart.ChartData[4,0].Text = "Cherry Coke"

# Insert numbers to chart as values of series
Series1 = [35000, 46000, 28000, 52000]
Series2 = [41000, 32000, 36000, 40000]
i = 0
while i < len(Series1):
    chart.ChartData[i + 1,1].NumberValue = Series1[i]
    chart.ChartData[i + 1,2].NumberValue = Series2[i]
    i += 1

# Set series labels
chart.Series.SeriesLabel = chart.ChartData["B1","C1"]

# Set category labels
chart.Categories.CategoryLabels = chart.ChartData["A2","A5"]

# Set values for series
chart.Series[0].Values = chart.ChartData["B2","B5"]
chart.Series[1].Values = chart.ChartData["C2","C5"]

# Set gap width
chart.GapWidth = 350

# Set overlap
chart.OverLap = -50

# Set fill color of each series
chart.Series[0].Fill.FillType = FillFormatType.Solid
chart.Series[0].Fill.SolidColor.Color = Color.get_CadetBlue()
chart.Series[1].Fill.FillType = FillFormatType.Solid
chart.Series[1].Fill.SolidColor.Color = Color.get_LightBlue()

# Add data labels
for i in range(len(Series1)):
    chart.Series[0].DataLabels.Add()
    chart.Series[1].DataLabels.Add()

# Save the document
presentation.SaveToFile("output/ClusteredColumnChart.pptx", FileFormat.Pptx2019)
presentation.Dispose()

Python: Create Column Charts in PowerPoint

Create a Stacked Column Chart in PowerPoint in Python

A stacked column chart is a variation of the standard column chart where each column represents a category, and the height of the column corresponds to the total value of the category.

To add a stacked column chart in PowerPoint using Spire.Prensetion for Python, you use the ISlide.Shapes.AppendChartInit(type: ChartType, rectangle RectangleF, init bool) method and specify the chart type as ColumnStacked. Then, you can use to set the chart data, title, series labels, category labels, series values and other attributes using the properties of the IChart class.

The following are the steps to create a stacked column chart in PowerPoint in Python.

  • Create a Presentation object.
  • Get the first slide using Prenstion.Slides[] property.
  • Add a stacked column chart to the side using ISlide.Shapes.AppendChartInit(type: ChartType, rectangle RectangleF, init bool).
  • Add text and numbers to the chart sheet as chart data using IChart.ChartData property.
  • Set series labels, category labels, series values and other attributes using the properties of the IChart class.
  • Save the document to a PowerPoint file using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation object
presentation = Presentation()

# Set slide size type
presentation.SlideSize.Type = SlideSizeType.Screen16x9

# Get the first slide
slide = presentation.Slides[0]

# Add a stacked column chart
rect = RectangleF.FromLTRB(40, 80, 700, 450)
chart = slide.Shapes.AppendChartInit(ChartType.ColumnStacked, rect, False)

# Set chart title
chart.ChartTitle.TextProperties.Text = "Soda Soft Drink Sales"
chart.ChartTitle.TextProperties.IsCentered = True
chart.ChartTitle.Height = 25
chart.HasTitle = True

# Insert text to chart as series labels
chart.ChartData[0,0].Text = "Product"
chart.ChartData[0,1].Text = "Store A"
chart.ChartData[0,2].Text = "Store B"

# Insert text to chart as category labels
chart.ChartData[1,0].Text = "Diet Coke"
chart.ChartData[2,0].Text = "Mountain Dew"
chart.ChartData[3,0].Text = "Diet Pesi"
chart.ChartData[4,0].Text = "Cherry Coke"

# Insert numbers to chart as values of series
Series1 = [35000, 46000, 28000, 52000]
Series2 = [41000, 32000, 36000, 40000]
i = 0
while i < len(Series1):
    chart.ChartData[i + 1,1].NumberValue = Series1[i]
    chart.ChartData[i + 1,2].NumberValue = Series2[i]
    i += 1

# Set series labels
chart.Series.SeriesLabel = chart.ChartData["B1","C1"]

# Set category labels
chart.Categories.CategoryLabels = chart.ChartData["A2","A5"]

# Set values for series
chart.Series[0].Values = chart.ChartData["B2","B5"]
chart.Series[1].Values = chart.ChartData["C2","C5"]

# Set gap width
chart.GapWidth = 350

# Set fill color of each series
chart.Series[0].Fill.FillType = FillFormatType.Solid
chart.Series[0].Fill.SolidColor.Color = Color.get_CadetBlue()
chart.Series[1].Fill.FillType = FillFormatType.Solid
chart.Series[1].Fill.SolidColor.Color = Color.get_LightBlue()

# Add data labels
for i in range(len(Series1)):
    chart.Series[0].DataLabels.Add()
    chart.Series[1].DataLabels.Add()

# Save the document
presentation.SaveToFile("output/StackedColumnChart.pptx", FileFormat.Pptx2019)
presentation.Dispose()

Python: Create Column Charts in PowerPoint

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.

Python: Convert Excel to SVG

2024-02-02 07:18:32 Written by Koohji

SVG (Scalable Vector Graphics) is a flexible file format widely used on the web. Unlike traditional image formats, SVG files are not based on pixels. Instead, they use mathematical equations to define shapes, lines, and colors. This unique characteristic allows SVG files to be scaled up or down without any loss of quality, making them an excellent choice for creating interactive and visually appealing graphics. By converting Excel files to SVG, you can seamlessly embed the resulting SVG files into web pages, ensuring smooth integration and display of your Excel data on the web. In this article, we will demonstrate how to convert Excel to SVG format 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

Convert a Worksheet in Excel to SVG in Python

Spire.XLS for Python provides the Worksheet.ToSVGStream() method to convert an Excel worksheet to SVG. The detailed steps are as follows:

  • Create an object of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet by its index through Workbook.Worksheets[] property.
  • Create an object of the Stream class.
  • Save the worksheet to an SVG using Worksheet.ToSVGStream() method.
  • Python
from spire.xls.common import *
from spire.xls import *

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

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

# Save the worksheet to an SVG
stream = Stream("WorksheetToSVG.svg")
worksheet.ToSVGStream(stream, 0, 0, 0, 0)
stream.Flush()
stream.Close()

workbook.Dispose()

Python: Convert Excel to SVG

Convert a Chart Sheet in Excel to SVG in Python

A chart sheet in Excel is a separate sheet within an Excel workbook that is dedicated to displaying a chart. Spire.XLS for Python allows you to convert a chart sheet to SVG by using the ChartSheet.ToSVGStream() method. The detailed steps are as follows:

  • Create an object of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific chart sheet using Workbook.GetChartSheetByName() method.
  • Create an object of the Stream class.
  • Save the chart sheet to an SVG using ChartSheet.ToSVGStream() method.
  • Python
from spire.xls.common import *
from spire.xls import *

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

# Get a specific chart sheet
chartSheet = workbook.GetChartSheetByName("Chart1")

# Save the chart sheet to an SVG
stream = Stream("ChartSheetToSVG.svg")
chartSheet.ToSVGStream(stream)
stream.Flush()
stream.Close()

workbook.Dispose()

Python: Convert Excel to SVG

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.

Accepting and rejecting tracked changes in Excel are essential features that empower users to effectively manage and control modifications made by multiple contributors. Accepting changes allows users to include modifications in the spreadsheet, facilitating collaboration and ensuring that the final version reflects collective input. Conversely, rejecting changes enables users to maintain the original content and avoid incorporating incorrect or unnecessary modifications. These functions provide users with the ability to maintain data integrity, ensure document accuracy, and streamline the collaborative process in Excel. In this article, we will demonstrate how to accept and reject tracked changes 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

Accept Tracked Changes in Excel in Python

Spire.XLS for Python provides the Workbook.HasTrackedChanges property to determine whether an Excel workbook has tracked changes or not. If the property returns True, you can use the Workbook.AcceptAllTrackedChanges() method to accept these changes at once.

The following steps explain how to accept all tracked changes in an Excel workbook using Spire.XLS for Python:

  • Create a Workbook object.
  • Load a sample Excel workbook using Workbook.LoadFromFile() method.
  • Check if the workbook has tracked changes using Workbook.HasTrackedChanges property.
  • Accept all tracked changes in the workbook using Workbook.AcceptAllTrackedChanges() method.
  • Save the result workbook using Workbook.SaveToFile() method.
  • Python
from spire.xls.common import *
from spire.xls import *

# Specify the input and output file paths
inputFile = "Sample.xlsx"
outputFile = "AcceptChanges.xlsx"

# Create a Workbook object
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile(inputFile)

# Check if the file has tracked changes
if workbook.HasTrackedChanges:
    # Accept all tracked changes in the file
    workbook.AcceptAllTrackedChanges()

# Save the result file
workbook.SaveToFile(outputFile, FileFormat.Version2013)
workbook.Dispose()

Python: Accept or Reject Tracked Changes in Excel

Reject Tracked Changes in Excel in Python

If the changes made to a workbook compromise the integrity of the data, such as introducing errors, inconsistencies, or inaccuracies, you can reject these changes by using the Workbook.RejectAllTrackedChanges() method.

The following steps explain how to reject all tracked changes in an Excel workbook using Spire.XLS for Python:

  • Create a Workbook object.
  • Load a sample Excel workbook using Workbook.LoadFromFile() method.
  • Check if the workbook has tracked changes using Workbook.HasTrackedChanges property.
  • Reject all tracked changes in the workbook using Workbook.RejectAllTrackedChanges() method.
  • Save the result workbook using Workbook.SaveToFile() method.
  • Python
from spire.xls.common import *
from spire.xls import *

# Specify the input and output file paths
inputFile = "Sample.xlsx"
outputFile = "RejectChanges.xlsx"

# Create a Workbook object
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile(inputFile)

# Check if the file has tracked changes
if workbook.HasTrackedChanges: 
    # Reject all tracked changes in the file
    workbook.RejectAllTrackedChanges()

# Save the result file
workbook.SaveToFile(outputFile, FileFormat.Version2013)
workbook.Dispose()

Python: Accept or Reject Tracked Changes in Excel

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.

The inclusion of attachments in a PDF can be useful for sharing related files or providing additional context and resources alongside the main document. However, there may be instances when you need to remove attachments from a PDF for reasons like reducing file size, protecting sensitive information, or simply decluttering the document. In this article, you will learn how to remove attachments from a PDF document in Python using Spire.PDF for Python.

Install Spire.PDF for Python

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

pip install Spire.PDF

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

Prerequisite Knowledge

There are typically two types of attachments in PDF, document-level attachments and annotation attachments. The following table lists the differences between them and their representations in Spire.PDF.

Attachment type Represented by Definition
Document level attachment PdfAttachment class A file attached to a PDF at the document level won't appear on a page, but can be viewed in the "Attachments" panel of a PDF reader.
Annotation attachment PdfAnnotationAttachment class A file attached as an annotation can be found on a page or in the "Attachment" panel. An annotation attachment is shown as a paper clip icon on the page; reviewers can double-click the icon to open the file.

Remove Document-Level Attachments from PDF in Python

To obtain all document-level attachments of a PDF document, use the PdfDocument.Attachments property. Then, you can remove all of them using the Clear() method or selectively remove a specific attachment using the RemoveAt() method. The following are the steps to remove document-level attachments from PDF in Python.

  • Create a PdfDocument object.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Get the attachment collection from the document using PdfDocument.Attachments property.
  • Remove all attachments using PdfAttachmentCollection.Clear() method. To remove a specific attachment, use PdfAttachmentCollection.RemoveAt() method.
  • Save the changes to a different PDF file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf import *
from spire.pdf.common import *

# Create a PdfDocument object
doc = PdfDocument()

# Load a PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Attachments.pdf")

# Get the attachment collection from the document
attachments = doc.Attachments

# Remove all attachments
attachments.Clear()

# Remove a specific attachment
# attachments.RemoveAt(0)

# Save the changes to file
doc.SaveToFile("output/DeleteAttachments.pdf")

# Close the document
doc.Close()

Remove Annotation Attachments from PDF in Python

Annotations are page-based elements, and to retrieve all annotations from a document, you need to iterate through the pages and obtain the annotations from each page. Next, identify if a particular annotation is an attachment annotation, and finally remove it from the annotation collection using the RemoveAt() method.

The following are the steps to remove annotation attachments from PDF in Python.

  • Create a PdfDocument object.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Iterate through the pages in the document
  • Get the annotation collection from a specific page through PdfPageBase.AnnotationsWidget property.
  • Iterate through the annotations in the collection.
  • Determine if a specific annotation is an instance of PdfAttachmentAnnotationWidget.
  • Remove the attachment annotation using PdfAnnotationCollection.RemoveAt() method.
  • Save the changes to a different PDF file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf import *
from spire.pdf.common import *

# Create a PdfDocument object
doc = PdfDocument()

# Load a PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\AnnotationAttachment.pdf")

# Iterate through the pages in the document
for i in range(doc.Pages.Count):

    # Get annotation collection from a certain page
    annotationCollection = doc.Pages.get_Item(i).AnnotationsWidget

    if annotationCollection.Count > 0:

        # Iterate through the annotation in the collection
        for j in range(annotationCollection.Count):

            # Get a specific annotation
            annotation = annotationCollection.get_Item(j)

            # Determine if it is an attachment annotation
            if isinstance(annotation, PdfAttachmentAnnotationWidget):

                # Remove the annotation
                annotationCollection.RemoveAt(j)

# Save the changes to file
doc.SaveToFile("output/DeleteAnnotationAttachment.pdf")

# Close the document
doc.Close()

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.

In PowerPoint, sections are a powerful tool for organizing and managing slides. By dividing slides into different sections, you can better organize content, navigate through your presentation, and present information in a more structured manner. This article will demonstrate how to add and remove sections in a PowerPoint presentation using Spire.Presentation for Python.

Install Spire.PDF 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

Add a Section at the End of a PowerPoint in Python

Spire.Presentation for Python provides the Presentation.SectionList.Append(section_name) method to add a section at the end of a presentation. Here are the specific steps to perform this operation:

  • Create a Presentation class instance.
  • Load a PowerPoint document using Presentation.LoadFromFile() method.
  • Add a section at the end using the Presentation.SectionList.Append() method.
  • Save the document using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create a new presentation object
presentation = Presentation()

# Load a sample PowerPoint presentation
presentation.LoadFromFile("sample.pptx")

# Append a new section
presentation.SectionList.Append("New Section")

# Save the presentation
presentation.SaveToFile("AddSection.pptx", FileFormat.Pptx2013)

# Dispose of the presentation object
presentation.Dispose()

Python: Add or Remove Sections in PowerPoint

Insert a Section Before a Specified Section in Python

You can also use the Presentation.SectionList.Insert(index, section_name) method to insert a new section before a specific section. Here are the detailed steps:

  • Create a Presentation class instance.
  • Load a PowerPoint document using Presentation.LoadFromFile() method.
  • Insert a new section before a specific section using the Presentation.SectionList.Insert() method, where index is the position of the specific section.
  • Save the document using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create a new presentation object
presentation = Presentation()

# Load a sample PowerPoint presentation
presentation.LoadFromFile("sample.pptx")

# Insert a new section before the second section
presentation.SectionList.Insert(1," New Section")

# Save the presentation
presentation.SaveToFile("AddSection.pptx", FileFormat.Pptx2013)

# Dispose of the presentation object
presentation.Dispose()

Python: Add or Remove Sections in PowerPoint

Add a Section Before a Specified Slide in Python

You can also use the Presentation.SectionList.Add(section_name, slide) method to insert a new section before a specific slide. Here are the detailed steps:

  • Create a Presentation class instance.
  • Load a PowerPoint document using Presentation.LoadFromFile() method.
  • Insert a new section before a specific slide using the Presentation.SectionList.Add() method
  • Save the document using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create a new presentation object
presentation = Presentation()

# Load a sample PowerPoint presentation
presentation.LoadFromFile("sample.pptx")

# Get the second slide
slide=presentation.Slides[1]

# Add a new section before the second slide
presentation.SectionList.Add("New Section",slide)

# Save the presentation
presentation.SaveToFile("AddSection.pptx", FileFormat.Pptx2013)

# Dispose of the presentation object
presentation.Dispose()

Python: Add or Remove Sections in PowerPoint

Remove a Section from a PowerPoint in Python

If you don't need a specific section, you can simply remove it using the Presentation.SectionList.RemoveAt(index_to_remove) method. Please note that removing a section does not delete the slides within that section. Here are the steps to delete a specific section while preserving its slides:

  • Create a Presentation class instance.
  • Load a PowerPoint document using Presentation.LoadFromFile() method.
  • Remove a specific section using the Presentation.SectionList.RemoveAt(index_to_remove) method, which takes an integer index as a parameter. You can also remove all sections using the Presentation.Slides.RemoveAll() method.
  • Save the document using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create a new presentation object
presentation = Presentation()

# Load a sample PowerPoint presentation
presentation.LoadFromFile("sample.pptx")

# Remove the second section
presentation.SectionList.RemoveAt(1)

# # Remove all sections
# presentation.SectionList.RemoveAll()

# Save the presentation
presentation.SaveToFile("RemoveSection.pptx", FileFormat.Pptx2013)

# Dispose of the presentation object
presentation.Dispose()

Python: Add or Remove Sections in PowerPoint

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.

Tables in Excel are powerful tools for organizing, storing, analyzing, and visualizing data. They are widely used in various industries and fields, including finance, business, science, education, and more. The table functionality in Excel makes data processing easier and provides users with flexibility and efficiency to make decisions and solve problems. This article will explain how to use Spire.XLS for Python to add or delete tables in Excel documents using 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 commands.

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

Add Tables to an Excel Document in Python

Spire.XLS for Python creates table objects for the specified data source using the Worksheet.ListObjects.Create(tableName, range) method. The following are the detailed steps:

  • Create an object of the Workbook class.
  • Use the Workbook.LoadFromFile() method to load an Excel document.
  • Use the Workbook.Worksheets[] property to retrieve the desired worksheet.
  • Create a table object using the Worksheet.ListObjects.Create() method.
  • Set the table style using the Worksheet.ListObjects[].BuiltInTableStyle property.
  • Use the Workbook.SaveToFile() method to save the resulting file.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an .xlsx document
workbook.LoadFromFile("Data/sample1.xlsx")

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

# Create a table named "table" in the worksheet, with range [1,1,13,5]
sheet.ListObjects.Create("table", sheet.Range[1,1,13,5])

# Set the built-in table style of the first table to TableStyleLight9
sheet.ListObjects[0].BuiltInTableStyle = TableBuiltInStyles.TableStyleLight9

# Save the workbook to a file
workbook.SaveToFile("AddTable.xlsx", ExcelVersion.Version2016)

# Release resources and clean up the workbook object
workbook.Dispose()

Python: Add Tables to Excel Documents or Delete Tables from Excel Documents

Delete Tables from an Excel Document in Python

Excel table objects are located in the Worksheet.ListObjects collection. To delete a table object, you need to iterate through the collection, find the table object based on its name, and remove it from the collection. Here are the detailed steps:

  • Create an object of the Workbook class.
  • Use the Workbook.LoadFromFile() method to load an Excel document.
  • Use the Workbook.Worksheets[] property to retrieve the desired worksheet.
  • Iterate through the Worksheet.ListObjects collection in the worksheet to obtain the name of each ListObject object for finding the table object to delete.
  • Use the Worksheet.ListObjects.RemoveAt() method to remove the table object.
  • Use the Workbook.SaveToFile() method to save the resulting file.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an .xlsx document
workbook.LoadFromFile("Data/Sample2.xlsx")

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

# Iterate through all the tables in the worksheet
for i in range(len(sheet.ListObjects)):

    # Check if the table's name is "FruitTable"
if sheet.ListObjects[i].Name == "FruitTable":

        # If a matching table is found, remove it
        sheet.ListObjects.RemoveAt(i)

# Save the workbook to a file
workbook.SaveToFile("DeleteTable.xlsx", ExcelVersion.Version2016)

# Release resources and clean up the workbook object
workbook.Dispose()

Python: Add Tables to Excel Documents or Delete Tables from Excel Documents

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.

By incorporating supplemental resources directly into the PDF, it consolidates all relevant information in a single file, making it easier to organize, share, and archive. This feature enables users to seamlessly share supporting documents, images, or multimedia elements, eliminating the need for separate file transfers or external links. It streamlines communication, improves efficiency, and ensures that recipients have convenient access to all the necessary resources within the PDF itself. In this article, you will learn how to attach files to a PDF document in Python with the help of Spire.PDF for Python.

Install Spire.PDF for Python

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

pip install Spire.PDF

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

Background Knowledge

There are generally two types of attachments in PDF, namely document level attachment and annotation attachment. Both are supported by Spire.PDF for Python. The table below lists the differences between them.

Attachment type Represented by Definition
Document level attachment PdfAttachment class A file attached to a PDF at the document level won't appear on a page, but can be viewed in the "Attachments" panel of a PDF reader.
Annotation attachment PdfAnnotationAttachment class A file attached as an annotation can be found on a page or in the "Attachment" panel. An Annotation attachment is shown as a paper clip icon on the page; reviewers can double-click the icon to open the file.

Attach Files to a PDF Document in Python

To attach files to PDFs at the document level, you first need to create a PdfAttachment object based on an external file, and then you can add it to a PDF document using the PdfDocument.Attachments.Add() method. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Create a PdfAttachment object based on an external file.
  • Add the attachment to the document using PdfDocument.Attachments.Add() method.
  • Save the document to a different PDF file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf import *
from spire.pdf.common import *

# Create a PdfDocument object
doc = PdfDocument()

# Load a sample PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf")

# Create PdfAttachment objects based on external files
attachment_one = PdfAttachment("C:\\Users\\Administrator\\Desktop\\Data.xlsx")
attachment_two = PdfAttachment("C:\\Users\\Administrator\\Desktop\\logo.png")

# Add the attachments to PDF
doc.Attachments.Add(attachment_one)
doc.Attachments.Add(attachment_two)

# Save to file
doc.SaveToFile("output/Attachment.pdf")

Python: Attach Files to a PDF Document

Attach Files as Annotations in PDF in Python

An annotation attachment is represented by the PdfAttachmentAnnotation class. Create an instance of this class, specify its attributes such as bounds, flag and text, and then add it to a specified page using the PdfPageBase.AnnotationsWidget.Add() method.

Below are the steps to attach files as annotations in PDF using Spire.PDF for Python.

  • Create a PdfDocument object.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Get a specific page to add annotation through PdfDocument.Pages[] property.
  • Create a PdfAttachmentAnnotation object based on an external file.
  • Add the annotation attachment to the page using PdfPageBase.AnnotationsWidget.Add() method.
  • Save the document to a different PDF file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf import *
from spire.pdf.common import *

# Create a PdfDocument object
doc = PdfDocument()

# Load a sample PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf")

# Get a specific page
page = doc.Pages.get_Item(1)

# Draw a string on PDF
str = ""Here is the report:""
font = PdfTrueTypeFont(""Times New Roman"", 16.0, PdfFontStyle.Bold, True)
x = 50.0
y = doc.Pages.get_Item(0).ActualSize.Height - 300.0
page.Canvas.DrawString(str, font, PdfBrushes.get_Blue(), x, y)

# Create a PdfAttachmentAnnotation object based on an external file
data = Stream("C:\\Users\\Administrator\\Desktop\\Data.xlsx")
size = font.MeasureString(str);
bounds = RectangleF((x + size.Width + 5.0), y, 10.0, 15.0)
annotation = PdfAttachmentAnnotation(bounds, "Report.docx", data);

# Set color, flag, icon and text of the annotation
annotation.Color = PdfRGBColor(Color.get_Blue())
annotation.Flags = PdfAnnotationFlags.Default
annotation.Icon = PdfAttachmentIcon.Graph
annotation.Text = "Click to open the file"

# Add the attachment annotation to PDF
page.AnnotationsWidget.Add(annotation)

# Save to file
doc.SaveToFile("output/AnnotationAttachment.pdf")

Python: Attach Files to a PDF Document

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.

Content controls play an important role in Excel, providing powerful functionality for data input, display, and user interaction. These controls include text boxes, radio buttons, checkboxes, drop-down lists, and more. They offer users more efficient, intuitive, and flexible ways of handling data, making Excel a powerful tool for data management and analysis. This article will introduce how to use Spire.XLS for Python to add content controls to Excel documents or edit content controls in Excel documents using 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 commands.

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

Add Content Controls to an Excel document in Python

Spire.XLS for Python allows you to add content controls supported by Excel, such as text boxes, radio buttons, drop-down lists (also known as combo boxes), checkboxes, and more. The following are the detailed steps:

  • Create an object of the Workbook class.
  • Use the Workbook.LoadFromFile() method to load an Excel data document.
  • Use the Workbook.Worksheets[] property to retrieve the desired worksheet.
  • Add a text box using the Worksheet.TextBoxes.AddTextBox() method.
  • Add a radio button using the Worksheet.RadioButtons.Add() method.
  • Add a combo box using the Worksheet.ComboBoxes.AddComboBox() method.
  • Add a checkbox using the Worksheet.CheckBoxes.AddCheckBox() method.
  • Use the Workbook.SaveToFile() method to save the resulting file.
  • Python
from spire.xls.common import *
from spire.xls import *

# Create a new Workbook object
workbook = Workbook()

# Load an existing Excel file
workbook.LoadFromFile("Data/Sample01.xlsx")

# Select the first worksheet
worksheet = workbook.Worksheets[0]

# Set the height of the text box (unit: points)
height = 40

# Add a text box to the worksheet
textbox = worksheet.TextBoxes.AddTextBox(3, 2, height, 400)
textbox.Line.ForeKnownColor = ExcelColors.Black
textbox.Text = "Andy"

# Add radio buttons to the worksheet
radioButton1 = worksheet.RadioButtons.Add(5, 2, height, 60)
radioButton1.Text = "Male"
radioButton1.CheckState=CheckState.Checked
radioButton2 = worksheet.RadioButtons.Add(5, 3, height, 60)
radioButton2.Text = "Female"

# Assign a data range from another worksheet to a combo box
dataSheet = workbook.Worksheets[1]
comboBoxShape = worksheet.ComboBoxes.AddComboBox(7, 2, 30, 200)
comboBoxShape.ListFillRange = dataSheet.Range["A1:A7"]
comboBoxShape.SelectedIndex=1

# Add check boxes to the worksheet
checkBox = worksheet.CheckBoxes.AddCheckBox(9, 2, height, 60)
checkBox.CheckState = CheckState.Checked
checkBox.Text = "Sing"
checkBox = worksheet.CheckBoxes.AddCheckBox(9, 3, height, 60)
checkBox.CheckState = CheckState.Unchecked
checkBox.Text = "Dance"
checkBox = worksheet.CheckBoxes.AddCheckBox(9, 4, height, 60)
checkBox.CheckState = CheckState.Checked
checkBox.Text = "Exercise"
checkBox = worksheet.CheckBoxes.AddCheckBox(9, 5, height, 100)
checkBox.CheckState = CheckState.Unchecked
checkBox.Text = "Musical Instruments"

# Save the modified workbook to a new file
workbook.SaveToFile("AddContentControls.xlsx", ExcelVersion.Version2016)

# Clean up and release the workbook object
workbook.Dispose()

Python: Add Content Controls to Excel Documents or Edit Content Controls in Excel Documents

Edit Content Controls in an Excel document in Python

Spire.XLS for Python can also modify the properties of existing content controls in an Excel document, such as changing the text of a text box, resetting the selected item of a drop-down list, hiding a specific content control, and more. Here are the detailed steps:

  • Create an object of the Workbook class.
  • Use the Workbook.LoadFromFile() method to load an Excel document.
  • Use the Workbook.Worksheets[] property to retrieve the desired worksheet.
  • Modify the display content of a text box using the Worksheet.TextBoxes[].Text property.
  • Set whether to display a specific text box using the Worksheet.TextBoxes[].Visible property.
  • Set whether a radio button is checked using the Worksheet.RadioButtons[].CheckState property.
  • Set the selected item of a combo box using the Worksheet.ComboBoxes[].SelectedIndex property.
  • Set whether a checkbox is checked using the Worksheet.CheckBoxes[].CheckState property.
  • Use the Workbook.SaveToFile() method to save the resulting file.
  • Python
from spire.xls.common import *
from spire.xls import *

# Create a Workbook object
workbook = Workbook()

# Load Excel data from file
workbook.LoadFromFile("Data/Sample02.xlsx")

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

# Set the text content of the first textbox to "Gary"
worksheet.TextBoxes[0].Text = "Gary"

# Set the text content of the second textbox to "gary.li@gmail.com"
worksheet.TextBoxes[1].Text = "gary.li@gmail.com"

# Hide the fourth textbox
worksheet.TextBoxes[3].Visible = False

# Check the first radio button
worksheet.RadioButtons[0].CheckState = CheckState.Checked

# Set the selected index of the first combobox to 0 (the first option)
worksheet.ComboBoxes[0].SelectedIndex = 0

# Check the first checkbox
worksheet.CheckBoxes[0].CheckState = CheckState.Checked

# Uncheck the third checkbox
worksheet.CheckBoxes[2].CheckState = CheckState.Unchecked

# Save the modified workbook to a new file
workbook.SaveToFile("EditContentControls.xlsx", ExcelVersion.Version2016)

# Clean up and release the workbook object
workbook.Dispose()

Python: Add Content Controls to Excel Documents or Edit Content Controls in Excel Documents

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.

Sometimes, when dealing with PDF documents, there is a need to split a page into different sections based on content or layout. For instance, splitting a mixed-layout page with both horizontal and vertical content into two separate parts. This type of splitting is not commonly available in basic PDF management functions but can be important for academic papers, magazine ads, or mixed-layout designs. This article explains how to use Spire.PDF for Python to perform horizontal or vertical PDF page splitting.

Install Spire.PDF for Python

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

pip install Spire.PDF

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

Split PDF Page Horizontally or Vertically with Python

Spire.PDF for Python not only supports splitting a PDF document into multiple PDF documents, but also allows splitting a specific page within a PDF into two or more pages. Here are the detailed steps to split a page:

  • Create an instance of the PdfDocument class.
  • Load the source PDF document using the PdfDocument.LoadFromFile() method.
  • Retrieve the page(s) to be split using PdfDocument.Pages[].
  • Create a new PDF document and set its page margins to 0.
  • Set the width or height of the new document to half of the source document.
  • Add a page to the new PDF document using the PdfDocument.Pages.Add() method.
  • Create a template for the source document's page using the PdfPageBase.CreateTemplate() method.
  • Draw the content of the source page onto the new page using the PdfTemplate.Draw() method.
  • Save the split document using the PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
pdf = PdfDocument()

# Load the PDF document
pdf.LoadFromFile("Terms of service.pdf")

# Get the first page
page = doc.Pages.get_Item(0)

# Create a new PDF document and remove the page margins
newpdf = PdfDocument()
newpdf.PageSettings.Margins.All=0

# Horizontal splitting: Set the width of the new document's page to be the same as the width of the first page of the original document, and the height to half of the first page's height
newpdf.PageSettings.Width=page.Size.Width
newpdf.PageSettings.Height=page.Size.Height/2

'''
# Vertical splitting: Set the width of the new document's page to be half of the width of the first page of the original document, and the height to the same as the first page's height
newpdf.PageSettings.Width=page.Size.Width/2
newpdf.PageSettings.Height=page.Size.Height
'''

# Add a new page to the new PDF document
newPage = newpdf.Pages.Add()

# Set the text layout format
format = PdfTextLayout()
format.Break=PdfLayoutBreakType.FitPage
format.Layout=PdfLayoutType.Paginate

# Create a template based on the first page of the original document and draw it onto the new page of the new document, automatically paginating when the page is filled
page.CreateTemplate().Draw(newPage, PointF(0.0, 0.0), format)

# Save the document
newpdf.SaveToFile("HorizontalSplitting.pdf")

# Close the objects
newpdf.Close()
pdf.Close()

The result of horizontal splitting is as follows:

Python: Split a PDF Page into Multiple Pages

The result of vertical splitting is as follows:

Python: Split a PDF Page into Multiple Pages

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.

Using lists in PowerPoint allows you to present information in a structured and visually appealing way. They help break down complex ideas into digestible points, making it easier for your audience to understand and retain key concepts. Whether you're creating a slide deck for a business presentation, educational workshop, or conference talk, incorporating lists can enhance the visual appeal and effectiveness of your content. In this article, we will demonstrate how to create numbered lists and bulleted lists 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

Create a Numbered List in PowerPoint in Python

Spire.Presentation supports adding numerals or bullet points in front of paragraphs to create a numbered or bulleted list. To specify the bullet type, you can use the ParagraphProperties.BulletType property. The following are the steps to create a numbered list in a PowerPoint slide using Spire.Presentation for Python.

  • Create a Presentation object.
  • Get the first slide using Presentation.Slides[0] property.
  • Append a shape to the slide using ISlide.Shapes.AppendShape() method and set the shape style.
  • Specify the items of the numbered list inside a list.
  • Create paragraphs based on the list items, and set the bullet type of these paragraphs to Numbered using ParagraphProperties.BulletType property.
  • Set the numbered bullet style of these paragraphs using ParagraphProperties.BulletStyle property.
  • Add these paragraphs to the shape using IAutoShape.TextFrame.Paragraphs.Append() method.
  • Save the document to a PowerPoint file using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

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

# Get the first slide
slide = presentation.Slides[0]

# Add a shape to the slide and set the shape style
shape = slide.Shapes.AppendShape(ShapeType.Rectangle, RectangleF(50.0, 50.0, 300.0, 200.0))
shape.Fill.FillType = FillFormatType.none
shape.Line.FillType= FillFormatType.none

# Add text to the default paragraph
paragraph = shape.TextFrame.Paragraphs[0]
paragraph.Text = "Required Web Development Skills:"
paragraph.Alignment = TextAlignmentType.Left
paragraph.TextRanges[0].Fill.FillType = FillFormatType.Solid
paragraph.TextRanges[0].Fill.SolidColor.Color = Color.get_Black()

# Specify the list items
listItems = [
    " Command-line Unix",
    " Vim",
    " HTML",
    " CSS",
    " Python",
    " JavaScript",
    " SQL"
]

# Create a numbered list
for item in listItems:
    textParagraph = TextParagraph()
    textParagraph.Text = item
    textParagraph.Alignment = TextAlignmentType.Left
    textParagraph.TextRanges[0].Fill.FillType = FillFormatType.Solid
    textParagraph.TextRanges[0].Fill.SolidColor.Color = Color.get_Black()

    textParagraph.BulletType = TextBulletType.Numbered
    textParagraph.BulletStyle = NumberedBulletStyle.BulletArabicPeriod
    shape.TextFrame.Paragraphs.Append(textParagraph)
            

# Save the result document
presentation.SaveToFile("NumberedList.pptx", FileFormat.Pptx2013)
presentation.Dispose()

Python: Create Numbed or Bulleted Lists in PowerPoint

Create a Bulleted List with Symbol Bullets in PowerPoint in Python

The process of creating a bulleted list with symbol bullets is very similar to that of creating a numbered list. The only difference is that you need to set the bullet type of the paragraphs to Symbol. The following are the steps.

  • Create a Presentation object.
  • Get the first slide using Presentation.Slides[0] property.
  • Append a shape to the slide using ISlide.Shapes.AppendShape() method and set the shape style.
  • Specify the items of the bulleted list inside a list.
  • Create paragraphs based on the list items, and set the bullet type of these paragraphs to Symbol using ParagraphProperties.BulletType property.
  • Add these paragraphs to the shape using IAutoShape.TextFrame.Paragraphs.Append() method.
  • Save the document to a PowerPoint file using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

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

# Get the first slide
slide = presentation.Slides[0]

# Add a shape to the slide and set the shape style
shape = slide.Shapes.AppendShape(ShapeType.Rectangle, RectangleF(50.0, 50.0, 350.0, 200.0))
shape.Fill.FillType = FillFormatType.none
shape.Line.FillType = FillFormatType.none

# Add text to the default paragraph
paragraph = shape.TextFrame.Paragraphs[0]
paragraph.Text = "Computer Science Subjects:"
paragraph.Alignment = TextAlignmentType.Left
paragraph.TextRanges[0].Fill.FillType = FillFormatType.Solid
paragraph.TextRanges[0].Fill.SolidColor.Color = Color.get_Black()

# Specify the list items
listItems = [
    " Data Structure",
    " Algorithm",
    " Computer Networks",
    " Operating System",
    " Theory of Computations",
    " C Programming",
    " Computer Organization and Architecture"
]

# Create a symbol bulleted list
for item in listItems:
    textParagraph = TextParagraph()
    textParagraph.Text = item
    textParagraph.Alignment = TextAlignmentType.Left
    textParagraph.TextRanges[0].Fill.FillType = FillFormatType.Solid
    textParagraph.TextRanges[0].Fill.SolidColor.Color = Color.get_Black()
    textParagraph.BulletType = TextBulletType.Symbol
    shape.TextFrame.Paragraphs.Append(textParagraph)
    
# Save the result document
presentation.SaveToFile("SymbolBulletedList.pptx", FileFormat.Pptx2013)
presentation.Dispose()

Python: Create Numbed or Bulleted Lists in PowerPoint

Create a Bulleted List with Image Bullets in PowerPoint in Python

To use an image as bullets, you need to set the bullet type of the paragraphs to Picture and then set the image as bullet points using the ParagraphProperties.BulletPicture.EmbedImage property. The following are the detailed steps.

  • Create a Presentation object.
  • Get the first slide using Presentation.Slides[0] property.
  • Append a shape to the slide using ISlide.Shapes.AppendShape() method and set the shape style.
  • Specify the items of the bulleted list inside a list.
  • Create paragraphs based on the list items, and set the bullet type of these paragraphs to Picture using ParagraphProperties.BulletType property.
  • Set an image as bullet points using ParagraphProperties.BulletPicture.EmbedImage property.
  • Add these paragraphs to the shape using IAutoShape.TextFrame.Paragraphs.Append() method.
  • Save the document to a PowerPoint file using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

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

# Get the first slide
slide = presentation.Slides[0]

# Add a shape to the slide and set the shape style
shape = slide.Shapes.AppendShape(ShapeType.Rectangle, RectangleF(50.0, 50.0, 400.0, 180.0))
shape.Fill.FillType = FillFormatType.none
shape.Line.FillType = FillFormatType.none

# Add text to the default paragraph
paragraph = shape.TextFrame.Paragraphs[0]
paragraph.Text = "Project Task To-Do List:"
paragraph.Alignment = TextAlignmentType.Left
paragraph.TextRanges[0].Fill.FillType = FillFormatType.Solid
paragraph.TextRanges[0].Fill.SolidColor.Color = Color.get_Black()

# Specify the list items
listItems = [
    " Define projects and tasks you're working on",
    " Assign people to tasks",
    " Define the priority levels of your tasks",
    " Keep track of the progress status of your tasks",
    " Mark tasks as done when completed"
]

# Create an image bulleted list
for item in listItems:
    textParagraph = TextParagraph()
    textParagraph.Text = item
    textParagraph.Alignment = TextAlignmentType.Left
    textParagraph.TextRanges[0].Fill.FillType = FillFormatType.Solid
    textParagraph.TextRanges[0].Fill.SolidColor.Color = Color.get_Black()
    textParagraph.BulletType = TextBulletType.Picture   
    stream = Stream("icon.png")
    imageData = presentation.Images.AppendStream(stream)
    textParagraph.BulletPicture.EmbedImage = imageData
    shape.TextFrame.Paragraphs.Append(textParagraph)
    stream.Close()
    
# Save the result document
presentation.SaveToFile("ImageBulletedList.pptx", FileFormat.Pptx2013)
presentation.Dispose()

Python: Create Numbed or Bulleted Lists in PowerPoint

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 16