Excel document properties, also known as metadata, are essential for understanding the content and context of an Excel file. They provide valuable information about the document's content, authorship, and creation/revision history, which can facilitate the efficient organization and retrieval of files. In addition to adding document properties to Excel, this article will show you how to read or remove document properties from Excel in C# using Spire.XLS for .NET.

Install Spire.XLS for .NET

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

Read Standard and Custom Document Properties from Excel in C#

Excel properties are divided into two main categories:

  • Standard Properties: These are predefined properties that are built into Excel files. They typically include basic details about the file such as title, subject, author, keywords, etc.
  • Custom Properties: These are user-defined attributes that can be added to Excel to track additional information about the file based on your specific needs.

Spire.XLS for .NET allows to read both the standard and custom document properties of an Excel file. The following are the detailed steps:

  • Create a Workbook instance.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Create a StringBuilder instance.
  • Get a collection of all standard document properties using Workbook.DocumentProperties property.
  • Get specific standard document properties using the properties of the BuiltInDocumentProperties class and append them to the StringBuilder instance.
  • Get a collection of all custom document properties using Workbook.CustomDocumentProperties property.
  • Iterate through the collection.
  • Get the name and value of each custom document property using IDocumentProperty.Name and IDocumentProperty.Value properties and append them to the StringBuilder instance.
  • Write the content of the StringBuilder instance into a txt file.
  • C#
using Spire.Xls;
using Spire.Xls.Collections;
using Spire.Xls.Core;
using System.IO;
using System.Text;

namespace GetExcelProperties
{
    class Program
    {

        static void Main(string[] args)
        {
            {
                //Create a Workbook instance
                Workbook workbook = new Workbook();

                //Load a sample Excel file
                workbook.LoadFromFile("Budget Template.xlsx");

                //Create a StringBuilder instance
                StringBuilder sb = new StringBuilder();

                //Get a collection of all standard document properties
                BuiltInDocumentProperties standardProperties = workbook.DocumentProperties;

                //Get specific standard properties and append them to the StringBuilder instance
                sb.AppendLine("Standard Document Properties:");
                sb.AppendLine("Title: " + standardProperties.Title);
                sb.AppendLine("Subject: " + standardProperties.Subject);
                sb.AppendLine("Category: " + standardProperties.Category);
                sb.AppendLine("Keywords: " + standardProperties.Keywords);
                sb.AppendLine("Comments: " + standardProperties.Comments);
                sb.AppendLine();

                //Get a collection of all custom document properties
                ICustomDocumentProperties customProperties = workbook.CustomDocumentProperties;

                sb.AppendLine("Custom Document Properties:");
                //Iterate through the collection
                for (int i = 0; i < customProperties.Count; i++)
                {
                    //Get the name and value of each custom document property and append them to the StringBuilder instance
                    string name = customProperties[i].Name;
                    string value = customProperties[i].Value.ToString();
                    sb.AppendLine(name + ": " + value);
                }

                //Write the content of the StringBuilder instance into a text file
                File.WriteAllText("GetExcelProperties.txt", sb.ToString());            
            }
        }
    }
}

C#: Read or Remove Document Properties from Excel

Remove Standard and Custom Document Properties from Excel in C#

You can easily delete standard document properties from an Excel file by setting their values as empty. For custom document properties, you can use the ICustomDocumentProperties.Remove() method to delete them. The following are the detailed steps:

  • Create a Workbook instance.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a collection of all standard document properties using Workbook.DocumentProperties property.
  • Set the values of specific standard document properties as empty through the corresponding properties of the BuiltInDocumentProperties class.
  • Get a collection of all custom document properties using Workbook.CustomDocumentProperties property.
  • Iterate through the collection.
  • Delete each custom property from the collection by its name using ICustomDocumentProperties.Remove(string strName) method.
  • Save the result file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Collections;
using Spire.Xls.Core;

namespace DeleteExcelProperties
{
    class Program
    {

        static void Main(string[] args)
        {
            {
                //Create a Workbook instance
                Workbook workbook = new Workbook();

                //Load a sample Excel file
                workbook.LoadFromFile("Budget Template.xlsx");

                //Get a collection of all standard document properties
                BuiltInDocumentProperties standardProperties = workbook.DocumentProperties;

                //Set the value of each standard document property as empty
                standardProperties.Title = "";
                standardProperties.Subject = "";
                standardProperties.Category = "";
                standardProperties.Keywords = "";
                standardProperties.Comments = "";
 
                //Get a collection of all custom document properties
                ICustomDocumentProperties customProperties = workbook.CustomDocumentProperties;

                //Iterate through the collection
                for (int i = customProperties.Count -1; i >=0; i--)
                {
                    //Delete each custom document property from the collection by its name
                    customProperties.Remove(customProperties[i].Name);

                }

                //Save the result file
                workbook.SaveToFile("DeleteDocumentProperties.xlsx", ExcelVersion.Version2016);            
            }
        }
    }
}

C#: Read or Remove Document Properties from 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.

Spire.XLS provides a class named Workbook that represents an Excel workbook. This class contains a method named IsPasswordProtected(string fileName) which returns a boolean value. If the value is true, means the workbook is encrypted with password, otherwise it's not.

This is an Excel workbook protected with password:

Detect if an Excel Workbook is Password Protected in C#, VB.NET

Now refer below code to detect if the Excel workbook is password protected:

[C#]
using System;
using Spire.Xls;

namespace Detect_if_workbook_is_password_protected
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = "E:\\Program Files\\Sample.xlsx";
            //Detect if the Excel workbook is password protected.
            bool value = Workbook.IsPasswordProtected(fileName);
            Console.WriteLine(value);
            Console.ReadKey();
        }
    }
}
[VB.NET]
Imports Spire.Xls

Namespace Detect_if_workbook_is_password_protected
	Class Program
		Private Shared Sub Main(args As String())
			Dim fileName As String = "E:\Program Files\Sample.xlsx"
			'Detect if the Excel workbook is password protected.
			Dim value As Boolean = Workbook.IsPasswordProtected(fileName)
			Console.WriteLine(value)
			Console.ReadKey()
		End Sub
	End Class
End Namespace

After running the project, we get the Output that shows the workbook is password protected:

Detect if an Excel Workbook is Password Protected in C#, VB.NET

There can be many types of titles such as centered title, subtitle and title on PowerPoint slides. This article demonstrates how to get such titles from all the slides of a PowerPoint document by using Spire.Presentation and C#.

This is a PowerPoint document which contains a centered title and a subtitle on the first slide and a title on the second slide.

How to Get the Titles of All Slides with C#

Follow below steps to get the titles:

Step 1: Instantiate a Presentation object and load the PowerPoint document.

Presentation ppt = new Presentation();
ppt.LoadFromFile("test.pptx");

Step 2: Instantiate a list of IShape objects.

List<IShape> shapelist = new List<IShape>();

Step 3: Loop through all sildes in the document and all shapes on each slide, add the shape which placeholder type is title or centered title or subtitle to the list.

foreach (ISlide slide in ppt.Slides)
{
    foreach (IShape shape in slide.Shapes)
    {
        if (shape.Placeholder != null)
        {
            switch (shape.Placeholder.Type)
            {
                case PlaceholderType.Title:
                    shapelist.Add(shape);
                    break;
                case PlaceholderType.CenteredTitle:
                    shapelist.Add(shape);
                    break;
                case PlaceholderType.Subtitle:
                    shapelist.Add(shape);
                    break;
            }
        }
    }
}

Step 4: Loop through the list and print out the inner text of all shapes in the list.

for (int i = 0; i < shapelist.Count; i++)
{
    IAutoShape shape1 = shapelist[i] as IAutoShape;
    Console.WriteLine(shape1.TextFrame.Text);
}

Output:

How to Get the Titles of All Slides with C#

Full code:

using System;
using System.Collections.Generic;
using Spire.Presentation;

namespace Get_the_Titles_of_All_Slides
{
    class Program
    {
        static void Main(string[] args)
        {
            Presentation ppt = new Presentation();
            ppt.LoadFromFile("test.pptx");
            List<IShape> shapelist = new List<IShape>();
            foreach (ISlide slide in ppt.Slides)
            {
                foreach (IShape shape in slide.Shapes)
                {
                    if (shape.Placeholder != null)
                    {
                        switch (shape.Placeholder.Type)
                        {
                            case PlaceholderType.Title:
                                shapelist.Add(shape);
                                break;
                            case PlaceholderType.CenteredTitle:
                                shapelist.Add(shape);
                                break;
                            case PlaceholderType.Subtitle:
                                shapelist.Add(shape);
                                break;
                        }
                    }
                }
            }
            for (int i = 0; i < shapelist.Count; i++)
            {
                IAutoShape shape1 = shapelist[i] as IAutoShape;
                Console.WriteLine(shape1.TextFrame.Text);
            }
            Console.ReadKey();
        }
    }
}

Every time when we change the slide's size, we need to reset the size and position for the shape to ensure the shape on the slide shows orderly. This tutorial will focus on demonstrating how to reset the size and position for the shape in C#.

Firstly, please view the original shape:

Reset the size and position for the shape on presentation slides in C#

Code snippet of how to set the size and position of the shape:

Step 1: Create a new presentation document and load the document from file.

Presentation presentation = new Presentation();
presentation.LoadFromFile("Sample.pptx");

Step 2: Define the original slide size.

float currentHeight = presentation.SlideSize.Size.Height;
float currentWidth = presentation.SlideSize.Size.Width;

Step 3: Change the slide size as A3.

presentation.SlideSize.Type = SlideSizeType.A3;

Step 4: Define the new slide size.

float newHeight = presentation.SlideSize.Size.Height;
float newWidth = presentation.SlideSize.Size.Width;

Step 5: Define the ratio from the old and new slide size.

float ratioHeight = newHeight / currentHeight;
float ratioWidth = newWidth / currentWidth;

Step 6: Reset the size and position of the shape on the slide.

foreach (ISlide slide in presentation.Slides)
{
    foreach (IShape shape in slide.Shapes)
    {
        //Reset the shape size
        shape.Height = shape.Height * ratioHeight;
        shape.Width = shape.Width * ratioWidth;

        //Reset the shape position
        shape.Left = shape.Left * ratioHeight;
        shape.Top = shape.Top * ratioWidth;

    }

Step 7: Save the document to file.

presentation.SaveToFile("resize.pptx", FileFormat.Pptx2010);

Effective screenshot after reset the size and position of the shape on the slide:

Reset the size and position for the shape on presentation slides in C#

Full codes:

using Spire.Presentation;

namespace ResetSizeandPosition
{

    class Program
    {

        static void Main(string[] args)
        {
            {
                Presentation presentation = new Presentation();
                presentation.LoadFromFile("Sample.pptx");

                float currentHeight = presentation.SlideSize.Size.Height;
                float currentWidth = presentation.SlideSize.Size.Width;

                presentation.SlideSize.Type = SlideSizeType.A3;

                float newHeight = presentation.SlideSize.Size.Height;
                float newWidth = presentation.SlideSize.Size.Width;

                float ratioHeight = newHeight / currentHeight;
                float ratioWidth = newWidth / currentWidth;

                foreach (ISlide slide in presentation.Slides)
                {
                    foreach (IShape shape in slide.Shapes)
                    {
                        shape.Height = shape.Height * ratioHeight;
                        shape.Width = shape.Width * ratioWidth;

                        shape.Left = shape.Left * ratioHeight;
                        shape.Top = shape.Top * ratioWidth;
                    }

                    presentation.SaveToFile("resize.pptx", FileFormat.Pptx2010);
                }
            }

        }
    }
}

The GoToE (or embedded go-to) action is similar to a remote go-to action but allows jumping to a PDF file that is embedded in another PDF file. With Spire.PDF, it’s possible to create a GoToE action to direct from the current PDF file to the embedded PDF file. This article demonstrates how to accomplish this goal programmatically with C#.

At first, it's necessary to introduce you the parameters of public PdfEmbeddedGoToAction(string fileName, PdfDestination dest, bool newWindow);

Parameters:

  • fileName - the name of the target file.
  • dest - the destination inside the target file.
  • newWindow - if true open the file in a new window, if false the current file is replaced by the new file.

Now Follow below Detail steps:

Step 1: Create a PDF file and add a page to it.

PdfDocument pdf = new PdfDocument();
PdfPageBase page = pdf.Pages.Add();

Step 2: Attach a PDF file to the newly created file.

PdfAttachment attachment = new PdfAttachment("New Zealand.pdf");
pdf.Attachments.Add(attachment);

Step 3: Draw text on the page.

string text = "Test embedded go-to action! Click this will open the attached PDF in a new window.";
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 13f));
float width = 490f;
float height = font.Height * 2.2f;
RectangleF rect = new RectangleF(0, 100, width, height);
page.Canvas.DrawString(text, font, PdfBrushes.Black, rect);

Step 4: Create an embedded go-to action (/GoToE) which allows jumping to the attached PDF file and open it in a new window at the 2nd page and 200% zoom factor.

PdfDestination dest = new PdfDestination(1, new PointF(0, 842), 2f);
PdfEmbeddedGoToAction action = new PdfEmbeddedGoToAction(attachment.FileName, dest, true);

Step 5: Create an action annotation with the embedded go-to action and then add it to the page.

PdfActionAnnotation annotation = new PdfActionAnnotation(rect, action);
(page as PdfNewPage).Annotations.Add(annotation);

Step 6: Save the document.

pdf.SaveToFile("result.pdf");

Effective Screenshot:

Create a GoToE Action to an Embedded PDF File

Full code:

using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.Attachments;
using Spire.Pdf.General;
using Spire.Pdf.Graphics;

namespace Create_A_GoToE_Action
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument pdf = new PdfDocument();
            PdfPageBase page = pdf.Pages.Add();
            PdfAttachment attachment = new PdfAttachment("New Zealand.pdf");
            pdf.Attachments.Add(attachment);
            string text = "Test embedded go-to action! Click this will open the attached PDF in a new window.";
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 13f));
            float width = 490f;
            float height = font.Height * 2.2f;
            RectangleF rect = new RectangleF(0, 100, width, height);
            page.Canvas.DrawString(text, font, PdfBrushes.Black, rect);
            PdfDestination dest = new PdfDestination(1, new PointF(0, 842), 2f);
            PdfEmbeddedGoToAction action = new PdfEmbeddedGoToAction(attachment.FileName, dest, true);
            PdfActionAnnotation annotation = new PdfActionAnnotation(rect, action);
            (page as PdfNewPage).Annotations.Add(annotation);
            pdf.SaveToFile("result.pdf");            
        }
    }		 
}

How to update Ask Field in C#

2016-12-28 08:08:25 Written by Koohji

With Spire.Doc for .NET, developers can easily operate the word fields from code. We have already shown how to create an IF field and remove Custom Property Fields in C#. From Spire.Doc V5.8.33, our developers add a new event UpdateFields to handle the Ask Field. This article will focus on demonstrating how to update the ASK field on the word document in C#.

Firstly, please view the sample document with an Ask filed which will be updated later:

How to update Ask Field in C#

Step 1: Create a new instance of Spire.Doc.Document class and load the document from file.

Document doc = new Document();
doc.LoadFromFile("Sample.docx");

Step 2: Call UpdateFieldsHandler event to update the ASK field.

doc.UpdateFields += new UpdateFieldsHandler(doc_UpdateFields);

Step 3: Update the fields in the document.

doc.IsUpdateFields = true;

Step 4: Save the document to file.

doc.SaveToFile("output.docx", FileFormat.Docx);

The following doc_UpdateFields () method shows how to update the ask field:

private static void doc_UpdateFields(object sender, IFieldsEventArgs args)
 {
     if (args is AskFieldEventArgs)
     {
         AskFieldEventArgs askArgs = args as AskFieldEventArgs;

         askArgs.ResponseText = "Female";
     }
 }

Effective screenshot after updating the Ask Field in C#:

How to update Ask Field in C#

Full codes:

using Spire.Doc;
using Spire.Doc.Fields;
namespace Askfield
{
    class Program
    {
        public void Field()
        {

            Document doc = new Document();
            doc.LoadFromFile("Sample.docx");

            doc.UpdateFields += new UpdateFieldsHandler(doc_UpdateFields);

            doc.IsUpdateFields = true;

            doc.SaveToFile("output.docx", FileFormat.Docx);

        }
        private static void doc_UpdateFields(object sender, IFieldsEventArgs args)
        {
            if (args is AskFieldEventArgs)
            {
                AskFieldEventArgs askArgs = args as AskFieldEventArgs;

                askArgs.ResponseText = "Female";
            }
        }


    }
}

Adding rows and columns are common tasks in Word table processing, on the contrary, sometimes we also have the requirement of deleting rows or columns from a table. This article demonstrates how to delete a row and a column from an existing Word table using Spire.Doc.

Below is the screenshot of the original table. Afterwards, we will remove the colored row and column from the table.

How to Delete Rows and Columns from a Word Table in C#, VB.NET

Detail steps:

Step 1: Instantiate a Document object and load the Word document.

Document doc = new Document();
doc.LoadFromFile("Sample.docx");

Step 2: Get the table from the document.

Table table = doc.Sections[0].Tables[0] as Table;   

Step 3: Delete the third row from the table.

table.Rows.RemoveAt(2);

Step 4: Delete the third column from the table.

for (int i = 0; i < table.Rows.Count; i++)
{
    table.Rows[i].Cells.RemoveAt(2);
}

Step 5: Save the document.

doc.SaveToFile("result.docx", FileFormat.Docx2013);

Output:

How to Delete Rows and Columns from a Word Table in C#, VB.NET

Full code:

[C#]
using Spire.Doc;

namespace Delete_Rows_and_Columns
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("Sample.docx");
            Table table = doc.Sections[0].Tables[0] as Table;           
            table.Rows.RemoveAt(2);
            for (int i = 0; i < table.Rows.Count; i++)
            {
                table.Rows[i].Cells.RemoveAt(2);
            }
            doc.SaveToFile("result.docx", FileFormat.Docx2013);
        }
    }
}
[VB.NET]
Imports Spire.Doc

Namespace Delete_Rows_and_Columns
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New Document()
			doc.LoadFromFile("Sample.docx")
			Dim table As Table = TryCast(doc.Sections(0).Tables(0), Table)
			table.Rows.RemoveAt(2)
			For i As Integer = 0 To table.Rows.Count - 1
				table.Rows(i).Cells.RemoveAt(2)
			Next
		        doc.SaveToFile("result.docx", FileFormat.Docx2013);
		End Sub
	End Class
End Namespace

With the help of Spire.XLS, we could easily add header and footer to the excel page; we can also set different Header and Footer for Odd and Even Pages in Excel. This article will demonstrate how to add different header & footer for the first page on the excel worksheet.

Here comes to the code snippets of how to set different header and footer for the first page:

Step 1: Initialize an instance of Workbook and get the first worksheet.

Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];

Step 2: Set the value of DifferentFirst as 1, which indicates that headers/footers for first page are different from the other pages.

Step 3: Set the header and footer for the first page.

sheet.PageSetup.FirstHeaderString = "Different First page";
sheet.PageSetup.FirstFooterString = "Different First footer";

Step 4: Set the other pages' header and footer. If we don't need to set the header and footer for other pages, we can ignore this step.

sheet.PageSetup.LeftHeader = "Demo of Spire.XLS";
sheet.PageSetup.CenterFooter = "Footer by Spire.XLS";

Step 5: Save the document to file.

workbook.SaveToFile("Result.xlsx", FileFormat.Version2010); 

Effective screenshot:

How to add different header & footer for the first page

Full codes:

using Spire.Xls;
namespace SetDifferentHeaderorFooter 
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            Worksheet sheet = workbook.Worksheets[0];

            sheet.PageSetup.DifferentFirst = 1;

            sheet.PageSetup.FirstHeaderString = "Different First page";
            sheet.PageSetup.FirstFooterString = "Different First footer";

            sheet.PageSetup.LeftHeader = "Demo of Spire.XLS";
            sheet.PageSetup.CenterFooter = "Footer by Spire.XLS";

            workbook.SaveToFile("result.xlsx", FileFormat.Version2010);      
        }
    }
}

A donut chart is a variant of the pie chart, with a blank center allowing for additional information about the data as a whole to be included. In this article, you will learn how to create a doughnut chart using Spire.XLS in C#.

Step 1: Initialize a new instance of Workbook class and set the Excel version as 2013.

Workbook wb = new Workbook();
wb.Version = ExcelVersion.Version2013;

Step 2: Get the first sheet from workbook.

Worksheet sheet = wb.Worksheets[0];

Step 3: Insert some data in the sheet.

sheet.Range["A1"].Value = "Country";
sheet.Range["A1"].Style.Font.IsBold = true;
sheet.Range["A2"].Value = "Cuba";
sheet.Range["A3"].Value = "Mexico";
sheet.Range["A4"].Value = "France";
sheet.Range["A5"].Value = "German";
sheet.Range["B1"].Value = "Sales";
sheet.Range["B1"].Style.Font.IsBold = true;
sheet.Range["B2"].NumberValue = 6000;
sheet.Range["B3"].NumberValue = 8000;
sheet.Range["B4"].NumberValue = 9000;
sheet.Range["B5"].NumberValue = 8500;

Step 4: Create a Doughnut Chart based on the data from range A1:B5.

Chart chart = sheet.Charts.Add();
chart.ChartType = ExcelChartType.Doughnut;
chart.DataRange = sheet.Range["A1:B5"];
chart.SeriesDataFromRange = false;

Step 5: Set the chart position.

chart.LeftColumn = 4;
chart.TopRow = 2;
chart.RightColumn = 12;
chart.BottomRow = 22;

Step 6: Display percentage value in data labels.

foreach (ChartSerie cs in chart.Series)
{
    cs.DataPoints.DefaultDataPoint.DataLabels.HasPercentage = true;
}

Step 7: Save the file.

wb.SaveToFile("DoughnutChart.xlsx",ExcelVersion.Version2010);

Output:

How to Create a Doughnut Chart in Excel in C#

Full Code:

using Spire.Xls;
using Spire.Xls.Charts;

namespace DoughnutChart
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook wb = new Workbook();
            wb.Version = ExcelVersion.Version2013;
            Worksheet sheet = wb.Worksheets[0];

            //insert data
            sheet.Range["A1"].Value = "Country";
            sheet.Range["A1"].Style.Font.IsBold = true;
            sheet.Range["A2"].Value = "Cuba";
            sheet.Range["A3"].Value = "Mexico";
            sheet.Range["A4"].Value = "France";
            sheet.Range["A5"].Value = "German";
            sheet.Range["B1"].Value = "Sales";
            sheet.Range["B1"].Style.Font.IsBold = true;
            sheet.Range["B2"].NumberValue = 6000;
            sheet.Range["B3"].NumberValue = 8000;
            sheet.Range["B4"].NumberValue = 9000;
            sheet.Range["B5"].NumberValue = 8500;

            //add a new chart, set chart type as doughnut
            Chart chart = sheet.Charts.Add();
            chart.ChartType = ExcelChartType.Doughnut;
            chart.DataRange = sheet.Range["A1:B5"];
            chart.SeriesDataFromRange = false;

            //set position of chart
            chart.LeftColumn = 4;
            chart.TopRow = 2;
            chart.RightColumn = 12;
            chart.BottomRow = 22;
           
            //chart title
            chart.ChartTitle = "Market share by country";
            chart.ChartTitleArea.IsBold = true;
            chart.ChartTitleArea.Size = 12;

            foreach (ChartSerie cs in chart.Series)
            {
                cs.DataPoints.DefaultDataPoint.DataLabels.HasPercentage = true;
            }

            chart.Legend.Position = LegendPositionType.Top;
            wb.SaveToFile("DoughnutChart.xlsx",ExcelVersion.Version2010);
        }
    }
}

In previous topics, we demonstrated how to create, format, protect and copy chart in PowerPoint. In this article, we'll show you how to remove chart from a specific slide by using Spire.Presentation.

Below is a sample document which contains a chart and a textbox on the first slide, then we'll remove the chart from the slide.

How to Remove Chart from a PowerPoint Slide in C#, VB.NET

Code Snippets:

Step 1: Instantiate a Presentation object and load the PowerPoint document.

Presentation ppt = new Presentation();
ppt.LoadFromFile("Sample.pptx");

Step 2: Get the first slide from the document.

ISlide slide = ppt.Slides[0];

Step 3: Remove chart from the slide.

for(int i = 0; i < slide.Shapes.Count; i++)
{
    IShape shape = slide.Shapes[i] as IShape;
    if(shape is IChart)
    {
        slide.Shapes.Remove(shape);
    }
}

Step 4: Save the document.

ppt.SaveToFile("result.pptx", FileFormat.Pptx2010);

Effective screenshot:

How to Remove Chart from a PowerPoint Slide in C#, VB.NET

Full code:

[C#]
using Spire.Presentation;
using Spire.Presentation.Charts;

namespace Remove_Chart_in_PowerPoint
{
    class Program
    {
        static void Main(string[] args)
        {
            Presentation ppt = new Presentation();
            ppt.LoadFromFile("Sample.pptx");
            ISlide slide = ppt.Slides[0];
            for(int i = 0; i < slide.Shapes.Count; i++)
            {
                IShape shape = slide.Shapes[i] as IShape;
                if(shape is IChart)
                {
                    slide.Shapes.Remove(shape);
                }
            }
            ppt.SaveToFile("result.pptx", FileFormat.Pptx2010);
        }
    }
}
[VB.NET]
Imports Spire.Presentation
Imports Spire.Presentation.Charts

Namespace Remove_Chart_in_PowerPoint
	Class Program
		Private Shared Sub Main(args As String())
			Dim ppt As New Presentation()
			ppt.LoadFromFile("Sample.pptx")
			Dim slide As ISlide = ppt.Slides(0)
			For i As Integer = 0 To slide.Shapes.Count - 1
				Dim shape As IShape = TryCast(slide.Shapes(i), IShape)
				If TypeOf shape Is IChart Then
					slide.Shapes.Remove(shape)
				End If
			Next
			ppt.SaveToFile("result.pptx", FileFormat.Pptx2010)
		End Sub
	End Class
End Namespace
page 32