We're glad to announce the release of Spire.Presentation 9.3.4. This version adds SaveToSvgOption for settings PPTX to SVG conversion options, and it also supports retrieving the default font style of a PowerPoint document. Besides, some issues that occurred when converting PPTX to PDF/ SVG, loading and saving files are successfully fixed. See the content below for more details.

Here is a list of changes made in this release

Category ID Description
New feature SPIREPPT-2445 Support retrieving the default font styles of a PowerPoint document.
Presentation presentation = new Presentation();
presentation.LoadFromFile(inputFile);
IAutoShape shape = presentation.Slides[0].Shapes[0] as IAutoShape;
DefaultTextRangeProperties format = shape.TextFrame.Paragraphs[0].TextRanges[0].DisPlayFormat;
File.AppendAllText(outputFile, "text :" + shape.TextFrame.Paragraphs[0].TextRanges[0].Text + "\r\n");
File.AppendAllText(outputFile, "is bold :" + format.IsBold + "\r\n");
File.AppendAllText(outputFile, "is italic :" + format.IsItalic + "\r\n");
New feature SPIREPPT-2451 Adds SaveToSvgOption for settings PPTX to SVG conversion options.
Presentation ppt = new Presentation();
ppt.LoadFromFile(inputFile);
ppt.SaveToSvgOption.SaveUnderlineAsDecoration = true;
byte[] svgByte = ppt.Slides[0].Shapes[0].SaveAsSvgInSlide();
FileStream fs = new FileStream(outputFile + "1.svg", FileMode.Create);
fs.Write(svgByte, 0, svgByte.Length);
fs.Close();
New feature SPIREPPT-2459 Adds the showMasterShapes property to the ILayout class to display background shapes.
Presentation presentation = new Presentation();
presentation.LoadFromFile(@"in.pptx");
bool showMasterShape = presentation.Slides[1].Layout.ShowMasterShapes;
Bug SPIREPPT-2443 Fixes the issue that the gradient color was incorrect when converting PPTX to SVG.
Bug SPIREPPT-2452 Fixes the issue that the image quality degraded when converting PPTX to PDF.
Bug SPIREPPT-2453 Fixes the issue that the text space was lost when converting shape to SVG.
Bug SPIREPPT-2454 Fixes the issue that the content was incorrect when loading and saving PPTX documents.
Click the link to download Spire.Presentation 9.3.4:
More information of Spire.Presentation new release or hotfix:

The AutoFilter feature in Excel is a powerful tool that allows you to quickly filter worksheet data based on specific criteria, making it easier to find and analyze relevant information. When applying AutoFilter to a range of cells, you can display only those rows that meet certain conditions, while hiding the rest of the data. In this article, you will learn how to add or remove AutoFilter in Excel with 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 VS Code 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 in VS Code

Add AutoFilter to Excel Cells in Python

Spire.XLS for Python allows you to apply AutoFilter on a specific cell range through the Worksheet.AutoFilters.Range property. The following are the detailed steps:

  • Create a Workbook instance.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[sheetIndex] property.
  • Add an AutoFilter to a specified cell range using Worksheet.AutoFilters.Range property.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "Data.xlsx"
outputFile = "ExcelAutoFilter.xlsx"

# Create a Workbook instance
workbook = Workbook()

# Load an Excel file
workbook.LoadFromFile(inputFile)

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

# Create an AutoFilter in the sheet and specify the range to be filtered
sheet.AutoFilters.Range = sheet.Range["A1:C1"]

# Save the result file
workbook.SaveToFile(outputFile, ExcelVersion.Version2016)
workbook.Dispose()

Python: Add or Remove AutoFilter in Excel

Apply Date AutoFilter in Excel in Python

If you need to explore information related to specific dates or time, you can apply a date filter to the selected range using the Workbook.AutoFilters.AddDateFilter(column: IAutoFilter, dateTimeGroupingType: DateTimeGroupingType, year: int, Month: int, day: int, hour: int, minute: int, second: int) method. The following are detailed steps.

  • Create a Workbook instance.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[sheetIndex] property.
  • Add an AutoFilter to a specified range using Workbook.AutoFilters.Range property.
  • Get the column to be filtered.
  • Call the Workbook.AutoFilters.AddDateFilter() method to add a date filter to the column to filter data related to a specified year/month/date, etc.
  • Apply the filter using Workbook.AutoFilters.Filter() method.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "Data.xlsx"
outputFile = "DateAutoFilter.xlsx"

# Create a Workbook instance
workbook = Workbook()

#Load an Excel file
workbook.LoadFromFile(inputFile)

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

# Create an auto filter in the sheet and specify the range to be filtered
sheet.AutoFilters.Range = sheet.Range["A1:A12"]

# Get the column to be filtered
filtercolumn = sheet.AutoFilters[0]

# Add a date filter to filter data related to February 2022
sheet.AutoFilters.AddDateFilter(filtercolumn, DateTimeGroupingType.Month, 2022, 2, 0, 0, 0, 0)

# Apply the filter
sheet.AutoFilters.Filter()

# Save the result file
workbook.SaveToFile(outputFile, ExcelVersion.Version2016)
workbook.Dispose()

Python: Add or Remove AutoFilter in Excel

Apply Custom AutoFilter in Excel in Python

The Workbook.AutoFilters.CustomFilter(column: FilterColumn, operatorType: FilterOperatorType, criteria: Object) method allows you to create custom filters based on certain criteria. For example, you can filter data that contains specific text. The following are detailed steps.

  • Create a Workbook instance.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[sheetIndex] property.
  • Add an AutoFilter to a specified range using Workbook.AutoFilters.Range property.
  • Get the column to be filtered.
  • Add a custom filter to the column to filter data containing the specified string using Workbook.AutoFilters.CustomFilter() method.
  • Apply the filter using Workbook.AutoFilters.Filter() method.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "Data.xlsx"
outputFile = "CustomAutoFilter.xlsx"

# Create a Workbook instance
workbook = Workbook()

#Load an Excel file
workbook.LoadFromFile(inputFile)

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

# Create an auto filter in the sheet and specify the range to be filtered
sheet.AutoFilters.Range = sheet.Range["G1:G12"]

# Get the column to be filtered
filtercolumn = sheet.AutoFilters[0]

# Add a custom filter to filter data containing the string "Grocery"
strCrt = String("Grocery")
sheet.AutoFilters.CustomFilter(filtercolumn, FilterOperatorType.Equal, strCrt)

# Apply the filter
sheet.AutoFilters.Filter()

# Save the result file
workbook.SaveToFile(outputFile, ExcelVersion.Version2016)
workbook.Dispose()

Python: Add or Remove AutoFilter in Excel

Remove AutoFilter in Excel in Python

In addition to adding AutoFilters in Excel files, Spire.XLS for Python also support removing or deleting the AutoFilters from Excel through the Worksheet.AutoFilters.Clear() method. The following are detailed steps.

  • Create a Workbook instance.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[sheetIndex] property.
  • Remove AutoFilter from the worksheet using Worksheet.AutoFilters.Clear() method.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "CustomAutoFilter.xlsx"
outputFile = "RemoveAutoFilter.xlsx"

# Create a Workbook instance
workbook = Workbook()

# Load an Excel file
workbook.LoadFromFile(inputFile)

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

# Delete AutoFilter from the sheet
sheet.AutoFilters.Clear()

# Save the result file
workbook.SaveToFile(outputFile, ExcelVersion.Version2016)
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.

Adding, modifying, and removing footers in a PowerPoint document is crucial for enhancing the professionalism and readability of a presentation. By adding footers, you can include key information such as presentation titles, authors, dates, or page numbers, which helps the audience better understand the content. Modifying footers allows you to update information, making it more attractive and practical. Additionally, removing footers is also necessary, especially in certain situations such as when specific information is not required to be displayed at the bottom of each page for a particular occasion. In this article, you will learn how to add, modify, or remove footers in PowerPoint documents in C# using Spire.Presentation for .NET.

Install Spire.Presentation for .NET

To begin with, you need to add the DLL files included in the Spire.Presentation for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Presentation

C# Add Footers in PowerPoint Documents

Spire.Presentation enables the addition of footer, slide number, and date placeholders at the bottom of PowerPoint document pages to uniformly add the same footer content across all pages. Here are the detailed steps:

  • Create a Presentation object.
  • Load a PowerPoint document using the lisentation.LoadFromFile() method.
  • Set Presentation.FooterVisible = true to make the footer visible and set the footer text.
  • Set Presentation.SlideNumberVisible = true to make slide numbers visible, then iterate through each slide, check for the existence of a slide number placeholder, and modify the text to "Slide X" format if found.
  • Set Presentation.DateTimeVisible = true to make date and time visible.
  • Use the Presentation.SetDateTime() method to set the date format.
  • Save the document using the Presentation.SaveToFile() method.
  • C#
using Spire.Presentation;

namespace SpirePresentationDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Presentation object
            Presentation presentation = new Presentation();

            // Load the presentation from a file
            presentation.LoadFromFile("Sample1.pptx");

            // Set the footer visible
            presentation.FooterVisible = true;

            // Set the footer text to "Spire.Presentation"
            presentation.SetFooterText("Spire.Presentation");

            // Set slide number visible
            presentation.SlideNumberVisible = true;

            // Iterate through each slide in the presentation
            foreach (ISlide slide in presentation.Slides)
            {
                foreach (IShape shape in slide.Shapes)
                {
                    if (shape.Placeholder != null)
                    {
                        // If it is a slide number placeholder
                        if (shape.Placeholder.Type.Equals(PlaceholderType.SlideNumber))
                        {
                            TextParagraph textParagraph = (shape as IAutoShape).TextFrame.TextRange.Paragraph;
                            String text = textParagraph.Text;

                            // Modify the slide number text to "Slide X"
                            textParagraph.Text = "Slide " + text;
                        }
                    }
                }
            }

            // Set date time visible
            presentation.DateTimeVisible = true;

            // Set date time format
            presentation.SetDateTime(DateTime.Now, "MM/dd/yyyy");

            // Save the modified presentation to a file
            presentation.SaveToFile("AddFooter.pptx", FileFormat.Pptx2016);

            // Dispose of the Presentation object resources
            presentation.Dispose();
        }
    }
}

C#: Add, Modify, or Remove Footers in PowerPoint Documents

C# Modify Footers in PowerPoint Documents

To modify footers in a PowerPoint document, you first need to individually inspect the shapes on each slide, identify footer placeholders, page number placeholders, etc., and then set specific content and formats for each type of placeholder. Here are the detailed steps:

  • Create a Presentation object.
  • Load a PowerPoint document using the Presentation.LoadFromFile() method.
  • Use the Presentation.Slides[index] property to retrieve a slide.
  • Use a for loop to iterate through the shapes on the slide, individually checking each shape to determine if it is a placeholder for a footer, page number, etc., and then modify its content or format accordingly.
  • Save the document using the Presentation.SaveToFile() method.
  • C#
using Spire.Presentation;

namespace SpirePresentationDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Presentation object
            Presentation presentation = new Presentation();

            // Load the presentation from a file
            presentation.LoadFromFile("Sample2.pptx");

            // Get the first slide
            ISlide slide = presentation.Slides[0];

            // Iterate through shapes in the slide
            for (int i = 0; i < slide.Shapes.Count; i++)
            {
                // Check if the shape is a placeholder
                if (slide.Shapes[i].Placeholder != null)
                {
                    // Get the placeholder type
                    PlaceholderType type = slide.Shapes[i].Placeholder.Type;

                    // If it is a footer placeholder
                    if (type == PlaceholderType.Footer)
                    {
                        // Convert the shape to IAutoShape type
                        IAutoShape autoShape = (IAutoShape)slide.Shapes[i];

                        // Set the text content to "E-ICEBLUE"
                        autoShape.TextFrame.Text = "E-ICEBLUE";

                        // Modify the text font
                        ChangeFont1(autoShape.TextFrame.Paragraphs[0]);
                    }
                    // If it is a slide number placeholder
                    if (type == PlaceholderType.SlideNumber)
                    {
                        // Convert the shape to IAutoShape type
                        IAutoShape autoShape = (IAutoShape)slide.Shapes[i];

                        // Modify the text font
                        ChangeFont1(autoShape.TextFrame.Paragraphs[0]);
                    }
                }
            }

            // Save the modified presentation to a file
            presentation.SaveToFile("ModifyFooter.pptx", FileFormat.Pptx2016);

            // Dispose of the Presentation object resources
            presentation.Dispose();
        }
       static void ChangeFont1(TextParagraph paragraph)
        {
            // Iterate through each text range in the paragraph
            foreach (TextRange textRange in paragraph.TextRanges)
            {
                // Set the text style to italic
                textRange.IsItalic = TriState.True;

                // Set the text font
                textRange.EastAsianFont = new TextFont("Times New Roman");

                // Set the text font size to 34
                textRange.FontHeight = 34;

                // Set the text color
                textRange.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.Solid;
                textRange.Fill.SolidColor.Color = System.Drawing.Color.LightSkyBlue;
            }
        }
   }  
}

C#: Add, Modify, or Remove Footers in PowerPoint Documents

C# Remove Footers in PowerPoint Documents

To remove footers from a PowerPoint document, you first need to locate footer placeholders, page number placeholders, date placeholders, etc., within the slides, and then remove them from the collection of shapes on the slide. Here are the detailed steps:

  • Create a Presentation object.
  • Load a PowerPoint document using the Presentation.LoadFromFile() method.
  • Use the Presentation.Slides[index] property to retrieve a slide.
  • Use a for loop to iterate through the shapes on the slide, check if it is a placeholder, and if it is a footer placeholder, page number placeholder, date placeholder, remove it from the slide.
  • Save the document using the Presentation.SaveToFile() method.
  • C#
using Spire.Presentation;

namespace SpirePresentationDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Presentation object
            Presentation presentation = new Presentation();

            // Load the presentation from a file
            presentation.LoadFromFile("Sample2.pptx");

            // Get the first slide
            ISlide slide = presentation.Slides[0];

            // Iterate through shapes in the slide in reverse order
            for (int i = slide.Shapes.Count - 1; i >= 0; i--)
            {
                // Check if the shape is a placeholder
                if (slide.Shapes[i].Placeholder != null)
                {
                    // Get the placeholder type
                    PlaceholderType type = slide.Shapes[i].Placeholder.Type;

                    // If it is a footer placeholder, slide number placeholder, or date placeholder
                    if (type == PlaceholderType.Footer || type == PlaceholderType.SlideNumber || type == PlaceholderType.DateAndTime)
                    {
                        // Remove it from the slide
                        slide.Shapes.RemoveAt(i);
                    }
                }
            }

            // Save the modified presentation to a file
            presentation.SaveToFile("RemoveFooter.pptx", FileFormat.Pptx2016);

            // Dispose of the Presentation object resources
            presentation.Dispose();
        }
    }
}

C#: Add, Modify, or Remove Footers in PowerPoint 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.

Thursday, 21 March 2024 09:11

Python: Encrypt or Decrypt Word Documents

Protecting valuable and sensitive information from unauthorized access is a crucial task for individuals and organizations alike. When it comes to sharing and storing confidential Word documents, such as financial records, legal documents, or personal records, encrypting the documents provides extra protection for their security and confidentiality. Moreover, using Python, users can easily encrypt large numbers of Word documents. This article shows how to use Spire.Doc for Python to encrypt Word documents in Python programs.

Install Spire.Doc for Python

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

pip install Spire.Doc

If you are unsure how to install, please refer to: How to Install Spire.Doc for Python in VS Code

Encrypt a Word Document with a Password

Using the Document.Encrypt(password: str) method provided by Spire.Doc for Python, developers can set an open password for a Word document, ensuring that only authorized people can open and view the document. The detailed steps for encrypting a Word document with a password are as follows:

  • Create an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Encrypt the document using Document.Encrypt() method.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an instance of Document class
doc = Document()

# Load a Word document
doc.LoadFromFile("Sample.docx")

# Encrypt the document
doc.Encrypt("password")

# Save the document
doc.SaveToFile("output/EncryptedDocument.docx")
doc.Close()

Python: Encrypt or Decrypt Word Documents

Change the Encryption from a Word Document

By passing the password as the parameter, developers can load an encrypted document using Document.LoadFromFile(fileName: str, fileFormat: FileFormat, password: str) method. After loading the encrypted document, the Document.Encrypt() method can be used to set a new password. The detailed steps are as follows:

  • Create an instance of Document class.
  • Load an encrypted Word document using Document.LoadFromFile() method.
  • Change the password of the document using Document.Encrypt() method.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an instance of Document class
doc = Document()

# Load an encrypted Word document
doc.LoadFromFile("output/EncryptedDocument.docx", FileFormat.Docx, "password")

# Change the password
doc.Encrypt("password1")

# Save the document
doc.SaveToFile("output/ChangeDocument.docx")
doc.Close()

Remove the Password from a Word Document

After loading an encrypted Word document, developers can also use Document.RemoveEncryption() method to remove the encryption from the document directly, thus making the document available to all users. The detailed steps are as follows:

  • Create an instance of Document class.
  • Load an encrypted Word document using Document.LoadFromFile() method.
  • Remove the password using Document.RemoveEncryption() method.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an instance of Document class
doc = Document()

# Load an encrypted Word document
doc.LoadFromFile("output/EncryptedDocument.docx", FileFormat.Auto, "password")

# Remove the password
doc.RemoveEncryption()

# Save the document
doc.SaveToFile("output/RemovePassword.docx", FileFormat.Docx)
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.

Thursday, 21 March 2024 01:08

Python: Flatten Forms in PDF

Flattening forms in PDF means transforming the interactive form fields (such as text boxes, checkboxes, and drop-down menus) into static content. Once a form is flattened, it cannot be edited or filled out anymore. When you need to maintain a permanent and unalterable record of a completed form, flattening is essential. This ensures that the data entered into the form fields cannot be modified or tampered with, providing a reliable reference for future use. In this article, we will demonstrate how to flatten forms in PDF 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 VS Code 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 in VS Code

Flatten All Forms in a PDF in Python

Spire.PDF for Python provides the PdfDocument.Form.IsFlatten property, which enables you to flatten all forms in a PDF file. The detailed steps are as follows.

  • Create an object of the PdfDocument class.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Flatten all forms in the PDF file by setting the PdfDocument.Form.IsFlatten property to True.
  • Save the result file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Specify the input and output PDF file paths
input_file = "Form.pdf"
output_file = "FlattenAll.pdf"

# Create an object of the PdfDocument class
doc = PdfDocument()
# Load a PDF file
doc.LoadFromFile(input_file)

# Flatten all forms in the PDF file
doc.Form.IsFlatten = True

# Save the result file
doc.SaveToFile(output_file)
doc.Close()

Python: Flatten Forms in PDF

Flatten a Specific Form in a PDF in Python

To flatten a specific form in a PDF file, you can use the PdfField.Flatten property. The detailed steps are as follows.

  • Create an object of the PdfDocument class.
  • Load a PDF file using the PdfDocument.LoadFromFile() method.
  • Get the forms of the PDF file using PdfDocument.Form property.
  • Get a specific form by its index or name using PdfFormWidget.FieldsWidget.get_Item() method.
  • Flatten the form by setting the PdfField.Flatten property to True.
  • Save the result file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Specify the input and output PDF file paths
input_file = "Form.pdf"
output_file = "FlattenSpecific.pdf"

# Create an object of the PdfDocument class
doc = PdfDocument()
# Load a PDF file
doc.LoadFromFile(input_file)

# Get the forms of the PDF file
loadedForm = doc.Form

# Get a specific form by its index or name
formWidget = PdfFormWidget(loadedForm)
form = formWidget.FieldsWidget.get_Item(2)
# form = formWidget.FieldsWidget.get_Item("Address")

# Flatten the specific form
form.Flatten = True

# Save the result file
doc.SaveToFile(output_file)
doc.Close()

Python: Flatten Forms in PDF

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.

We are pleased to announce the release of Spire.Doc for Python 12.3.2. This version supports getting revisions. It also fixes the issue that the program threw a "TypeError" error when the keyword was not matched using FindString(). More details are listed below.

Here is a list of changes made in this release

Category ID Description
New feature SPIREDOC-10366 Supports getting revisions.
doc1 = Document(inputFile_1)
doc2 = Document(inputFile_2)
doc1.Compare(doc2, "Author")
revisions = DifferRevisions(doc1)
content = ""
m = 0
n = 0
insertRevisionList = revisions.InsertRevisions
deleteRevisionList = revisions.DeleteRevisions
for i in range(0, insertRevisionList.__len__()):
    # if isinstance(insertRevisionList[i], TextRange):
    if insertRevisionList[i].DocumentObjectType == DocumentObjectType.TextRange:
          m += 1
          textRange = TextRange(insertRevisionList[i])
          content += "insert #" + m.__str__() + ":" + textRange.Text + '\n'        content += "=====================" + '\n'
for i in range(0, deleteRevisionList.__len__()):
    # if isinstance(deleteRevisionList[i], TextRange):
    if deleteRevisionList[i].DocumentObjectType == DocumentObjectType.TextRange:
           n += 1
           textRange = TextRange(deleteRevisionList[i])
           content += "delete #" + n.__str__() + ":" + textRange.Text + '\n'        content += "=====================" + '\n'
New feature SPIREDOC-10350 Supports TextSelection.GetAsRange(), TextSelection.GetRanges() and TextSelection.GetAsRange(true) methods.
document = Document()
document.LoadFromFile(inputFile)
textSelections = document.FindAllString("word", False, True)
for selection in textSelections:
    selection.GetAsRange();
    selection.GetRanges();
    selection.GetAsRange(true);
Bug SPIREDOC-10344 Fixes the issue that the program threw a "TypeError" error when the keyword was not matched using FindString().
Click the link below to download Spire.Doc for Python 12.3.2:
Wednesday, 20 March 2024 06:59

Rewrite Excel using AI

With the advancement of AI technology, we are entering a new era where the capabilities of Excel can be revolutionized and expanded through artificial intelligence. Leveraging AI technology, we can reconstruct Excel's routine functions, such as merging data from multiple ranges, intelligently populating data, and even exploring intelligent generation strategies based on existing content, further enabling the capability to directly transform textual descriptions into visual representations. This can significantly enhance efficiency and reduce the burden of manual operations for users. This article will explore how to rewrite Excel content using Spire.XLS AI.

Install Spire.XLS for .NET

The Excel AI integrated into Spire.XLS for .NET package, hence to begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

Request a License Key of AI Product

A license key is required to run Spire.XLS AI, please contact our sales department (sales@e-iceblue.com) to request one.

Use AI to Rewrite Excel

Spire.XLS AI provides the ExcelAI class, which empowers users with the ability to intelligently rewrite Excel worksheets. Below is an overview of the key methods involved in implementing this functionality:

  • ExcelMerge(CellRange descRange, List<CellRange> srcRanges, CellRange titleRange) :This method is used to merges the data from multiple ranges into a destination range with the given title range.
    • Please note that, to ensure the AI can correctly identify and match data across different source cell ranges, title within each range intended for merging should remain consistent or have clear correspondences. If titles within the source data ranges are inconsistent or missing, it could lead to the AI being unable to accurately map the data, thus impacting the accuracy of the merging outcome.
  • ExcelFill(CellRange dataRange, CellRange descRange, bool containTitle, List<int> fillColumnIndexs, List<string> keys = null): This method is used to fill the Excel worksheet with data extracted from the specified data range.
    • The "descRange" parameter represents the description range, which has a description corresponding to the source data to ensure that AI can intelligently match and fill in.
    • The "containTitle" boolean indicates whether the data range contains a title row.
    • The "fillColumnIndices" parameter represents the index of the data source column to be filled.
    • The "keys" parameter is an optional parameter used to associate and match the data during the filling process, when provided, the ExcelFill method utilizes these key values for data correspondence, if null, the method will automatically identify and associate data based on the description information within the descRange.
  • ExcelGenerate(List<CellRange> srcRanges): This method is used to analyze the content and context within cell ranges and leverage artificial intelligence technology to generate corresponding calculations, aggregations, or other operations based on natural language instructions. ExcelAI class will recognize and parse the natural language instructions within the markers enclosed in <ai>...</ai>.
  • ImageGenerate(string description): This method is designed to intelligently create images that align with natural language text descriptions provided as input. It further extends its functionality through an enhanced overloaded interface, namely ImageGenerate(String description, ImageGenerationModel model, ImageGenerationSize size), which allows users to specify the image model and size.

Merge Data from Multiple Ranges in C#

The following steps introduce how to merge data from multiple ranges in worksheet:

  • Create a Workbook class instance.
  • Load an Excel document using Workbook.LoadFromFile() method.
  • Create a new Workbook class instance and fill data in worksheet.
  • Create an ExcelAI class instance.
  • Reset the user's all chat history by ExcelAI.ResetUserHistory() method.
  • Create a list and store multiple ranges that need to be merged.
  • Specify the destination range and title range.
  • Merge the data from the ranges stored in list using ExcelAI.ExcelMerge() method.
  • Save the workbook using Workbook.SaveToFile () method.
  • C#
using Spire.Xls;
using Spire.Xls.AI;
using System.Collections.Generic;

// Create a new Workbook instance and load source Excel file
Workbook wb1 = new Workbook();
wb1.LoadFromFile("MergeSource.xlsx");

// Create another new instance of Workbook
Workbook wb2 = new Workbook();

// Access the first Worksheet in wb2
Worksheet sheet = wb2.Worksheets[0];

// Fill data into cells
sheet.Range["A1"].Text = "Name"; 
sheet.Range["B1"].Text = "Capital";
sheet.Range["C1"].Text = "Continent"; 
sheet.Range["D1"].Text = "Area";
sheet.Range["E1"].Text = "Population";
sheet.Range["A2"].Text = "Argentina";
sheet.Range["B2"].Text = "Kingston"; 
sheet.Range["C2"].Text = "North America"; 
sheet.Range["D2"].NumberValue = 11424; 
sheet.Range["E2"].NumberValue = 2500000;

// Create a new ExcelAI instance
ExcelAI excelAI = new ExcelAI();

// Reset the user's all chat history
excelAI.ResetUserHistory();

// Create a list of CellRange objects to specify the source data ranges to merge
var srcRanges = new List();
srcRanges.Add(sheet["A1:E2"]); 
srcRanges.Add(wb1.Worksheets[0].Range["A1:E7"]);
srcRanges.Add(wb1.Worksheets[1].Range["A1:E2"]);

// Specify the destination range in wb1 where merged data will be placed
var descRange = wb1.Worksheets[0].Range["A10"];

// Specify the title range for merging purposes
var titleRange = wb1.Worksheets[0].Range["A1:E1"];

// Merge the data from source ranges into the destination range with the given title range
string jsonStr = excelAI.ExcelMerge(descRange, srcRanges, titleRange);

// Save the Excel file
wb1.SaveToFile("Merge_out.xlsx", ExcelVersion.Version2016);

Rewrite Excel using AI

Fill Excel with Data Extracted from Specified Range in C#

The following steps introduce how to intelligently fill excel with data extracted from specified range:

  • Create a Workbook class instance.
  • Load an Excel document using Workbook.LoadFromFile() method.
  • Get the first worksheet.
  • Specify the data range and description range within the worksheet.
  • Create an ExcelAI class instance.
  • Reset the user's all chat history by ExcelAI.ResetUserHistory() method.
  • Fill the worksheet based on given data and descriptions using ExcelAI.ExcelFill() method.
  • Save the workbook using Workbook.SaveToFile () method.
  • C#
using Spire.Xls;
using Spire.Xls.AI;
using System.Collections.Generic;

// Create a new Workbook instance 
Workbook wb = new Workbook();

// Load an Excel file from disk
wb.LoadFromFile("FillSource.xlsx");

// Access the first worksheet
var worksheet = wb.Worksheets[0];

// Define the data range
var dataRange = worksheet.Range["A1:E11"];

// Specify the description range 
var descRange = worksheet.Range["B14"];

// Create a new ExcelAI instance 
ExcelAI excelAI = new ExcelAI();

// Reset the user's all chat history
excelAI.ResetUserHistory();

// Intelligently fill the worksheet based on given data and descriptions
string jsonStr = excelAI.ExcelFill(dataRange, descRange, true, new List() { 0, 1,2 }, new List() { "Name", "Capital", "Continent" });

// Save the Excel file
wb.SaveToFile("Fill_out.xlsx", ExcelVersion.Version2016);

Rewrite Excel using AI

Generate Data based on Existing Content in C#

The following steps introduce how to generate data based on existing content in worksheet:

  • Create a Workbook class instance.
  • Load an Excel document using Workbook.LoadFromFile() method.
  • Get the first worksheet.
  • Get the index of last data row and last data column.
  • Fill text and insert AI instructions in different cells to return the total number of students, the sum formula and the ranking information.
  • Create a list and store allocated ranges from worksheet.
  • Create an ExcelAI class instance.
  • Generate intelligent processing information using ExcelAI.ExcelGenerate() method.
  • Save the workbook using Workbook.SaveToFile () method.
  • C#
using Spire.Xls;
using Spire.Xls.AI;
using System.Collections.Generic;

// Create a new Workbook instance 
Workbook wb = new Workbook();

// Load an Excel file from disk
wb.LoadFromFile("StudentScoreCard.xlsx");

// Get the first worksheet
Worksheet worksheet = wb.Worksheets[0];

// Calculate the index of the last data row
int lastrow = worksheet.LastDataRow;

// Calculate the index of the last data column 
int lastcol = worksheet.LastDataColumn;

// Fill text in specified cell
worksheet.Range[lastrow + 1, 1].Text = "Total:";

// Insert an AI instruction in cell to return the total number of students
worksheet.Range[lastrow + 1, 2].Text = "Return total number of student";

// Fill text in specified cell
worksheet.Range[2, lastcol + 1].Text = "Sum:";
worksheet.Range[2, lastcol + 2].Text = "Rank:";

for (int i = 3; i <= lastrow; i++)
{
    // Insert AI instructions in different cells to return the sum formula for this row's score and the ranking information for the student
    worksheet.Range[i, lastcol + 1].Text = "Return the summation formula";
    worksheet.Range[i, lastcol + 2].Text = "Return the ranking of the student";
}

// Create a list to store ranges
List ranges = new List();

// Add entire allocated range in list
ranges.Add(worksheet.AllocatedRange);

// Create a new ExcelAI instance 
ExcelAI excelAI = new ExcelAI();

// Generate intelligent processing information based on the provided cell ranges
string jsonStr = excelAI.ExcelGenerate(ranges);

// Save the Excel file
wb.SaveToFile("Generate_out.xlsx", ExcelVersion.Version2016);

Rewrite Excel using AI

Generate Images based on Text Description in C#

The following steps introduce how to generate images based on text description:

  • Create an ExcelAI class instance.
  • Generate image streams based on given descriptions using ExcelAI.ImageGenerate() method.
  • Create a list to store the image streams.
  • Create a Workbook class instance.
  • Iterate over image stream from list and write them to PNG.
  • Create empty worksheets and add the image streams in specified cells.
  • Save the workbook using Workbook.SaveToFile () method.
  • C#
using Spire.AI.Api;
using Spire.Xls;
using Spire.Xls.AI;
using System;
using System.Collections.Generic;
using System.IO;

// Define three text descriptions for generating images
string description1 = "A little dog running in the countryside";
string description2 = "A road full of beautiful flowers";
string description3 = "Students learning in the classroom";

// Create a new ExcelAI instance
ExcelAI excelAI = new ExcelAI();

// Generate image streams based on the descriptions
var imageStream1 = excelAI.ImageGenerate(description1, ImageGenarationModel.STABLE_DIFFUSION_XL_1024_V1_0, ImageGenarationSize.I1024x1024);
var imageStream2 = excelAI.ImageGenerate(description2, ImageGenarationModel.STABLE_DIFFUSION_XL_1024_V1_0, ImageGenarationSize.I1024x1024);
var imageStream3 = excelAI.ImageGenerate(description3);

// Create a list to store the generated image streams
var imageStreams = new List();

// Add the generated image streams to the list
imageStreams.Add(imageStream1);
imageStreams.Add(imageStream2);
imageStreams.Add(imageStream3);

// Create a new Workbook instance and clear any existing worksheets
Workbook wb = new Workbook();
wb.Worksheets.Clear();

// Iterate over each image stream in the list
for (int i = 0; i < imageStreams.Count; i++)
{
    // Generate a unique filename for the image
    string randomFileName = Guid.NewGuid().ToString() + ".png";

    // Create a new file with the generated filename and write the image stream to it
    using (Stream outputStream = File.Create(randomFileName))
    {
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = imageStreams[i].Read(buffer, 0, buffer.Length)) > 0)
        {
            outputStream.Write(buffer, 0, bytesRead);
        }
    }

    // Create a new empty worksheet in the workbook
    Worksheet worksheet = wb.CreateEmptySheet(String.Format("ImageSheet{0}",i+1));

    // Add the image stream to the worksheet at cell (1, 1)
    worksheet.Pictures.Add(1, 1, imageStreams[i]);
}

// Save the Excel file
wb.SaveToFile("GenerateImage_out.xlsx", ExcelVersion.Version2016);

Rewrite Excel using AI

Pie charts and doughnut charts are two popular types of data visualization tools that are widely used to show the proportional distribution of categories within the whole. Both charts can serve as powerful communication aids, allowing viewers to quickly grasp the significance of each component and how it relates to the overall picture.

While pie charts and doughnut charts share many similarities, they also have unique characteristics that make them suitable for different analytical scenarios. In this article, you will learn how to create a pie chart or a doughnut chart in PowerPoint with 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 VS Code 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 in VS Code

Create a Pie Chart in PowerPoint with Python

Pie charts are designed to resemble a circle, which is divided into sections or "slices", with each slice representing a portion of the whole.

With Spire.Prensetion for Python, you can add a pie chart to a presentation slide using the ISlide.Shapes.AppendChartInit(type: ChartType, rectangle: RectangleF, init: bool) method and specify the chart type as Pie. The following are the detailed steps.

  • Create a Presentation instance.
  • Get the first slide using Prenstion.Slides[] property.
  • Add a pie chart at a specified location on the side using ISlide.Shapes.AppendChartInit(type: ChartType, rectangle RectangleF, init bool).
  • Set and format the chart title.
  • Define some data and append the data 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.
  • Set to show label value and percentage value.
  • Save the result file using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation instance
presentation = Presentation()

# Add a pie chart at a specified location on the first slide
rect = RectangleF.FromLTRB (40, 100, 590, 420)
chart = presentation.Slides[0].Shapes.AppendChartInit (ChartType.Pie, rect, False)

# Set and format chart title
chart.ChartTitle.TextProperties.Text = "Sales by Quarter"
chart.ChartTitle.TextProperties.IsCentered = True
chart.ChartTitle.Height = 30
chart.HasTitle = True

# Define some data
quarters = ["1st Qtr", "2nd Qtr", "3rd Qtr", "4th Qtr"]
sales = [210, 320, 180, 460]

# Append data to ChartData, which represents a data table where the chart data is stored
chart.ChartData[0,0].Text = "Quarters"
chart.ChartData[0,1].Text = "Sales"
i = 0
while i < len(quarters):
    chart.ChartData[i + 1,0].Text = quarters[i]
    chart.ChartData[i + 1,1].NumberValue = sales[i]
    i += 1

# Set series labels and category labels
chart.Series.SeriesLabel = chart.ChartData["B1","B1"]
chart.Categories.CategoryLabels = chart.ChartData["A2","A5"]

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

# Add data points to series
for i, unusedItem in enumerate(chart.Series[0].Values):
    cdp = ChartDataPoint(chart.Series[0])
    cdp.Index = i
    chart.Series[0].DataPoints.Add(cdp)

# Fill each data point with a different color
chart.Series[0].DataPoints[0].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[0].Fill.SolidColor.Color = Color.get_RosyBrown()
chart.Series[0].DataPoints[1].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[1].Fill.SolidColor.Color = Color.get_LightBlue()
chart.Series[0].DataPoints[2].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[2].Fill.SolidColor.Color = Color.get_LightPink()
chart.Series[0].DataPoints[3].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[3].Fill.SolidColor.Color = Color.get_MediumPurple()

# Set the data labels to display label value and percentage value
chart.Series[0].DataLabels.LabelValueVisible = True
chart.Series[0].DataLabels.PercentValueVisible = True

# Save the result file 
presentation.SaveToFile("CreatePieChart.pptx", FileFormat.Pptx2016)
presentation.Dispose()

Python: Create a Pie Chart or a Doughnut Chart in PowerPoint

Create a Doughnut Chart in PowerPoint with Python

Doughnut charts are very similar to pie charts, with the primary difference being the presence of a "hole" in the center. This hole can be used to display additional information or to maintain a cleaner look.

To add a donut chart to a presentation slide, you can specify the ChartType parameter of ISlide.Shapes.AppendChartInit() method as Doughnut. The following are the detailed steps.

  • Create a Presentation instance.
  • Get the first slide using Prenstion.Slides[] property.
  • Add a doughnut chart at a specified location on the side using ISlide.Shapes.AppendChartInit(type: ChartType, rectangle: RectangleF, init: bool).
  • Define some data and append the data 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.
  • Set to show label value and percentage value.
  • Save the result file using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation instance
presentation = Presentation()

# Add a doughnut chart at a specified location on the first slide
rect = RectangleF.FromLTRB (80, 100, 630, 420)
chart = presentation.Slides[0].Shapes.AppendChartInit(ChartType.Doughnut, rect, False)

# Set and format chart title
chart.ChartTitle.TextProperties.Text = "Annual Report"
chart.ChartTitle.TextProperties.IsCentered = True
chart.ChartTitle.Height = 30

# Define some data
years = ["Year 2020", "Year 2021", "Year 2022", "Year 2023"]
sales = [16500, 28000, 43200, 60000]

# Append data to ChartData, which represents a data table where the chart data is stored
chart.ChartData[0,0].Text = "Quarters"
chart.ChartData[0,1].Text = "Sales"
i = 0
while i < len(years):
    chart.ChartData[i + 1,0].Text = years[i]
    chart.ChartData[i + 1,1].NumberValue = sales[i]
    i += 1

# Set series labels and category labels
chart.Series.SeriesLabel = chart.ChartData["B1","B1"]
chart.Categories.CategoryLabels = chart.ChartData["A2","A5"]

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

# Add data points to series
for i, item in enumerate(chart.Series[0].Values):
    cdp = ChartDataPoint(chart.Series[0])
    cdp.Index = i
    chart.Series[0].DataPoints.Add(cdp)

# Fill each data point with a different color
chart.Series[0].DataPoints[0].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[0].Fill.SolidColor.Color = Color.get_LightBlue()
chart.Series[0].DataPoints[1].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[1].Fill.SolidColor.Color = Color.get_MediumPurple()
chart.Series[0].DataPoints[2].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[2].Fill.SolidColor.Color = Color.get_DarkGray()
chart.Series[0].DataPoints[3].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[3].Fill.SolidColor.Color = Color.get_DarkOrange()

# Set the data labels to display label value and percentage value
chart.Series[0].DataLabels.LabelValueVisible = True
chart.Series[0].DataLabels.PercentValueVisible = True

# Set the hole size of the doughnut chart
chart.Series[0].DoughnutHoleSize = 50

# Save the result file
presentation.SaveToFile("DoughnutChart.pptx", FileFormat.Pptx2016)
presentation.Dispose()

Python: Create a Pie Chart or a Doughnut Chart 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.

We are pleased to announce the release of Spire.XLS 14.3.3. This version supports PivotTable grouping functionality. In addition, it also supports adding the FindAll() method to CellRange and setting "Repeat All Item Labels" for PivotTable. Some known issues have also been successfully fixed in this version, such as the issue that the content was incorrect after saving Excel files. More details are listed below.

Here is a list of changes made in this release

Category ID Description
New feature SPIREXLS-765 Supports PivotTable grouping function.
XlsPivotTable pt = worksheet.PivotTables[0] as XlsPivotTable;
IPivotField field = pt.RowFields[0];
DateTime start = new DateTime(2024, 5, 6);
DateTime end = new DateTime(2024, 10, 6);
PivotGroupByTypes[] types = new PivotGroupByTypes[]{ PivotGroupByTypes.Days };
field.CreateGroup(start, end, types, 1);
New feature SPIREXLS-5091 Supports adding FindAll() method to CellRange.
Workbook workbook = new Workbook();
workbook.LoadFromFile(@"test.xlsx");
Worksheet sheet = workbook.Worksheets[0];
sheet.Range["A1"].FindAll()
New feature SPIREXLS-5123 Supports setting "Repeat All Item Labels" for PivotTable.
foreach (XlsPivotTable pt in wb.Worksheets["PivotTable"].PivotTables)
 {
 pt.Options.RepeatAllItemLabels = true; 
 }
Bug SPIREXLS-5097 Fixes the issue that the content was incorrect after saving Excel files.
Bug SPIREXLS-5103 Fixes the issue that the sheet content exported using ExportDataTable was incorrect.
Bug SPIREXLS-5105 Fixes the issue that formula values were incorrect when converting Excel to PDF.
Bug SPIREXLS-5106 Fixes the issue that the program threw "Size of image is too large" exception when converting Excel to images.
Bug SPIREXLS-5110 Fixes the issue that the PivotTable column names were inconsistent when converting Excel to pictures.
Bug SPIREXLS-5122 Fixes the issue that there were some extra blank comments in result files after using CellRange.Comment.Text.
Bug SPIREXLS-5125 Fixes the issue that the styles were incorrect when converting Excel to PDF.
Bug SPIREXLS-5126 Fixes the issue that the program threw "ArgumentNullException" exception when loading files.
Bug SPIREXLS-5148 Fixed the issue that the program threw "NullReferenceException" exception when splitting a document.
Click the link below to download Spire.XLS 14.3.3:
More information of Spire.XLS new release or hotfix:
Monday, 18 March 2024 01:40

Python: Reorder PDF Pages

Typically, the content of a PDF document needs to follow a logical flow, such as a report is usually structured with chapters, sections, and subsections. When the pages within a PDF are not arranged in the correct sequence, the coherence of the document will be affected. By reordering the pages, you can ensure that the information is presented in a clear and understandable manner. In this article, you will learn how to reorder the pages in a PDF file with 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 VS Code 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 in VS Code

Reorder PDF Pages with Python

Spire.PDF for Python provides the PdfDocument.Pages.ReArrange(orderArray: List[int]) method to rearrange the pages in a PDF file. The parameter orderArray is a list of integers which allows you to reorder the PDF pages by specifying the page index in the desired order.

The following are the detailed steps to rearrange the PDF page order with Python:

  • Create a PdfDocument instance.
  • Load a sample PDF file using PdfDocument.LoadFromFile() method.
  • Rearrange the page order of the PDF file using PdfDocument.Pages.ReArrange(orderArray: List[int]) method.
  • Save the result file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

inputFile = "Report.pdf"
outputFile = "RearrangePDFPageOrder.pdf"

# Create a PdfDocument instance 
pdf = PdfDocument()

# Load a PDF file
pdf.LoadFromFile(inputFile)

# Reorder pages in the PDF file
pdf.Pages.ReArrange([3, 2, 0, 1])

# Save the result file
pdf.SaveToFile(outputFile, FileFormat.PDF)
pdf.Close()

Python: Reorder PDF 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.

Page 2 of 220