Filters in pivot tables enable users to narrow down the displayed data based on specific criteria. By adding filters, users can focus on subsets of data that are most relevant to their analysis, allowing for a more targeted and efficient data exploration. In this article, we will demonstrate how to add filters to pivot tables in 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

Add Report Filter to Pivot Table in Excel in C#

Spire.XLS for .NET offers the XlsPivotTable.ReportFilters.Add() method to add report filters to a pivot table. 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 in the file using Workbook.Worksheets[index] property.
  • Get a specific pivot table in the worksheet using Worksheet.PivotTables[index] property.
  • Create a report filter using PovotReportFilter class.
  • Add the report filter to the pivot table using XlsPivotTable.ReportFilters.Add() method.
  • Save the resulting file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Core.Spreadsheet.PivotTables;

namespace AddReportFilter
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an object of the Workbook class
            Workbook workbook = new Workbook();
            // Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

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

            // Get the first pivot table
            XlsPivotTable pt = sheet.PivotTables[0] as XlsPivotTable;

            // Create a report filter
            PivotReportFilter reportFilter = new PivotReportFilter("Product", true);

            // Add the report filter to the pivot table
            pt.ReportFilters.Add(reportFilter);

            // Save the resulting file
            workbook.SaveToFile("AddReportFilter.xlsx", FileFormat.Version2016);
            workbook.Dispose();
        }
    }
}

C#: Add Filters to Pivot Tables in Excel

Add Filter to a Row Field of Pivot Table in Excel in C#

You can add a value filter or label filter to a specific row field in a pivot table using the XlsPivotTable.RowFields[index].AddValueFilter() or XlsPivotTable.RowFields[index].AddLabelFilter() 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 worksheet in the file using Workbook.Worksheets[index] property.
  • Get a specific pivot table in the worksheet using Worksheet.PivotTables[index] property.
  • Add a value filter or label filter to a specific row field in the pivot table using XlsPivotTable.RowFields[index].AddValueFilter() or XlsPivotTable.RowFields[index].AddLabelFilter() method.
  • Calculate the data in the pivot table using XlsPivotTable.CalculateData() method.
  • Save the resulting file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Core.Spreadsheet.PivotTables;

namespace AddRowFilter
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an object of the Workbook class
            Workbook workbook = new Workbook();
            // Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

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

            // Get the first pivot table
            XlsPivotTable pt = sheet.PivotTables[0] as XlsPivotTable;


            // Add a value filter to the first row field in the pivot table
            pt.RowFields[0].AddValueFilter(PivotValueFilterType.GreaterThan, pt.DataFields[0], 5000, null);
            // Or add a label filter to the first row field in the pivot table
            //pt.RowFields[0].AddLabelFilter(PivotLabelFilterType.Equal, "Mike", null);

            // Calculate the pivot table data
            pt.CalculateData();

            // Save the resulting file
            workbook.SaveToFile("AddRowFilter.xlsx", FileFormat.Version2016);
            workbook.Dispose();
        }
    }
}

C#: Add Filters to Pivot Tables in Excel

Add Filter to a Column Field of Pivot Table in Excel in C#

To add a value filter or label filter to a specific column field in a pivot table, you can use the XlsPivotTable.ColumnFields[index].AddValueFilter() or XlsPivotTable.ColumnFields[index].AddLabelFilter() 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 worksheet in the file using Workbook.Worksheets[index] property.
  • Get a specific pivot table in the worksheet using Worksheet.PivotTables[index] property.
  • Add a value filter or label filter to a specific column field in the pivot table using XlsPivotTable.ColumnFields[index].AddValueFilter() or XlsPivotTable.ColumnFields[index].AddLabelFilter() method.
  • Calculate the data in the pivot table using XlsPivotTable.CalculateData() method.
  • Save the resulting file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Core.Spreadsheet.PivotTables;

namespace AddColumnFilter
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an object of the Workbook class
            Workbook workbook = new Workbook();
            // Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

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

            // Get the first pivot table
            XlsPivotTable pt = sheet.PivotTables[0] as XlsPivotTable;

            // Add a label filter to the first column field in the pivot table
            pt.ColumnFields[0].AddLabelFilter(PivotLabelFilterType.Equal, "Laptop", null);
            // Or add a value filter to the first column field in the pivot table
            // pt.ColumnFields[0].AddValueFilter(PivotValueFilterType.Between, pt.DataFields[0], 5000, 10000);


            // Calculate the pivot table data
            pt.CalculateData();

            // Save the resulting file
            workbook.SaveToFile("AddColumnFilter.xlsx", FileFormat.Version2016);
            workbook.Dispose();
        }
    }
}

C#: Add Filters to Pivot Tables 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.

Importing and exporting PDF form data allows users to seamlessly exchange form information with external files in formats such as FDF (Forms Data Format), XFDF (XML Forms Data Format), or XML. The import function enables quick population of PDF forms using data from external sources, while the export function extracts data from PDF forms and saves it to external files. This capability simplifies data management, making it especially valuable for processing large volumes of form data or integrating with other systems. In this article, we will demonstrate how to import PDF form data from FDF, XFDF, or XML files, or export PDF form data to FDF, XFDF, or XML files in C# using Spire.PDF for .NET.

Install Spire.PDF for .NET

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

PM> Install-Package Spire.PDF

Import PDF Form Data from FDF, XFDF or XML Files in C#

Spire.PDF for .NET offers the PdfFormWidget.ImportData() method for importing PDF form data from FDF, XFDF, or XML files. The detailed steps are as follows.

  • Create an object of the PdfDocument class.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Get the form of the PDF document using PdfDocument.Form property.
  • Import form data from an FDF, XFDF or XML file using PdfFormWidget.ImportData() method.
  • Save the resulting document using PdfDocument.SaveToFile() method.
  • C#
using Spire.Pdf;
using Spire.Pdf.Widget;

namespace ImportPdfFormData
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create an object of the PdfDocument class
            PdfDocument document = new PdfDocument();
            //Load a PDF document
            document.LoadFromFile("Forms.pdf");

            //Get the form of the PDF document 
            PdfFormWidget loadedForm = document.Form as PdfFormWidget;
             
            //Import PDF form data from an XML file
            loadedForm.ImportData("Data.xml", DataFormat.Xml);

            //Import PDF form data from an FDF file
            //loadedForm.ImportData("Data.fdf", DataFormat.Fdf);

            //Import PDF form data from an XFDF file
            //loadedForm.ImportData("Data.xfdf", DataFormat.XFdf);

            //Save the resulting document
            document.SaveToFile("Output.pdf");
            //Close the PdfDocument object
            document.Close();
        }
    }
}

C#: Import and Export PDF Form Data

Export PDF Form Data to FDF, XFDF or XML Files in C#

Spire.PDF for .NET also enables you to export PDF form data to FDF, XFDF, or XML files by using the PdfFormWidget.ExportData() method. The detailed steps are as follows.

  • Create an object of the PdfDocument class.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Get the form of the PDF document using PdfDocument.Form property.
  • Export form data to an FDF, XFDF or XML file using PdfFormWidget.ExportData() method.
  • C#
using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Widget;

namespace ExportPdfFormData
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create an object of the PdfDocument class
            PdfDocument document = new PdfDocument();
            //Load a PDF document
            document.LoadFromFile("Forms.pdf");

            //Get the form of the PDF document 
            PdfFormWidget loadedForm = document.Form as PdfFormWidget;

            //Export PDF form data to an XML file
            loadedForm.ExportData("Data.xml", DataFormat.Xml, "Form");

            //Export PDF form data to an FDF file
            //loadedForm.ExportData("Data.fdf", DataFormat.Fdf, "Form");

            //Export PDF form data to an XFDF file
            //loadedForm.ExportData("Data.xfdf", DataFormat.XFdf, "Form");

            //Close the PdfDocument object
            document.Close();
        }
    }
}

C#: Import and Export PDF Form Data

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.

C#: Copy Pages in PDF

2024-10-10 01:03:29 Written by support iceblue

Copying PDF pages facilitates better organization of information. By copying pages that contain important sections and then compiling them into a new document, you can bring together relevant content from different sources to create a cohesive resource that is easy to navigate. In this article, you will learn how to copy pages in PDF in C# using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF 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.PDF

Copy Pages within the Same PDF in C#

To duplicate PDF pages, you can first create template based on a specified page in PDF, and then draw the template on a newly added page through the PdfPageBase.Canvas.DrawTemplate() method. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Get a specified page using PdfDocument.Pages[] property.
  • Get the size of the page using PdfPageBase.Size property.
  • Create a template based on the page using PdfPageBase.CreateTemplate() method.
  • Add a new page of the same size at the end using PdfDocument.Pages.Add(SizeF size, PdfMargins margins) method. Or you can insert a new page of the same size at a specified location using PdfDocument.Pages.Insert(int index, SizeF size, PdfMargins margins) method.
  • Draw template on the newly added page using PdfPageBase.Canvas.DrawTemplate(PdfTemplate template, PointF location) method.
  • Save the result file using PdfDocument.SaveToFile() method.
  • C#
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace DuplicatePage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();

            //Load a PDF file
            pdf.LoadFromFile("Butterflies.pdf");

            //Get the first page
            PdfPageBase page = pdf.Pages[0];

            //Get the size of the page
            SizeF size = page.Size;

            //Create a template based on the page
            PdfTemplate template = page.CreateTemplate();

            //Add a new page the same size as the first page
            page = pdf.Pages.Add(size, new PdfMargins(0));
            //Insert a new page at the specified location
            //page = pdf.Pages.Insert(1, size, new PdfMargins(0));

            //Draw the template on the newly added page
            page.Canvas.DrawTemplate(template, new PointF(0, 0));

            //Save the PDF file
            pdf.SaveToFile("CopyPDFPages.pdf");
        }
    }
}

C#: Copy Pages in PDF

Copy Pages from One PDF to Another in C#

Spire.PDF for .NET also allows you to load two PDF files, create templates based on the pages in one PDF file, and then draw them onto the pages in another PDF file. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load two PDF files using PdfDocument.LoadFromFile() method.
  • Get a specified page in the first PDF using PdfDocument.Pages[] property.
  • Get the size of the page using PdfPageBase.Size property.
  • Create a template based on the page using PdfPageBase.CreateTemplate() method.
  • Insert a new page of the same size at a specified location in the second PDF using PdfDocument.Pages.Insert(int index, SizeF size, PdfMargins margins) method. Or you can add a new page of the same size at the end of the second PDF using PdfDocument.Pages.Add(SizeF size, PdfMargins margins) method.
  • Draw template on the newly added page using PdfPageBase.Canvas.DrawTemplate(PdfTemplate template, PointF location) method.
  • Save the result file using PdfDocument.SaveToFile() method.
  • C#
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace CopyPageToAnother
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the first PDF file
            PdfDocument pdf1 = new PdfDocument();
            pdf1.LoadFromFile("Butterflies.pdf");

            //Load the second PDF file
            PdfDocument pdf2 = new PdfDocument();
            pdf2.LoadFromFile("SamplePDF.pdf");

            //Get the first page in the first PDF file
            PdfPageBase page = pdf1.Pages[0];

            //Get the size of the page
            SizeF size = page.Size;

            //Create a template based on the page
            PdfTemplate template = page.CreateTemplate();

            //Insert a new page at a specified location in the second PDF file
            PdfPageBase newPage = pdf2.Pages.Insert(0, size, new PdfMargins(0));

            //Add a new page at the end of the second PDF file
            //PdfPageBase newPage = pdf2.Pages.Add(size, new PdfMargins(0));

            //Draw the template on the newly added page
            newPage.Canvas.DrawTemplate(template, new PointF(0, 0));

            //Save the result file
            pdf2.SaveToFile("CopyPagesToAnotherPDF.pdf");
        }
    }
}

C#: Copy Pages 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.

C#: Convert PDF to Markdown

2024-09-30 01:13:45 Written by support iceblue

The need to convert PDF documents into more flexible and editable formats, such as Markdown, has become a common task for developers and content creators. Converting PDFs to Markdown files facilitates easier editing and version control, and enhances content portability across different platforms and applications, making it particularly suitable for modern web publishing workflows. By utilizing Spire.PDF for .NET, developers can automate the conversion process, ensuring that the rich formatting and structure of the original PDFs are preserved in the resulting Markdown files.

This article will demonstrate how to use Spire.PDF for .NET to convert PDF documents to Markdown format with C# code.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF 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.PDF

Convert PDF Documents to Markdown Files

With the Spire.PDF for .NET library, developers can easily load any PDF file using the PdfDocument.LoadFromFile(string filename) method and then save the document in the desired format by calling the PdfDocument.SaveToFile(string filename, FileFormat fileFormat) method. To convert a PDF to Markdown format, simply specify the FileFormat.Markdown enumeration as a parameter when invoking the method.

The detailed steps for converting PDF documents to Markdown files are as follows:

  • Create an instance of PdfDocument class.
  • Load a PDF document using PdfDocument.LoadFromFile(string filename) method.
  • Convert the document to a Markdown file using PdfDocument.SaveToFile(string filename, FileFormat.Markdown) method.
  • C#
using Spire.Pdf;

namespace PDFToMarkdown
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of PdfDocument class
            PdfDocument pdf = new PdfDocument();

            // Load a PDF document
            pdf.LoadFromFile("Sample.pdf");

            // Convert the document to Markdown file
            pdf.SaveToFile("output/PDFToMarkdown.md", FileFormat.Markdown);

            // Release resources
            pdf.Close();
        }
    }
}

The PDF Document:

C#: Convert PDF to Markdown

The Result Markdown File:

C#: Convert PDF to Markdown

Convert PDF to Markdown by Streams

In addition to directly reading files for manipulation, Spire.PDF for .NET also supports loading a PDF document from a stream using PdfDocument.LoadFromStream() method and converting it to a Markdown file stream using PdfDocument.SaveToStream() method. Using streams reduces memory usage, supports large files, enables real-time data transfer, and simplifies data exchange with other systems.

The detailed steps for converting PDF documents to Markdown files by streams are as follows:

  • Create a Stream object of PDF documents by downloading from the web or reading from a file.
  • Load the PDF document from the stream using PdfDocument.LoadFromStream(Stream stream) method.
  • Create another Stream object to store the converted Markdown file.
  • Convert the PDF document to a Markdown file stream using PdfDocument.SaveToStream(Stream stream, FileFormat.Markdown) method.
  • C#
using Spire.Pdf;
using System.IO;
using System.Net.Http;

namespace PDFToMarkdownByStream
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Create an instance of PdfDocument class
            PdfDocument pdf = new PdfDocument();

            // Download a PDF document from a url as bytes
            using (HttpClient client = new HttpClient())
            {
                byte[] pdfBytes = await client.GetByteArrayAsync("http://example.com/Sample.pdf");

                // Create a MemoryStream using the bytes
                using (MemoryStream inputStream = new MemoryStream(pdfBytes))
                {
                    // Load the PDF document from the stream
                    pdf.LoadFromStream(inputStream);

                    // Create another MemoryStream object to store the Markdown file
                    using (MemoryStream outputStream = new MemoryStream())
                    {
                        // Convert the PDF document to a Markdown file stream
                        pdf.SaveToStream(outputStream, FileFormat.Markdown);
                        outputStream.Position = 0; // Reset the position of the stream for subsequent reads

                        // Upload the result stream or write it to a file
                        await client.PostAsync("http://example.com/upload", new StreamContent(outputStream));
                        File.WriteAllBytes("output.md", outputStream.ToArray());
                    }
                }
            }

            // Release resources
            pdf.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.

Transforming text to numbers and vice versa in Excel is essential for effective data management. By converting text to numbers, you enhance the accuracy of calculations and data processing, which is vital for activities such as financial reporting and statistical analysis. Conversely, changing numbers to text can improve formatting, making outputs clearer and more readable, ultimately presenting data in a more user-friendly way.

In this article, you will learn how to convert text to numbers and numbers to text in Excel 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

Convert Text to Numbers in C#

When you import data from an external source into Excel, you might notice a small green triangle in the upper-left corner of certain cells. This triangle serves as an error indicator, signaling that the number is formatted as text. When numbers are stored as text, it can lead to unexpected outcomes, such as formulas not calculating correctly and displaying as text instead of yielding results.

To convert text-formatted numbers back to numeric format, you can use the CellRange.ConvertToNumber() method. The CellRange object can refer to either a single cell or a range of cells.

Here are the steps to convert text to numbers in Excel:

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Access a specific worksheet with Workbook.Worksheets[index] property.
  • Retrieve a cell or range of cells using Worksheet.Range property.
  • Convert the text in the cell(s) to numbers using CellRange.ConvertToNumber() method.
  • Save the document as a new Excel file.
  • C#
using Spire.Xls;

namespace ConvertTextToNumbers
{
    class Program
    {
        static void Main(string[] args)
        {

            // Create a Workbook object
            Workbook workbook = new Workbook();

            // Load an Excel document
            workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

            // Get a specific worksheet
            Worksheet worksheet = workbook.Worksheets[0];

            // Get a cell range
            CellRange range = worksheet.Range["D2:G13"];

            // Convert text to number
            range.ConvertToNumber();

            // Save the workbook to a different Excel file
            workbook.SaveToFile("TextToNumbers.xlsx", ExcelVersion.Version2013);

            // Dispose resources
            workbook.Dispose();
        }
    }
}

C#: Convert Text to Numbers and Numbers to Text

Convert Numbers to Text in C#

When working with numerical data in Excel, you may find occasions where converting numbers to text is necessary. This is especially crucial for data that requires specific formatting, such as IDs or phone numbers, where leading zeros must be preserved.

To convert a number in a cell to text, you can set the CellRange.NumberFormat property to @. The CellRange object can represent either a single cell or a range of cells.

Here are the steps to convert numbers to text in Excel:

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Access a specific worksheet through Workbook.Worksheets[index] property.
  • Retrieve a specific cell or range of cells using Worksheet.Range property.
  • Convert the numbers in the cell(s) to text by setting CellRange.NumberFormat to @.
  • Save the document as a new Excel file.
  • C#
using Spire.Xls;

namespace ConvertNumbersToText
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();

            // Load an Excel document
            workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Employee.xlsx");

            // Get a specific worksheet
            Worksheet worksheet = workbook.Worksheets[0];

            // Get a cell range
            CellRange cellRange = worksheet.Range["F2:F9"];

            // Convert numbers in the cell range to text
            cellRange.NumberFormat = "@";

            // Save the workbook to a different Excel file
            workbook.SaveToFile("NumbersToText.xlsx", ExcelVersion.Version2013);

            // Dispose resources
            workbook.Dispose();
        }
    }
}

C#: Convert Text to Numbers and Numbers to Text

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.

C#: Crop Pages in PDF

2024-09-18 01:10:05 Written by support iceblue

PDF page cropping is particularly useful in scenarios where the original document has excessive margins or borders that are not necessary for the intended use. By cropping pages, you can preserve the designated area for specific use, making the document more efficient for sharing, printing, or digital presentations. In this article, you will learn how to crop pages in PDF in C# using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF 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.PDF

Crop a PDF Page in C#

Spire.PDF for .NET allows you specify a rectangular area, and then use the PdfPageBase.CropBox property to crop page to the specified area. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Get a specified page using PdfDocument.Pages[] property.
  • Crop the page to the specified area using PdfPageBase.CropBox property.
  • Save the result file using PdfDocument.SaveToFile() method.
  • C#
using System.Drawing;
using Spire.Pdf;

namespace CropPDFPage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            //Load a PDF file from disk
            pdf.LoadFromFile("Sample1.pdf");

            //Get the first page
            PdfPageBase page = pdf.Pages[0];

            //Crop the page by the specified area
            page.CropBox = new RectangleF(0, 300, 600, 260);

            //Save the result file
            pdf.SaveToFile("CropPDF.pdf");
            pdf.Close();
        }
    }
}

C#: Crop Pages in PDF

Crop a PDF Page and Export as an Image in C#

To accomplish this task, you can use the PdfDocument.SaveAsImage(int pageIndex, PdfImageType type) method to convert a cropped PDF page to an image. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Get a specified page using PdfDocument.Pages[] property.
  • Crop the page to the specified area using PdfPageBase.CropBox property.
  • Convert the copped page to an image using PdfDocument.SaveAsImage() method.
  • Save the image as a PNG, JPG or BMP file using Image.Save(string filename, ImageFormat format) method.
  • C#
using System.Drawing;
using System.Drawing.Imaging;
using Spire.Pdf;
using Spire.Pdf.Graphics;

namespace CropPDFPageToImage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            //Load a PDF file from disk
            pdf.LoadFromFile("Sample1.pdf");

            //Get the first page
            PdfPageBase page = pdf.Pages[0];

            //Crop the page by the specified area
            page.CropBox = new RectangleF(0, 300, 600, 260);

            //Convert the page to an image
            Image image = pdf.SaveAsImage(0, PdfImageType.Bitmap);

            //Save the image as a PNG file
            image.Save("CropPDFSaveAsImage.png", ImageFormat.Png);

            //Save the image as a JPG file
            //image.Save("ToJPG.jpg", ImageFormat.Jpeg);

            //Save the image as a BMP file
            //image.Save("ToBMP.bmp", ImageFormat.Bmp);
        }
    }
}

C#: Crop Pages 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.

When printing Excel spreadsheets, particularly those containing complex datasets or detailed reports, configuring the page setup properly is crucial. Excel’s page setup options enable you to adjust key factors such as page margins, orientation, paper size, and scaling, ensuring your documents are tailored to fit various printing needs. By customizing these settings, you can control how your content is displayed on the page, making sure it appears polished and professional. In this article, we will demonstrate how to set page setup options in 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

Set Page Margins in Excel in C#

The PageSetup class in Spire.XLS for .NET is used to configure page setup options for Excel worksheets. You can access the PageSetup object of a worksheet through the Worksheet.PageSetup property. Then, use properties like PageSetup.TopMargin, PageSetup.BottomMargin, PageSetup.LeftMargin, PageSetup.RightMargin, PageSetup.HeaderMarginInch, and PageSetup.FooterMarginInch to set the corresponding margins for the worksheet. 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 using Workbook.Worksheets[index] property.
  • Access the PageSetup object of the worksheet using Worksheet.PageSetup property.
  • Set the top, bottom, left, right, header, and footer margins using PageSetup.TopMargin, PageSetup.BottomMargin, PageSetup.LeftMargin, PageSetup.RightMargin, PageSetup.HeaderMarginInch, and PageSetup.FooterMarginInch properties.
  • Save the modified workbook to a new file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;

namespace SetPageMargins
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();

            // Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

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

            // Get the PageSetup object of the worksheet
            PageSetup pageSetup = sheet.PageSetup;

            // Set top, bottom, left, and right page margins for the worksheet
            // The measure of the unit is Inch (1 inch = 2.54 cm)
            pageSetup.TopMargin = 1;
            pageSetup.BottomMargin = 1;
            pageSetup.LeftMargin = 1;
            pageSetup.RightMargin = 1;
            pageSetup.HeaderMarginInch = 1;
            pageSetup.FooterMarginInch = 1;

            // Save the modified workbook to a new file
            workbook.SaveToFile("SetPageMargins.xlsx", ExcelVersion.Version2016);
            workbook.Dispose();
        }
    }
}

C#: Set Page Setup Options in Excel

Set Page Orientation in Excel in C#

The PageSetup.Orientation property lets you determine how the page should be oriented when printed. You can choose between two options: portrait mode or landscape mode. 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 using Workbook.Worksheets[index] property.
  • Access the PageSetup object of the worksheet using Worksheet.PageSetup property.
  • Set the page orientation using PageSetup.Orientation property.
  • Save the modified workbook to a new file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;

namespace SetPageOrientation
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Page Orientation
            // Create a Workbook object
            Workbook workbook = new Workbook();

            // Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

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

            // Get the PageSetup object of the worksheet
            PageSetup pageSetup = sheet.PageSetup;

            // Set the page orientation for printing the worksheet to landscape mode
            pageSetup.Orientation = PageOrientationType.Landscape;

            // Save the modified workbook to a new file
            workbook.SaveToFile("SetPageOrientation.xlsx", ExcelVersion.Version2016);
            workbook.Dispose();
        }
    }
}

C#: Set Page Setup Options in Excel

Set Paper Size in Excel in C#

The PageSetup.PaperSize property enables you to select from a variety of paper sizes for printing your worksheet. These options include A3, A4, A5, B4, B5, letter, legal, tabloid, and more. 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 using Workbook.Worksheets[index] property.
  • Access the PageSetup object of the worksheet using Worksheet.PageSetup property.
  • Set the paper size using PageSetup.PaperSize property.
  • Save the modified workbook to a new file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;

namespace SetPaperSize
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();

            // Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

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

            // Get the PageSetup object of the worksheet
            PageSetup pageSetup = sheet.PageSetup;

            // Set the paper size to A4
            pageSetup.PaperSize = PaperSizeType.PaperA4;

            // Save the modified workbook to a new file
            workbook.SaveToFile("SetPaperSize.xlsx", ExcelVersion.Version2016);
            workbook.Dispose();
        }
    }
}

C#: Set Page Setup Options in Excel

Set Print Area in Excel in C#

You can specify the exact area that you want to print using the PageSetup.PringArea property. 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 using Workbook.Worksheets[index] property.
  • Access the PageSetup object of the worksheet using Worksheet.PageSetup property.
  • Set the print area using PageSetup.PringArea property.
  • Save the modified workbook to a new file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;

namespace SetPrintArea
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();

            // Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

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

            // Get the PageSetup object of the worksheet
            PageSetup pageSetup = sheet.PageSetup;

            // Set the print area of the worksheet to "A1:E5"
            pageSetup.PrintArea = "A1:E5";

            // Save the modified workbook to a new file
            workbook.SaveToFile("SetPrintArea.xlsx", ExcelVersion.Version2016);
            workbook.Dispose();
        }
    }
}

C#: Set Page Setup Options in Excel

Set Scaling Factor in Excel in C#

If you want to scale the content of your worksheet to a specific percentage of its original size, use the PageSetup.Zoom property. 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 using Workbook.Worksheets[index] property.
  • Access the PageSetup object of the worksheet using Worksheet.PageSetup property.
  • Set the scaling factor using PageSetup.Zoom property.
  • Save the modified workbook to a new file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;

namespace SetScalingFactor
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();

            // Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

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

            // Get the PageSetup object of the worksheet
            PageSetup pageSetup = sheet.PageSetup;

            // Set the scaling factor of the worksheet to 90%
            pageSetup.Zoom = 90;

            // Save the modified workbook to a new file
            workbook.SaveToFile("SetScalingFactor.xlsx", ExcelVersion.Version2016);
            workbook.Dispose();
        }
    }
}

C#: Set Page Setup Options in Excel

Set Fit-to-Pages Options in Excel in C#

Spire.XLS also enables you to fit your worksheet content to a specific number of pages by using the PageSetup.FitToPagesTall and PageSetup.FitToPagesWide properties. 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 using Workbook.Worksheets[index] property.
  • Access the PageSetup object of the worksheet using Worksheet.PageSetup property.
  • Fit the content of the worksheet to one page using PageSetup.FitToPagesTall and PageSetup.FitToPagesWide properties.
  • Save the modified workbook to a new file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;

namespace SetFitToPages
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();

            // Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

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

            // Get the PageSetup object of the worksheet
            PageSetup pageSetup = sheet.PageSetup;

            // Fit the content of the worksheet within one page vertically (i.e., all rows will fit on a single page)
            pageSetup.FitToPagesTall = 1;
            // Fit the content of the worksheet within one page horizontally (i.e., all columns will fit on a single page)
            pageSetup.FitToPagesWide = 1;

            // Save the modified workbook to a new file
            workbook.SaveToFile("FitToPages.xlsx", ExcelVersion.Version2016);
            workbook.Dispose();
        }
    }
}

C#: Set Page Setup Options in Excel

Set Headers and Footers in Excel in C#

For setting headers and footers in Excel, please check this article: C#/VB.NET: Add Headers and Footers to 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.

In some cases, checking the size, orientation, and rotation of PDF pages can be part of the quality control process. For example, before publishing or distributing a document, you might need to verify this information to ensure that all pages in the document are correctly presented. In this article, you will learn how to get PDF page size, orientation and rotation angle in C# using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF 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.PDF 

Get PDF Page Size in C#

Spire.PDF for .NET offers the PdfPageBase.Size.Width and PdfPageBase.Size.Height properties to get the width and height of a PDF page in points. If you want to convert the default unit of measure to other units, you can use the PdfUnitConvertor class. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Get a specified page using PdfDocument.Pages[] property.
  • Get the width and height of the PDF page using PdfPageBase.Size.Width and PdfPageBase.Size.Height properties.
  • Create a PdfUnitConvertor instance, and then convert the size units from points to other units of measure using PdfUnitConvertor.ConvertUnits() method.
  • Add the page size information to a StringBuilder instance, and then save the result to a TXT file.
  • C#
using System.Text;
using Spire.Pdf;
using Spire.Pdf.Graphics;

namespace GetPDFPageSize
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            //Load a PDF file from disk
            pdf.LoadFromFile("SamplePDF.pdf");

            //Get the first page 
            PdfPageBase page = pdf.Pages[0];

            //Get the width and height of the page in "point"
            float pointWidth = page.Size.Width;
            float pointHeight = page.Size.Height;

            //Create PdfUnitConvertor to convert the unit
            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();

            //Convert size units from points to pixels
            float pixelWidth = unitCvtr.ConvertUnits(pointWidth, PdfGraphicsUnit.Point, PdfGraphicsUnit.Pixel);
            float pixelHeight = unitCvtr.ConvertUnits(pointHeight, PdfGraphicsUnit.Point, PdfGraphicsUnit.Pixel);

            //Convert size units from points to inches
            float inchWidth = unitCvtr.ConvertUnits(pointWidth, PdfGraphicsUnit.Point, PdfGraphicsUnit.Inch);
            float inchHeight = unitCvtr.ConvertUnits(pointHeight, PdfGraphicsUnit.Point, PdfGraphicsUnit.Inch);

            //Convert size units from points to centimeters
            float centimeterWidth = unitCvtr.ConvertUnits(pointWidth, PdfGraphicsUnit.Point, PdfGraphicsUnit.Centimeter);
            float centimeterHeight = unitCvtr.ConvertUnits(pointHeight, PdfGraphicsUnit.Point, PdfGraphicsUnit.Centimeter);

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

            //Add the page size information to the StringBuilder instance 
            content.AppendLine("The page size of the file in points is (width: " + pointWidth + "pt, height: " + pointHeight + "pt).");
            content.AppendLine("The page size of the file in pixels is (width: " + pixelWidth + "pixel, height: " + pixelHeight + "pixel).");
            content.AppendLine("The page size of the file in inches is (width: " + inchWidth + "inch, height: " + inchHeight + "inch).");
            content.AppendLine("The page size of the file in centimeters is (width: " + centimeterWidth + "cm, height: " + centimeterHeight + "cm).");

            //Save to a txt file
            File.WriteAllText("GetPageSize.txt", content.ToString());
        }
    }
}

C#: Get Page Size, Orientation and Rotation of PDF

Detect PDF Page Orientation in C#

To detect the orientation of a PDF page, you can compare the width and height of the page. If the page width is greater than the height, then the page orientation is landscape, otherwise it is portrait. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Get a specified page using PdfDocument.Pages[] property.
  • Get the width and height of the PDF page using PdfPageBase.Size.Width and PdfPageBase.Size.Height properties.
  • Compare the values of page width and height to detect the page orientation.
  • Output the result using Console.WriteLine() method.
  • C#
using Spire.Pdf;

namespace GetPDFPageOrientation
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            //Load a PDF file from disk
            pdf.LoadFromFile("SamplePDF.pdf");

            //Get the first page 
            PdfPageBase page = pdf.Pages[0];

            //Get the width and height of the page
            float width = page.Size.Width;
            float height = page.Size.Height;

            //Compare the values of page width and height 
            if (width > height)
            {
                Console.WriteLine("The page orientation is Landscape.");
            }

            else
            {
                Console.WriteLine("The page orientation is Portrait.");
            }
        }
    }
}

C#: Get Page Size, Orientation and Rotation of PDF

Detect PDF Page Rotation Angle in C#

The rotation angle of a PDF page can be obtained through the PdfPageBase.Rotation property. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Get a specified page using PdfDocument.Pages[] property.
  • Get the rotation angle of the page using PdfPageBase.Rotation property, and then convert it to text string.
  • Output the result using Console.WriteLine() method.
  • C#
using Spire.Pdf;

namespace GetPDFPageRotationAngle
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            //Load a PDF file from disk
            pdf.LoadFromFile("E:\\PythonPDF\\Sample.pdf");

            //Get the first page 
            PdfPageBase page = pdf.Pages[0];

            //Get the rotation angle of the current page
            PdfPageRotateAngle rotationAngle = page.Rotation;
            string rotation = rotationAngle.ToString();

            //Output the page rotation angle information
            Console.WriteLine("The rotation angle of the current page is: " + rotation);
        }
    }
}

C#: Get Page Size, Orientation and Rotation of 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.

Creating charts in PowerPoint slides is a powerful way to enhance presentations by visually representing complex information, making it easier for audiences to grasp key insights. By reading Excel data directly to generate charts, you can streamline the data entry process and ensure data accuracy. Or, if you want to use charts from Excel files directly in PowerPoint presentations, you can directly insert them as pictures into PowerPoint slides, thus maximizing the original formatting and appearance. This article will show how to create charts in PowerPoint slides from Excel data using Spire.Office for .NET in .NET programs.

Install Spire.Office for .NET

To begin with, you need to add the DLL files included in the Spire.Office 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.Office

Create Charts in PowerPoint Slides with Excel Data using C#

Developers can read data from Excel worksheets with Spire.XLS for .NET and then create charts in PowerPoint slides with Spire.Presentation for .NET using the read data as the charts' data source. The detailed steps for creating charts in PowerPoint presentations with Excel file data are as follows:

  • Create an instance of Presentation class.
  • Create an instance of Workbook class and load an Excel file using Workbook.LoadFromFile() method.
  • Get the first slide in the presentation through Presentation.Slides[] property and create a chart in the first slide of the presentation using ISlide.Shapes.AppendChart() method.
  • Clear the default dummy data using IChart.ChartData.Clear() method.
  • Get the first worksheet in the workbook through Workbook.Worksheets[] property.
  • Iterate through rows in the worksheet and then the columns in the worksheet:
    • Get the cell values in the worksheet through Worksheet.AllocatedRange[].Value2 property and set them as the values of the chart’s data through IChart.ChartData[].Value property.
  • Set the chart title using properties under IChart.ChartTitle property.
  • Set the chart series labels and category labels through IChart.Series.SeriesLabel and IChart.Categories.CategoryLabels properties.
  • Set the series values through IChart.Series[].Values property.
  • Set the number format of the axis through IChart.PrimaryCategoryAxis.NumberFormat and IChart.PrimaryValueAxis.NumberFormat properties.
  • Set the style of the chart through IChart.ChartStyle property.
  • Save the presentation using Presentation.SaveToFile() method.
  • C#
using Spire.Presentation;
using Spire.Presentation.Charts;
using Spire.Xls;
using System.Drawing;
using FileFormat = Spire.Presentation.FileFormat;
using IChart = Spire.Presentation.Charts.IChart;

namespace PresentationChartExcelData
{
    class Program
    {
        public static void Main(string[] args)
        {
            // Create an instance of Presentation class
            Presentation presentation = new Presentation();

            // Set the slide size
            presentation.SlideSize.Type = SlideSizeType.Screen16x9;

            // Create an instance of Workbook class and load an Excel file
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");

            // Get the first worksheet in the workbook
            Worksheet sheet = workbook.Worksheets[0];

            // Create a chart in the presentation
            RectangleF rect = new RectangleF(50, 100, presentation.SlideSize.Size.Width - 100, presentation.SlideSize.Size.Height - 150);
            ISlide slide = presentation.Slides[0];
            IChart chart = slide.Shapes.AppendChart(ChartType.ColumnClustered, rect);

            // Clear the default dummy data
            chart.ChartData.Clear(0, 0, 5, 5);

            // Iterate through the rows in the worksheet
            for (int i = 0; i < sheet.AllocatedRange.RowCount; i++)
            {
                // Iterate through the columns in the worksheet
                for (int j = 0; j < sheet.AllocatedRange.ColumnCount; j++)
                {
                    // Set the cell values in the worksheet as the values of the chart data
                    chart.ChartData[i, j].Value = sheet.AllocatedRange[i + 1, j + 1].Value2;
                    // Copy number formats
                    chart.ChartData[i, j].NumberFormat = sheet.AllocatedRange[i + 1, j + 1].NumberFormat;
                }
            }

            // Set the chart title
            chart.ChartTitle.TextProperties.Text = sheet.Name;
            chart.ChartTitle.TextProperties.IsCentered = true;
            chart.ChartTitle.Height = 25;
            chart.HasTitle = true;

            // Set the series labels and category labels
            chart.Series.SeriesLabel = chart.ChartData["B1", "C1"];
            chart.Categories.CategoryLabels = chart.ChartData["A2", "A" + sheet.AllocatedRange.RowCount];

            // Set the series values
            chart.Series[0].Values = chart.ChartData["B2", "B" + sheet.AllocatedRange.RowCount];
            chart.Series[1].Values = chart.ChartData["C2", "C" + sheet.AllocatedRange.RowCount];

            // Set the number format of the axis
            chart.PrimaryCategoryAxis.NumberFormat = sheet.AllocatedRange["A2"].NumberFormat;
            chart.PrimaryValueAxis.NumberFormat = sheet.AllocatedRange["B2"].NumberFormat;

            // Set the style of the chart
            chart.ChartStyle = ChartStyle.Style2;

            // Set the overlap and gap width
            chart.OverLap = 50;
            chart.GapWidth = 200;

            // Save the presentation
            presentation.SaveToFile("output/PresentationChartExcelData.pptx", FileFormat.Pptx2019);
            presentation.Dispose();
            workbook.Dispose();
        }
    }
}

C#: Create Charts in PowerPoint Slides with Excel Data

Insert Excel Charts into PowerPoint Slides as Images using C#

To insert an existing chart from an Excel worksheet into a PowerPoint slide while maintaining its appearance and formatting precisely, the Workbook.SaveChartAsImage() method can be employed. This method allows the Excel chart to be saved as an image, which can then be added to the slide. The specific steps are as follows:

  • Create an instance of Presentation class.
  • Create an instance of Workbook class and load an Excel file using Workbook.LoadFromFile() method.
  • Save a chart in a worksheet as an image using Workbook.SaveChartAsImage() method.
  • Embed the image into the presentation using Presentation.Images.Append() method.
  • Add the image to a slide using Presentation.Slides[].AppendEmbedImage() method.
  • Save the presentation using Presentation.SaveToFile() method.
  • C#
using Spire.Presentation;
using Spire.Presentation.Drawing;
using Spire.Xls;
using System.Drawing;
using FileFormat = Spire.Presentation.FileFormat;

namespace PresentationChartExcelChart
{
    class Program
    {
        public static void Main(string[] args)
        {
            // Create an instance of Presentation class
            Presentation presentation = new Presentation();

            // Set the slide size
            presentation.SlideSize.Type = SlideSizeType.Screen16x9;

            // Create an instance of Workbook class and load an Excel file
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");

            // Save the first chart in the first worksheet as an image
            Image image = workbook.SaveChartAsImage(workbook.Worksheets[0], 0);

            // Embed the image into the presentation
            IImageData imageData = presentation.Images.Append(image);

            // Add the image to the first slide
            RectangleF rect = new RectangleF(50, 120, presentation.SlideSize.Size.Width - 100, presentation.SlideSize.Size.Height - 170);
            presentation.Slides[0].Shapes.AppendEmbedImage(ShapeType.Rectangle, imageData, rect);

            // Save the presentation
            presentation.SaveToFile("output/PresentationChartExcelChart.pptx", FileFormat.Pptx2019);
            presentation.Dispose();
            workbook.Dispose();
        }
    }
}

C#: Create Charts in PowerPoint Slides with Excel Data

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 Word documents allow users to organize data in a clear and structured manner. However, as documents grow in complexity, the need to adjust table structures often arises. Whether you need to combine multiple tables for a comprehensive view or divide a large table for better readability, mastering the art of merging and splitting tables in Word can significantly improve the presentation of your data.  In this article, you will learn how to merge or split tables in Word in C# using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc 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.Doc

Merge Tables in Word in C#

With Spire.Doc for .NET, you can combine two or more tables into one by copying all rows from other tables to the target table and then deleting the other tables. The following are the detailed steps.

  • Create a Document instance.
  • Load a Word document using Document.LoadFromFile() method.
  • Get a specified section using Document.Sections[] property.
  • Get two tables in the section using section.Tables[] property.
  • Iterate through all rows in the second table and copy them using Table.Rows[].Clone() method.
  • Add the rows of the second table to the first table using Table.Rows.Add() method.
  • Save the result document using Document.SaveToFile() method.
  • C#
using Spire.Doc;

namespace CombineTables
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document doc = new Document();

            //Load a Word document
            doc.LoadFromFile("Cost.docx");

            //Get the first section
            Section section = doc.Sections[0];

            //Get the first and second table in the section
            Table table1 = section.Tables[0] as Table;
            Table table2 = section.Tables[1] as Table;

            //Add the rows of table2 to table1
            for (int i = 0; i < table2.Rows.Count; i++)
            {
                table1.Rows.Add(table2.Rows[i].Clone());
            }

            //Remove the table2
            section.Tables.Remove(table2);

            //Save the result document
            doc.SaveToFile("CombineTables.docx", FileFormat.Docx);
        }
    }
}

C#: Merge or Split Tables in Word

Split Tables in Word in C#

To split a table into two or more tables, you need to create a new table, then copy the specified rows from the original table to the new table, and then delete those rows from the original table. The following are the detailed steps.

  • Create a Document instance.
  • Load a Word document using Document.LoadFromFile() method.
  • Get a specified section using Document.Sections[] property.
  • Get a specified table in the section using section.Tables[] property.
  • Specify the row index where the table will be split.
  • Create a new instance of the Table class.
  • Iterate through the specified rows in the original table and copy them using Table.Rows[].Clone() method.
  • Add the specified rows to the new table using Table.Rows.Add() method.
  • Iterate through the copied rows and remove each row from the original table using Table.Rows.RemoveAt() method.
  • Add the new table to the section using Section.Tables.Add() method.
  • Save the result document using Document.SaveToFile() method.
  • C#
using Spire.Doc;

namespace SplitWordTable
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document doc = new Document();

            //Load a Word document
            doc.LoadFromFile("CombineTables.docx");

            //Get the first section
            Section section = doc.Sections[0];

            //Get the first table in the section
            Table table = section.Tables[0] as Table;

            //Specify to split the table from the fifth row
            int splitIndex = 4;

            //Create a new table
            Table newTable = new Table(section.Document);

            //Adds rows (from the 5th to the last row) to the new table
            for (int i = splitIndex; i < table.Rows.Count; i++)
            {
                newTable.Rows.Add(table.Rows[i].Clone());
            }

            //Delete rows from the original table
            for (int i = table.Rows.Count - 1; i >= splitIndex; i--)
            {
                table.Rows.RemoveAt(i);
            }

            //Add the new table to the section
            section.Tables.Add(newTable);

            //Save the result document
            doc.SaveToFile("SplitTable.docx", FileFormat.Docx);
        }
    }
}

C#: Merge or Split Tables in Word

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 1 of 91
page 1