When working with Word documents, batch extraction of hyperlinks has significant practical applications. Manually extracting URLs from technical documents or product manuals is not only inefficient but also prone to omissions and errors. To address this, this article presents an automated solution using C# to accurately extract hyperlink anchor text, corresponding URLs, and screen tips by parsing document elements. The extracted hyperlink data can support data analysis, SEO optimization, and other applications. The following sections demonstrate how to use Spire.Doc for .NET to extract hyperlinks from a Word document with C# code in .NET programs.

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

Extracting All Hyperlinks from a Word Document Using C#

In a Word document, hyperlinks are stored as fields. To extract them, the first step is to identify all field objects by checking whether each document object is an instance of the Field class. Then, by checking whether the field object's Type property equals FieldType.FieldHyperlink, we can extract all hyperlink fields.

Once the hyperlinks are identified, we can use the Field.FieldText property to retrieve the hyperlink anchor text and the Field.GetFieldCode() method to obtain the full field code in the following format:

Hyperlink Type Field Code Example
Standard Hyperlink HYPERLINK "https://www.example.com/example"
Hyperlink with ScreenTip HYPERLINK "https://www.example.com/example" \o "ScreenTip"

By parsing the field code, we can extract both the hyperlink URL and the screen tip text, enabling complete retrieval of hyperlink information.

  • Create a Document object and use the Document.LoadFromFile() method to load the target Word document.
  • Iterate through all sections in the document using foreach (Section section in doc.Sections) to retrieve each section object.
  • For each section, iterate through its child objects using foreach (DocumentObject secObj in section.Body.ChildObjects) to access individual elements.
  • If a child object is of type Paragraph:
    • Iterate through the child objects within the paragraph using foreach (DocumentObject paraObj in paragraph.ChildObjects).
  • If a paragraph child object is of type Field and its Field.Type property value equals FieldType.FieldHyperlink, process the Field object.
  • For each Field object:
    • Extract the anchor text using the Field.FieldText property.
    • Retrieve the field code string using the Field.GetFieldCode() method.
  • Process the field code string:
    • Extract the URL enclosed in quotation marks after "HYPERLINK".
    • Check if the field code contains the \o parameter; if present, extract the screen tip text enclosed in double quotes.
  • Store the extracted hyperlinks and write them to an output file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace ExtractWordHyperlink
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of Document
            Document doc = new Document();
            // Load a Word document
            doc.LoadFromFile("Sample.docx");

            // Create a string list to store the hyperlink information
            List<string> hyperlinkInfoList = new List<string>();

            // Iterate through the sections in the document
            foreach (Section section in doc.Sections)
            {
                // Iterate through the child objects in the section
                foreach (DocumentObject secObj in section.Body.ChildObjects)
                {
                    // Check if the current document object is a Paragraph instance
                    if (secObj is Paragraph paragraph )
                    {
                        // Iterate through the child objects in the paragraph
                        foreach (DocumentObject paraObj in paragraph.ChildObjects)
                        {
                            // Check if the current child object is a field
                            if (paraObj is Field field && field.Type == FieldType.FieldHyperlink)
                            {
                                string hyperlinkInfo = "";
                                // Get the anchor text
                                string anchorText = field.FieldText;

                                // Get the field code
                                string fieldCode = field.GetFieldCode();
                                // Get the URL from the field code
                                string url = fieldCode.Split('"')[1];
                                // Check if there is a ScreenTip
                                if (fieldCode.Contains("\\o"))
                                {
                                    // Get the ScreenTip text
                                    string screenTip = fieldCode.Split("\"")[3].Trim();
                                    // Consolidate the information
                                    hyperlinkInfo += $"Anchor Text: {anchorText}\nURL: {url}\nScreenTip: {screenTip}";
                                }
                                else
                                {
                                    hyperlinkInfo += $"Anchor Text: {anchorText}\nURL: {url}";
                                }
                                hyperlinkInfo += "\n";
                                // Append the hyperlink information to the list
                                hyperlinkInfoList.Add(hyperlinkInfo);

                            }
                        }
                    }
                }
            }

            // Write the extracted hyperlink information to a text file
            File.WriteAllLines("output/ExtractedHyperlinks.txt", hyperlinkInfoList);

            doc.Close();
        }
    }
}

Hyperlinks Extracted from Word Documents Using C#

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 a PDF, ensuring the content appears as intended is crucial. Depending on your needs, you may want to print the document at the actual size to maintain the original dimensions or scale it to fit the entire page for a better presentation.

C# Print PDF in Actual Size or Fit to Page

To accommodate different printing needs, Spire.PDF for .NET provides flexible printing options that allow developers to control the output easily. This article will demonstrate how to print a PDF either at the actual size or fit to page in C# using the Spire.PDF for .NET library.

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

Print a PDF to Fit the Page Size in C#

When printing a PDF to fit the page, the content is automatically scaled to match the dimensions of the paper. This ensures that the document fits within the printed area, regardless of its original size.

To fit the content to the page, you can use the PdfDocument.PrintSettings.SelectSinglePageLayout(PdfSinglePageScalingMode pageScalingMode, bool autoPortraitOrLandscape) method. The detailed steps are as follows.

  • Create an instance of the PdfDocument class.
  • Load the PDF file using the PdfDocument.LoadFromFile() method.
  • Configure print settings to scale the PDF to fit the page size for printing using the PdfDocument.PrintSettings.SelectSinglePageLayout(PdfSinglePageScalingMode pageScalingMode, bool autoPortraitOrLandscape) method.
  • Call the PdfDocument.Print() method to print the PDF file.
  • C#
using Spire.Pdf;
using Spire.Pdf.Print;

namespace PrintPdfToFitPageSize
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the PdfDocument class
            PdfDocument pdf = new PdfDocument();
            // Load the specified PDF file into the PdfDocument object
            pdf.LoadFromFile("Sample.pdf");

            // Configure print settings to scale the PDF to fit the page size for printing
            pdf.PrintSettings.SelectSinglePageLayout(PdfSinglePageScalingMode.FitSize, false);
            // Execute the print command to print the loaded PDF document
            pdf.Print();
            

        }
    }
}

Print a PDF at the Actual Size in C#

When printing a PDF at the actual size, the original document dimensions are preserved without scaling. This ensures that the printed output matches the PDF's defined measurements.

To print a PDF at its actual size, you can also use the PdfDocument.PrintSettings.SelectSinglePageLayout(PdfSinglePageScalingMode pageScalingMode, bool autoPortraitOrLandscape) method. The detailed steps are as follows.

  • Create an instance of the PdfDocument class.
  • Load the PDF file using the PdfDocument.LoadFromFile() method.
  • Configure print settings to print the PDF at its actual size without scaling using the PdfDocument.PrintSettings.SelectSinglePageLayout(PdfSinglePageScalingMode pageScalingMode, bool autoPortraitOrLandscape) method.
  • Call the PdfDocument.Print() method to print the PDF file.
  • C#
using Spire.Pdf;
using Spire.Pdf.Print;
using System.Drawing.Printing;

namespace PrintPdfAtActualSize
{
    internal class Program
    {
        static void Main(string[] args)
        {         
            // Create a new instance of the PdfDocument class
            PdfDocument pdf = new PdfDocument();
            // Load the PDF file into the PdfDocument object
            pdf.LoadFromFile("Sample.pdf");

            // Set paper margins as 0
            pdf.PrintSettings.SetPaperMargins(0, 0, 0, 0);

            // Configure print settings to print the PDF at its actual size without scaling
            pdf.PrintSettings.SelectSinglePageLayout(PdfSinglePageScalingMode.ActualSize, false);
            // Execute the print command to print the loaded PDF document
            pdf.Print();
        }
    }
}

Print a PDF at the Actual Size on Custom-Sized Paper

In some cases, you may need to print a PDF at its actual size on a specific size of paper. Spire.PDF allows you to define a custom paper size using the PaperSize class and then you can assign it to the print settings of the document using the PdfDocument.PrintSettings.PaperSize property. The detailed steps are as follows.

  • Create an instance of the PdfDocument class.
  • Load the PDF file using the PdfDocument.LoadFromFile() method.
  • Define a custom paper size for printing using the PaperSize class.
  • Assign the custom paper size to the print settings of the file using the using the PdfDocument.PrintSettings.PaperSize property.
  • Configure print settings to print the PDF at its actual size without scaling using the PdfDocument.PrintSettings.SelectSinglePageLayout(PdfSinglePageScalingMode pageScalingMode, bool autoPortraitOrLandscape) method.
  • Call the PdfDocument.Print() method to print the PDF file.
  • C#
using Spire.Pdf;
using Spire.Pdf.Print;
using System.Drawing.Printing;

namespace PrintPdfOnCustomSizedPaper
{
    internal class Program
    {
        static void Main(string[] args)
        {            
            // Create a new instance of the PdfDocument class
            PdfDocument pdf = new PdfDocument();
            // Load the specified PDF file into the PdfDocument object
            pdf.LoadFromFile("Sample.pdf");

            //// Define an A3 paper size for printing
            //PaperSize paperSize = new PaperSize
            //{
            //    // Set paper size to A3
            //    RawKind = (int)PaperKind.A3
            //};

            // Define a custom paper size for printing
            PaperSize paperSize = new PaperSize
            {
                // Set the width of the paper
                Width = 283 * 100, //inch*100
                // Set the height of the paper
                Height = 826 * 100, //inch*100
                // Set paper size to custom
                RawKind = (int)PaperKind.Custom
            };

            // Assign the custom paper size to the print settings of the PdfDocument
            pdf.PrintSettings.PaperSize = paperSize;

            // Set paper margins as 0
            pdf.PrintSettings.SetPaperMargins(0, 0, 0, 0);

            // Set print settings to print the PDF at its actual size without scaling
            pdf.PrintSettings.SelectSinglePageLayout(PdfSinglePageScalingMode.ActualSize, false);
            // Execute the print command to print the loaded PDF document
            pdf.Print();
        }
    }
}

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.

Fonts play a crucial role in defining the visual appeal and readability of Word documents, influencing everything from professional reports to creative projects. Whether you're looking to refresh the design of your document by replacing outdated fonts or troubleshooting missing fonts that disrupt formatting, understanding how to retrieve and replace fonts in Microsoft Word is an essential skill.

In this article, you will learn how to get and replace fonts in a Word document using C# and 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

Get Fonts Used in a Word Document in C#

To extract font information from a Word document, you must traverse its sections and paragraphs, examining each child object within the paragraphs. If a child object is identified as a TextRange, you can retrieve the font details—such as the font name, size, and color—using the properties of the TextRange class.

The following are the steps to get fonts used in a Word document in C#:

  • Create a Document object.
  • Load a Word document using the Document.LoadFromFile() method.
  • Iterate through each section, paragraph, and child object.
  • For each child object, check if it is an instance of TextRange class.
  • If it is, retrieve the font name and size using the TextRange.CharacterFormat.FontName and TextRange.CharacterFormat.FontSize properties.
  • Write the font information in a text file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace RetrieveFonts
{
    // Customize a FontInfo class to help store font information
    class FontInfo
    {
        public string Name { get; set; }
        public float? Size { get; set; }

        public FontInfo()
        {
            Name = "";
            Size = null;
        }

        public override bool Equals(object obj)
        {
            if (this == obj) return true;
            if (!(obj is FontInfo other)) return false;
            return Name.Equals(other.Name) && Size.Equals(other.Size);
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(Name, Size);
        }
    }
    class Program
    {
        // Function to write string to a txt file
        static void WriteAllText(string filename, List<string> text)
        {
            try
            {
                using (StreamWriter writer = new StreamWriter(filename))
                {
                    foreach (var line in text)
                    {
                        writer.WriteLine(line);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        static void Main(string[] args)
        {
            List<FontInfo> fontInfos = new List<FontInfo>();
            List<string> fontInformations = new List<string>();

            // Create a Document instance
            Document document = new Document();

            // Load a Word document
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

            // Iterate through the sections
            foreach (Section section in document.Sections)
            {
                // Iterate through the paragraphs
                foreach (Paragraph paragraph in section.Body.Paragraphs)
                {
                    // Iterate through the child objects
                    foreach (DocumentObject obj in paragraph.ChildObjects)
                    {
                        if (obj is TextRange txtRange)
                        {
                            // Get the font name, size and text color
                            string fontName = txtRange.CharacterFormat.FontName;
                            float fontSize = txtRange.CharacterFormat.FontSize;
                            string textColor = txtRange.CharacterFormat.TextColor.ToString();

                            // Store the font information
                            FontInfo fontInfo = new FontInfo { Name = fontName, Size = fontSize };

                            if (!fontInfos.Contains(fontInfo))
                            {
                                fontInfos.Add(fontInfo);
                                string str = $"Font Name: {fontInfo.Name}, Size: {fontInfo.Size:F2}, Color: {textColor}";
                                fontInformations.Add(str);
                            }
                        }
                    }
                }
            }

            // Write font information to a txt file
            WriteAllText("GetFonts.txt", fontInformations);

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

Get fonts used in a Word document in C#

Replace a Specific Font in a Word Document in C#

After retrieving the font name from a specific TextRange, you can easily replace it with a new font using the TextRange.CharacterFormat.FontName property. Additionally, you can modify the font size and text color by accessing the corresponding properties in the TextRange class. This allows for comprehensive customization of the text formatting within the document.

The following are the steps to replace a specific font in a Word document in C#:

  • Create a Document object.
  • Load a Word document using the Document.LoadFromFile() method.
  • Iterate through each section and its paragraphs.
  • For each paragraph, check each child object to see if it is an instance of the TextRange class.
  • If it is a TextRange, retrieve the font name using the TextRange.CharacterFormat.FontName property.
  • Compare the font name to the specified font.
  • If they match, set a new font name using the TextRange.CharacterFormat.FontName property.
  • Save the modified document to a new Word file using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

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

            // Load a Word document
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

            // Iterate through the sections
            foreach (Section section in document.Sections)
            {
                // Iterate through the paragraphs
                foreach (Paragraph paragraph in section.Body.Paragraphs)
                {
                    // Iterate through the child objects
                    foreach (DocumentObject obj in paragraph.ChildObjects)
                    {
                        // Determine if a child object is a TextRange
                        if (obj is TextRange txtRange)
                        {
                            // Get the font name
                            string fontName = txtRange.CharacterFormat.FontName;

                            // Determine if the font name is Calibri
                            if (fontName.Equals("Calibri", StringComparison.OrdinalIgnoreCase))
                            {
                                // Replace the font with another font
                                txtRange.CharacterFormat.FontName = "Segoe Print";
                            }
                        }
                    }
                }
            }

            // Save the document to a different file
            document.SaveToFile("ReplaceFont.docx", FileFormat.Docx);

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

Replace fonts in a Word document in C#

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.

Slicers in Excel offer a user-friendly way to filter data in pivot tables and tables, making data analysis both visually appealing and interactive. Unlike traditional filter options, which can be less intuitive, slicers present filter choices as buttons. This allows users to quickly and easily refine their data views. Whether you are handling large datasets or building dynamic dashboards, slicers improve the user experience by providing immediate feedback on the selected criteria. This article explains how to add, update, and remove slicers 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 Slicers to Tables in Excel

Spire.XLS for .NET offers the Worksheet.Slicers.Add(IListObject table, string destCellName, int index) method to add a slicer to a table in an Excel worksheet. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Get the first worksheet using the Workbook.Worksheets[0] property.
  • Add data to the worksheet using the Worksheet.Range[].Value property.
  • Add a table to the worksheet using the Worksheet.IListObjects.Create() method.
  • Add a slicer to the table using the Worksheeet.Slicers.Add(IListObject table, string destCellName, int index) method.
  • Save the resulting file using the Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Core;

namespace AddSlicerToTable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an object of the Workbook class
            Workbook workbook = new Workbook();
            // Get the first worksheet
            Worksheet worksheet = workbook.Worksheets[0];

            // Add data to the worksheet
            worksheet.Range["A1"].Value = "Fruit";
            worksheet.Range["A2"].Value = "Grape";
            worksheet.Range["A3"].Value = "Blueberry";
            worksheet.Range["A4"].Value = "Kiwi";
            worksheet.Range["A5"].Value = "Cherry";
            worksheet.Range["A6"].Value = "Grape";
            worksheet.Range["A7"].Value = "Blueberry";
            worksheet.Range["A8"].Value = "Kiwi";
            worksheet.Range["A9"].Value = "Cherry";

            worksheet.Range["B1"].Value = "Year";
            worksheet.Range["B2"].Value2 = 2020;
            worksheet.Range["B3"].Value2 = 2020;
            worksheet.Range["B4"].Value2 = 2020;
            worksheet.Range["B5"].Value2 = 2020;
            worksheet.Range["B6"].Value2 = 2021;
            worksheet.Range["B7"].Value2 = 2021;
            worksheet.Range["B8"].Value2 = 2021;
            worksheet.Range["B9"].Value2 = 2021;

            worksheet.Range["C1"].Value = "Sales";
            worksheet.Range["C2"].Value2 = 50;
            worksheet.Range["C3"].Value2 = 60;
            worksheet.Range["C4"].Value2 = 70;
            worksheet.Range["C5"].Value2 = 80;
            worksheet.Range["C6"].Value2 = 90;
            worksheet.Range["C7"].Value2 = 100;
            worksheet.Range["C8"].Value2 = 110;
            worksheet.Range["C9"].Value2 = 120;            

            //Create a table from the specific data range
            IListObject table = worksheet.ListObjects.Create("Fruit Sales", worksheet.Range["A1:C9"]);

            // Add a slicer to cell "A11" to filter the data based on the first column of the table
            int index = worksheet.Slicers.Add(table, "A11", 0);
            // Set name and style for the slicer
            worksheet.Slicers[index].Name = "Fruit";
            worksheet.Slicers[index].StyleType = SlicerStyleType.SlicerStyleLight1;            

            //Save the resulting file
            workbook.SaveToFile("AddSlicerToTable.xlsx", ExcelVersion.Version2013);
            workbook.Dispose();
        }
    }
}

Add Slicers to Tables in Excel

Add Slicers to Pivot Tables in Excel

In addition to adding slicers to tables, Spire.XLS for .NET also enables you to add slicers to pivot tables in Excel using the Worksheet.Slicers.Add(IPivotTable pivot, string destCellName, int baseFieldIndex) method. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Get the first worksheet using the Workbook.Worksheets[0] property.
  • Add data to the worksheet using the Worksheet.Range[].Value property.
  • Create a pivot cache from the data using the Workbook.PivotCaches.Add() method.
  • Create a pivot table from the pivot cache using the Worksheet.PivotTables.Add() method.
  • Drag the pivot fields to the row, column, and data areas. Then calculate the data in the pivot table.
  • Add a slicer to the pivot table using the Worksheet.Slicers.Add(IPivotTable pivot, string destCellName, int baseFieldIndex) method.
  • Set the properties, such as the name, width, height, style, and cross filter type for the slicer.
  • Calculate the data in the pivot table.
  • Save the resulting file using the Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Core;

namespace AddSlicerToPivotTable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an object of the Workbook class
            Workbook workbook = new Workbook();
            // Get the first worksheet
            Worksheet worksheet = workbook.Worksheets[0];

            // Add data to the worksheet
            worksheet.Range["A1"].Value = "Fruit";
            worksheet.Range["A2"].Value = "Grape";
            worksheet.Range["A3"].Value = "Blueberry";
            worksheet.Range["A4"].Value = "Kiwi";
            worksheet.Range["A5"].Value = "Cherry";
            worksheet.Range["A6"].Value = "Grape";
            worksheet.Range["A7"].Value = "Blueberry";
            worksheet.Range["A8"].Value = "Kiwi";
            worksheet.Range["A9"].Value = "Cherry";

            worksheet.Range["B1"].Value = "Year";
            worksheet.Range["B2"].Value2 = 2020;
            worksheet.Range["B3"].Value2 = 2020;
            worksheet.Range["B4"].Value2 = 2020;
            worksheet.Range["B5"].Value2 = 2020;
            worksheet.Range["B6"].Value2 = 2021;
            worksheet.Range["B7"].Value2 = 2021;
            worksheet.Range["B8"].Value2 = 2021;
            worksheet.Range["B9"].Value2 = 2021;

            worksheet.Range["C1"].Value = "Sales";
            worksheet.Range["C2"].Value2 = 50;
            worksheet.Range["C3"].Value2 = 60;
            worksheet.Range["C4"].Value2 = 70;
            worksheet.Range["C5"].Value2 = 80;
            worksheet.Range["C6"].Value2 = 90;
            worksheet.Range["C7"].Value2 = 100;
            worksheet.Range["C8"].Value2 = 110;
            worksheet.Range["C9"].Value2 = 120;

            // Create a pivot cache from the specific data range
            CellRange dataRange = worksheet.Range["A1:C9"];
            PivotCache cache = workbook.PivotCaches.Add(dataRange);

            // Create a pivot table from the pivot cache
            PivotTable pt = worksheet.PivotTables.Add("Fruit Sales", worksheet.Range["A12"], cache);


            // Drag the fields to the row and column areas
            PivotField pf = pt.PivotFields["Fruit"] as PivotField;
            pf.Axis = AxisTypes.Row;
            PivotField pf2 = pt.PivotFields["Year"] as PivotField;
            pf2.Axis = AxisTypes.Column;

            // Drag the field to the data area
            pt.DataFields.Add(pt.PivotFields["Sales"], "Sum of Sales", SubtotalTypes.Sum);

            // Set style for the pivot table
            pt.BuiltInStyle = PivotBuiltInStyles.PivotStyleMedium10;

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

            // Add a Slicer to the pivot table
            int index_1 = worksheet.Slicers.Add(pt, "F12", 0);

            // Set the name, width, height, and style for the slicer
            worksheet.Slicers[index_1].Name = "Fruit";
            worksheet.Slicers[index_1].Width = 100;
            worksheet.Slicers[index_1].Height = 120;
            worksheet.Slicers[index_1].StyleType = SlicerStyleType.SlicerStyleLight2;

            // Set the cross filter type for the slicer
            XlsSlicerCache slicerCache = worksheet.Slicers[index_1].SlicerCache;
            slicerCache.CrossFilterType = SlicerCacheCrossFilterType.ShowItemsWithNoData;       

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

            // Save the resulting file
            workbook.SaveToFile("AddSlicerToPivotTable.xlsx", ExcelVersion.Version2013);
            workbook.Dispose();
        }
    }
}

Add Slicers to Pivot Tables in Excel

Update Slicers in Excel

You can update the properties of a slicer, such as its style, name, caption, and more using the corresponding properties of the XlsSlicer class. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet by its index using the Workbook.Worksheets[index] property.
  • Get a specific slicer from the worksheet by its index using the Worksheet.Slicers[index] property.
  • Update the properties of the slicer, such as its style, name, caption, and cross filter type using the properties of the XlsSlicer class.
  • Save the resulting file using the Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Core;

namespace UpdateSlicer
{
    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("AddSlicerToTable.xlsx");

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

            // Get the first slicer in the worksheet
            XlsSlicer slicer = worksheet.Slicers[0];

            // Change the style, name, and caption for the slicer
            slicer.StyleType = SlicerStyleType.SlicerStyleDark4;
            slicer.Name = "Slicer";
            slicer.Caption = "Slicer";

            // Change the cross filter type for the slicer
            slicer.SlicerCache.CrossFilterType = SlicerCacheCrossFilterType.ShowItemsWithDataAtTop;
            
            // Deselect an item in the slicer
            XlsSlicerCacheItemCollection slicerCacheItems = slicer.SlicerCache.SlicerCacheItems;
            XlsSlicerCacheItem xlsSlicerCacheItem = slicerCacheItems[0];
            xlsSlicerCacheItem.Selected = false;                        

            // Save the resulting file
            workbook.SaveToFile("UpdateSlicer.xlsx", ExcelVersion.Version2013);
            workbook.Dispose();
        }
    }
}

Update Slicers in Excel

Remove Slicers from Excel

You can remove a specific slicer from an Excel worksheet using the Worksheet.Slicers.RemoveAt() method, or remove all slicers at once using the Worksheet.Slicers.Clear() method. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet by its index using the Workbook.Worksheets[index] property.
  • Remove a specific slicer from the worksheet by its index using the Worksheet.Slicers.RemoveAt(index) method. Or remove all slicers from the worksheet using the Worksheet.Slicers.Clear() method.
  • Save the resulting file using the Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Core;

namespace RemoveSlicer
{
    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("AddSlicerToTable.xlsx");

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

            // Remove the first slicer by index
            worksheet.Slicers.RemoveAt(0);

            //// Or remove all slicers
            //worksheet.Slicers.Clear();

            // Save the resulting file
            workbook.SaveToFile("RemoveSlicer.xlsx", ExcelVersion.Version2013);
            workbook.Dispose();
        }
    }
}

Remove Slicers 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.

C#: Convert PowerPoint to Markdown

2025-02-25 01:10:16 Written by Koohji

PowerPoint presentations are widely used tools for visual communication, enabling users to effectively present information in an organized and visually engaging manner. They are ideal for business meetings, educational purposes, and project presentations. However, in some cases, converting PowerPoint presentations into a lightweight, text-based format such as Markdown is more practical.

Markdown is a popular markup language that is widely supported across documentation tools, version control systems, and static site generators. It offers a simple way to format text that is easier to read and write. By converting PowerPoint presentations to Markdown, users can integrate their content into text-based workflows more efficiently. This is especially helpful when collaborating on documents, tracking changes, or publishing content online.

In this article, we will walk you through the steps of converting PowerPoint presentations to Markdown format using C# and the Spire.Presentation for .NET library.

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

Convert a PowerPoint Presentation to Markdown

Spire.Presentation for .NET provides the Presentation.SaveToFile(string, FileFormat) method, allowing you to convert PowerPoint presentations into various file formats, including PDF, HTML, and Markdown. Below are the steps to convert a PowerPoint presentation to Markdown using Spire.Presentation for .NET:

  • Initialize an instance of the Presentation class.
  • Load a PowerPoint presentation using Presentation.LoadFromFile(string) method.
  • Save the PowerPoint presentation to Markdown format using Presentation.SaveToFile(string, FileFormat) method.
  • C#
using Spire.Presentation;

namespace PPTToMarkdown
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Presentation class
            Presentation ppt = new Presentation();
            //Load a PowerPoint presentation
            ppt.LoadFromFile(@"E:\Program Files\Sample.pptx");

            //Specify the file path for the output Markdown file 
            string result = @"E:\Program Files\PowerPointToMarkdown.md";

            //Save the PowerPoint presentation to Markdown format
            ppt.SaveToFile(result, FileFormat.Markdown);
        }
    }
}

Convert a PowerPoint Presentation to Markdown

Convert a Specific PowerPoint Slide to Markdown

In some cases, you may need to convert a specific slide instead of the whole presentation to Markdown. Spire.Presentation offers the ISlide.SaveToFile(string, FileFormat) method to convert a PowerPoint slide to Markdown. The following are the detailed steps:

  • Initialize an instance of the Presentation class.
  • Load a PowerPoint presentation using Presentation.LoadFromFile(string) method.
  • Get a specific slide in the PowerPoint presentation by its index through Presentation.Slides[int] property.
  • Save the PowerPoint slide to Markdown format using ISlide.SaveToFile(string, FileFormat) method.
  • C#
using Spire.Presentation;

namespace SlideToMarkdown
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Presentation class
            Presentation ppt = new Presentation();
            //Load a PowerPoint presentation
            ppt.LoadFromFile(@"E:\Program Files\Sample.pptx");

            //Get the second slide
            ISlide slide = ppt.Slides[1];

            //Specify the file path for the output Markdown file
            string result = @"E:\Program Files\SlideToMarkdown.md";

            //Save the slide to a Markdown file
            slide.SaveToFile(result, FileFormat.Markdown);
            ppt.Dispose();
        }
    }
}

Convert a Specific PowerPoint Slide to Markdown

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 Word documents, hyperlinks can be added to images and shapes to link to external websites, files, or specific sections within the document. However, over time, the destination URLs or file paths may change due to updates in external resources or reorganization of the document. When this happens, it’s important to update the hyperlinks to ensure they continue to point to the correct locations. For example, if a website's URL changes, an image is moved to a new folder or a linked shape needs to connect to a different page, updating the hyperlinks is crucial to keep the document functional and user-friendly.

In this article, we will introduce how to programmatically update hyperlinks for images and shapes in Word documents 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

Update Hyperlinks for Images in Word in C#

Spire.Doc for .NET offers the DocPicture.HasHyperlink property which allows you to identify if an image contains a hyperlink. Once identified, you can use the DocPicture.HRef property to seamlessly update or modify the hyperlink as needed. The detailed steps are as follows.

  • Create an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile() method.
  • Iterate through all sections in the document, all paragraphs in each section, and all objects in each paragraph.
  • Check if the object is a DocPicture.
  • Check if the DocPicture object has a hyperlink using the DocPicture.HasHyperlink property.
  • Modify the hyperlink of the DocPicture object using the DocPicture.HRef property.
  • Save the modified document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace UpdateHyperlinkForImage
{
    internal class Program
    {
        static void Main(string[] args) 
        {       
            // Create a Document instance
            Document doc = new Document();
            // Load a Word document
            doc.LoadFromFile("Sample1.docx");

            // Iterate through all sections in the document
            foreach (Section section in doc.Sections)
            {
                // Iterate through all paragraphs in the section
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    // Iterate through all objects in the paragraph
                    foreach (DocumentObject documentObject in paragraph.ChildObjects)
                    {
                        // Check if the object is a DocPicture (image)
                        if (documentObject is DocPicture)
                        {
                            DocPicture pic = documentObject as DocPicture;
                            // Check if the DocPicture object has a hyperlink
                            if (pic.HasHyperlink)
                            {
                                // Update the hyperlink (if you want to remove the hyperlink, set the value to null) 
                                pic.HRef = "https://www.e-iceblue.com/";

                            }
                        }
                    }
                }
            }

            // Save the modified document
            doc.SaveToFile("UpdateImageHyperlink.docx", FileFormat.Docx2016);
            doc.Close();
        }
    }
}

Update Hyperlinks for Images in Word in C#

Update Hyperlinks for Shapes in Word in C#

Similarly, you can check if a shape has a hyperlink using the ShapeObject.HasHyperlink property, and update or modify the hyperlink with the ShapeObject.HRef property. The detailed steps are as follows.

  • Create an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile() method.
  • Iterate through all sections in the document, all paragraphs in each section, and all objects in each paragraph.
  • Check if the object is a ShapeObject.
  • Check if the ShapeObject object has a hyperlink using the ShapeObject.HasHyperlink property.
  • Modify the hyperlink of the ShapeObject object using the ShapeObject.HRef property.
  • Save the modified document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace UpdateHyperlinkForShape
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Document instance
            Document doc = new Document();
            // Load a Word document
            doc.LoadFromFile("Sample2.docx");

            // Iterate through all sections in the document
            foreach (Section section in doc.Sections)
            {
                // Iterate through all paragraphs in the section
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    // Iterate through all objects in the paragraph
                    foreach (DocumentObject documentObject in paragraph.ChildObjects)
                    {
                        // Check if the object is a ShapeObject
                        if (documentObject is ShapeObject)
                        {
                            ShapeObject shape = documentObject as ShapeObject;
                            // Check if the shape has a hyperlink
                            if (shape.HasHyperlink)
                            {
                                // Update the hyperlink (if you want to remove the hyperlink, set the value to null) 
                                shape.HRef = "https://www.e-iceblue.com/";
                            }
                        }
                    }
                }
            }

            // Save the modified document
            doc.SaveToFile("UpdateShapeHyperlink.docx", FileFormat.Docx2016);
            doc.Close();
        }
    }
}

Update Hyperlinks for Shapes in Word in C#

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 working with Excel in C#, copying rows, columns, and cells can feel like a simple task, but it often comes with a catch—how to keep the formatting intact. Whether you’re organizing data for a report, creating a presentation, or just trying to keep your spreadsheet looking sharp, maintaining the original look is crucial. In this article, we will demonstrate the methods to copy rows, columns, and cells in Excel while preserving the original formatting 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 DLLs files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

Copy Rows in Excel with Formatting in C#

Copying rows in Excel while preserving their formatting can be efficiently achieved using the Worksheet.CopyRow(CellRange sourceRow, Worksheet destSheet, int destRowIndex, CopyRangeOptions copyOptions) method. This method enables you to duplicate rows either within the same worksheet or across different worksheets with precision. Additionally, you can control the copying behavior, such as copying all formatting, conditional formatting, data validations, styles, or even just the formula values, through the CopyRangeOptions parameter.

The following steps explain how to copy rows across different worksheets with formatting using Spire.XLS for .NET.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Get the source worksheet and the destination worksheet using the Workbook.Worksheets[index] property.
  • Get the desired row that you want to copy using the Worksheet.Rows[index] property.
  • Copy the row and its formatting from the source worksheet to the destination worksheet using the Worksheet.CopyRow(CellRange sourceRow, Worksheet destSheet, int destRowIndex, CopyRangeOptions copyOptions) method.
  • Copy the column widths of cells in the source row to the corresponding cells in the destination row.
  • Save the workbook to a file using the Workbook.SaveToFile() method.
  • C#
using Spire.Xls;

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

            // Get the source worksheet
            Worksheet sheet1 = workbook.Worksheets[0];

            // Get the destination worksheet
            Worksheet sheet2 = workbook.Worksheets[1];

            // Get the desired row that you want to copy
            CellRange row = sheet1.Rows[0];

            // Copy the row from the source worksheet to the first row of the destination worksheet
            sheet1.CopyRow(row, sheet2, 1, CopyRangeOptions.All);

            int columns = sheet1.Columns.Length;

            // Copy the column widths of the cells in the source row to the corresponding cells in the destination row
            for (int i = 0; i < columns; i++)
            {
                double columnWidth = row.Columns[i].ColumnWidth;
                sheet2.Rows[0].Columns[i].ColumnWidth = columnWidth;
            }

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

Copy Rows in Excel with Formatting in C#

Copy Columns in Excel with Formatting in C#

Similarly, copying columns in Excel with formatting can be accomplished using the Worksheet.CopyColumn(CellRange sourceColumn, Worksheet destSheet, int destColIndex, CopyRangeOptions copyOptions) method. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Get the source worksheet and the destination worksheet using the Workbook.Worksheets[index] property.
  • Get the desired column that you want to copy using the Worksheet.Columns[index] property.
  • Copy the column and its formatting from the source worksheet to the destination worksheet using the Worksheet.CopyColumn(CellRange sourceColumn, Worksheet destSheet, int destColIndex, CopyRangeOptions copyOptions) method.
  • Copy the row heights of cells in the source column to the corresponding cells in the destination column.
  • Save the workbook to a file using the Workbook.SaveToFile() method.
  • C#
using Spire.Xls;

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

            // Get the source worksheet
            Worksheet sheet1 = workbook.Worksheets[0];

            // Get the destination worksheet
            Worksheet sheet2 = workbook.Worksheets[1];

            // Get the desired column that you want to copy
            CellRange column = sheet1.Columns[0];

            // Copy the column from the source worksheet to the first column of the destination worksheet
            sheet1.CopyColumn(column, sheet2, 1, CopyRangeOptions.All);

            int rows = column.Rows.Length;

            // Copy the row heights of cells in the source column to the corresponding cells in the destination column
            for (int i = 0; i < rows; i++)
            {
                double rowHeight = column.Rows[i].RowHeight;
                sheet2.Columns[0].Rows[i].RowHeight = rowHeight;
            }

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

Copy Columns in Excel with Formatting in C#

Copy Cells in Excel with Formatting in C#

In addition to copying rows and columns in Excel with formatting, Spire.XLS for .NET also allows copying cell ranges with formatting using the CellRange.Copy(CellRange destRange, CopyRangeOptions copyOptions) method. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Get the source worksheet and the destination worksheet using the Workbook.Worksheets[index] property.
  • Get the source cell range and the destination cell range using the Worksheet.Range[] property.
  • Copy the source cell range and its formatting from the source worksheet to the destination cell range in the destination worksheet using the CellRange.Copy(CellRange destRange, CopyRangeOptions copyOptions) method.
  • Copy the row heights and column widths of the source cell range to the destination cell range.
  • Save the workbook to a file using the Workbook.SaveToFile() method.
  • C#
using Spire.Xls;

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

            // Get the source worksheet
            Worksheet sheet1 = workbook.Worksheets[0];
            // Get the destination worksheet
            Worksheet sheet2 = workbook.Worksheets[1];

            // Get the source cell range
            CellRange range1 = sheet1.Range["A1:E7"];
            // Get the destination cell range
            CellRange range2 = sheet2.Range["A1:E7"];

            // Copy the source cell range from the source worksheet to the destination cell range in the destination worksheet
            range1.Copy(range2, CopyRangeOptions.All);

            // Copy the row heights and column widths of the source cell range to the destination cell range
            for (int i = 0; i < range1.Rows.Length; i++)
            {
                CellRange row = range1.Rows[i];
                for (int j = 0; j < row.Columns.Length; j++)
                {
                    CellRange column = row.Columns[j];
                    range2.Rows[i].Columns[j].ColumnWidth = column.ColumnWidth;
                    range2.Rows[i].RowHeight = row.RowHeight;
                }
            }

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

Copy Cells in Excel with Formatting in C#

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 XML to Excel and PDF

2024-12-11 06:54:49 Written by Koohji

XML is often used for data interchange between different systems, while Excel is a widely recognized format for data analysis and reporting. By converting XML data to Excel, you can leverage Excel's powerful features to analyze and visualize the data more effectively. This conversion process is essential in various industries, including finance, healthcare, and e-commerce.

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

Understanding XML Structure: Elements, Attributes, and Data

Before converting XML to Excel, it's crucial to understand the structure of XML files. XML is a markup language that uses tags to define elements, attributes, and data. Here’s a breakdown of these components:

  • Elements: These are the building blocks of XML. They are defined by start and end tags and can contain data or other elements.
<person>
    <name>John Doe</name>
    <age>30</age>
</person>
  • Attributes: These provide additional information about elements. They are specified within the start tag of an element.
<person id="1">
    <name>John Doe</name>
    <age>30</age>
</person>
  • Data: This is the content enclosed within the start and end tags of an element.

Understanding these components will help you map XML data to Excel effectively.

Convert XML to Excel in C#

In .NET, you can use the System.Xml.Linq namespace, which provides classes for working with XML files. The primary class used is XDocument, which allows you to load, navigate, and manipulate XML documents effortlessly.

Here's an example:

  • C#
using System;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        // Load the XML file
        XDocument doc = XDocument.Load("data.xml");
        XElement root = doc.Root;

        // Iterate through elements
        foreach (XElement person in root.Elements("person"))
        {
            string name = person.Element("name")?.Value;
            string age = person.Element("age")?.Value;

            // Output the name and age
            Console.WriteLine($"Name: {name}, Age: {age}");
        }
    }
}

After parsing the XML data, the next step is to map it to an Excel worksheet. You can use Spire.XLS for .NET to create a new workbook, input data into specific cells, and apply various styles and formatting options. These include auto-fitting column widths, adjusting text alignment, and making the header bold.

To convert XML to Excel in C#, follow these steps:

  • Utilize the System.Xml.Linq library to extract data from the XML file.
  • Create a Workbook object.
  • Add a worksheet using the Workbook.Worksheets.Add() method.
  • Write the extracted data into the worksheet cells using the Worksheet.SetValue() method.
  • Apply styles and formatting to enhance the appearance of the worksheet.
  • Save the workbook to an Excel file using the Workbook.SaveToFile() method.

The following code demonstrates an efficient and advanced method for reading data from XML and importing it into an Excel file.

  • C#
using Spire.Xls;
using System.Xml.Linq;

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

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

            // Remove default worksheets
            workbook.Worksheets.Clear();

            // Add a worksheet and name it
            Worksheet worksheet = workbook.Worksheets.Add("Books");

            // Load an XML file
            XDocument xmlDoc = XDocument.Load(@"C:\Users\Administrator\Desktop\Books.xml");
            XElement xmlRoot = xmlDoc.Root;

            // Get the first "book" element
            XElement firstBook = xmlRoot.Element("book");

            // Extract header information and convert it into a list
            var headers = firstBook.Elements().ToList();

            // Write header to Excel
            for (int colIndex = 0; colIndex < headers.Count; colIndex++)
            {
                string headerText = headers[colIndex].Name.LocalName;
                worksheet.SetValue(1, colIndex + 1, headerText);
            }

            // Write other data to Excel by iterating over each book element and each data node within it
            int rowIndex = 2;
            foreach (XElement book in xmlRoot.Elements("book"))
            {
                var dataNodes = book.Elements().ToList();
                for (int colIndex = 0; colIndex < dataNodes.Count; colIndex++)
                {
                    string value = dataNodes[colIndex].Value;
                    worksheet.SetValue(rowIndex, colIndex + 1, value);
                }
                rowIndex++;
            }

            // Set column width
            worksheet.AllocatedRange.AutoFitColumns();

            // Set alignment
            worksheet.AllocatedRange.HorizontalAlignment = HorizontalAlignType.Left;

            // Set font style
            worksheet.Range["A1:F1"].Style.Font.IsBold = true;

            // Save the workbook to an Excel file
            workbook.SaveToFile("output/XmlToExcel.xlsx");

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

The result Excel file containing the data extracted from an XML file

Convert XML to PDF in C#

The previous example effectively imports data from an XML file into an Excel worksheet. This worksheet can subsequently be converted to a PDF file using the Worksheet.SaveToPdf() method. To ensure a well-structured PDF, you may want to adjust page layout settings, such as margins and the preservation of gridlines, during the conversion process.

Here are the steps to convert XML to PDF using C#:

  • Use the System.Xml.Linq library to retrieve data from the XML file.
  • Create a Workbook object.
  • Add a worksheet with the Workbook.Worksheets.Add() method.
  • Populate the worksheet cells with data extracted from the XML file using the Worksheet.SetValue() method.
  • Apply styles and formatting to improve the worksheet's appearance.
  • Configure page settings using properties from the PageSetup object, accessible via Worksheet.PageSetup.
  • Save the worksheet as a PDF file using the Worksheet.SaveToPdf() method.

The following code snippet illustrates how to import data from XML into a worksheet and then save that worksheet as a PDF file.

  • C#
using Spire.Xls;
using Spire.Xls.Core;
using System.Xml.Linq;

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

            // Remove default worksheets
            workbook.Worksheets.Clear();

            // Add a worksheet and name it
            Worksheet worksheet = workbook.Worksheets.Add("Books");

            // Load an XML file
            XDocument xmlDoc = XDocument.Load(@"C:\Users\Administrator\Desktop\Books.xml");
            XElement xmlRoot = xmlDoc.Root;

            // Get the first "book" element
            XElement firstBook = xmlRoot.Element("book");

            // Extract header information and convert it into a list
            var headers = firstBook.Elements().ToList();

            // Write header to Excel
            for (int colIndex = 0; colIndex < headers.Count; colIndex++)
            {
                string headerText = headers[colIndex].Name.LocalName;
                worksheet.SetValue(1, colIndex + 1, headerText);
            }

            // Write other data to Excel by iterating over each book element and each data node within it
            int rowIndex = 2;
            foreach (XElement book in xmlRoot.Elements("book"))
            {
                var dataNodes = book.Elements().ToList();
                for (int colIndex = 0; colIndex < dataNodes.Count; colIndex++)
                {
                    string value = dataNodes[colIndex].Value;
                    worksheet.SetValue(rowIndex, colIndex + 1, value);
                }
                rowIndex++;
            }

            // Set column width
            worksheet.AllocatedRange.AutoFitColumns();

            // Set alignment
            worksheet.AllocatedRange.HorizontalAlignment = HorizontalAlignType.Left;

            // Set font style
            worksheet.Range["A1:F1"].Style.Font.IsBold = true;

            // Fit worksheet on one page
            workbook.ConverterSetting.SheetFitToPage = true;

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

            // Set page margins
            pageSetup.TopMargin = 0.3;
            pageSetup.BottomMargin = 0.3;
            pageSetup.LeftMargin = 0.3;
            pageSetup.RightMargin = 0.3;

            // Preserve gridlines 
            pageSetup.IsPrintGridlines = true;

            // Save the worksheet to a PDF file
            worksheet.SaveToPdf("output/XmlToPdf.pdf");

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

The result PDF file containing the data extracted from an XML file

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.

Efficiently integrating data between systems is vital for boosting productivity and informed decision-making. A common task in this area is transferring data between Excel and databases. Importing Excel files into a database enables businesses to utilize powerful features like efficient queries, transaction support, and concurrency control, which Excel lacks. Conversely, exporting database data to Excel allows for detailed analysis, reporting, and sharing in a widely used and familiar format. In this article, we will explore how to import Excel data into databases and export data from databases into Excel files using Spire.XLS for .NET with C#.

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

Import Excel Data into Databases with C#

With the help of Spire.XLS for .NET, we can use the Workbook.LoadFromFile() method to load an Excel file and then access the cell data using CellRange.Value property. Subsequently, we can utilize the relevant database operation modules, such as the System.Data.SQLite module for SQLite, to write the data into the database. This approach enables the seamless import of data from an Excel file into a database.

The following steps and code use SQLite as an example to demonstrate how to import Excel data into a database using C#:

  • Define the path for the Excel file and the output database.
  • Create an instance of Workbook class and load an Excel file using Workbook.LoadFromFile() method.
  • Create a new SQLite database or connect to an existing database.
  • Iterate through each worksheet in the workbook and create a table in the database for each worksheet.
  • Get the cells in the first row through Worksheet.Rows.CellList property.
  • Iterate through the cells to get their values through CellRange.Value property, and use these values as the column names of the database table.
  • Iterate through the rest rows and cells, and insert them as values into the database.
  • Close the database connection and release resources.
  • C#
using System.Data.SQLite;
using Spire.Xls;

namespace ExcelToSQLite
{
    class Program
    {
        static void Main(string[] args)
        {
            // Excel file path
            string excelFilePath = "Sample.xlsx";

            // SQLite database path
            string sqliteFilePath = "output/Database.db";

            // Open the Excel file
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(excelFilePath);

            // If the database file doesn't exist, create it
            if (!File.Exists(sqliteFilePath))
            {
                SQLiteConnection.CreateFile(sqliteFilePath);
                Console.WriteLine("A new SQLite database file has been created: output.db");
            }

            // Create SQLite connection
            using (SQLiteConnection connection = new SQLiteConnection($"Data Source={sqliteFilePath};Version=3;"))
            {
                connection.Open();

                // Iterate through each worksheet
                foreach (Worksheet sheet in workbook.Worksheets)
                {
                    string tableName = sheet.Name;

                    // Get the first row as column names
                    var columns = sheet.Rows[0].CellList;
                    string createTableQuery = $"CREATE TABLE IF NOT EXISTS [{tableName}] (";

                    foreach (var column in columns)
                    {
                        createTableQuery += $"[{column.Value}] TEXT,";
                    }
                    createTableQuery = createTableQuery.TrimEnd(',') + ");";

                    // Create table
                    using (SQLiteCommand createTableCommand = new SQLiteCommand(createTableQuery, connection))
                    {
                        createTableCommand.ExecuteNonQuery();
                    }

                    // Insert data
                    for (int i = 1; i < sheet.Rows.Length; i++) // Skip the first row
                    {
                        var row = sheet.Rows[i];
                        string insertQuery = $"INSERT INTO [{tableName}] VALUES (";
                        foreach (var cell in row.CellList)
                        {
                            insertQuery += $"'{cell.Value?.Replace("'", "''")}',"; // Prevent SQL injection
                        }
                        insertQuery = insertQuery.TrimEnd(',') + ");";

                        using (SQLiteCommand insertCommand = new SQLiteCommand(insertQuery, connection))
                        {
                            insertCommand.ExecuteNonQuery();
                        }
                    }
                }

                connection.Close();
                workbook.Dispose();
            }

            Console.WriteLine("Excel data has been successfully written to the new SQLite database!");
        }
    }
}

Result of Transferring Data from Excel to Database with C#

Export Data from Databases into Excel Files with C#

Similarly, we can use the database handling module to read data from the database. Then, by creating a Workbook object, we can generate an Excel file and use the CellRange.Value property to write the data into the Excel file. This allows us to export data from the database to an Excel file.

The following steps and code use an SQLite database as an example to demonstrate how to export data from a database to an Excel file.

  • Define the path for the database and the output Excel file.
  • Create a Workbook instance to create a new Excel workbook and clear the default worksheets using Workbook.Worksheets.Clear() method.
  • Connect to the database and get all the table names.
  • Create a worksheet for each table with the table names as sheet names using Workbook.Worksheets.Add() method.
  • Get the column names in the tables and write them to the first row of the worksheet through Worksheet.Range[].Value property.
  • Get the data in the table and write it to the worksheet sequentially through Worksheet.Range[].Value property.
  • Format the worksheet through CellRange.Style property if needed.
  • Close the database connection and save the workbook using Workbook.SaveToFile() method.
  • C#
using System.Data;
using System.Data.SQLite;
using Spire.Xls;

namespace SQLiteToExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            // SQLite database path
            string sqliteFilePath = "Sample.db";

            // Excel file path
            string excelFilePath = "output/DatabaseToExcel.xlsx";

            // Create a new Workbook instance
            Workbook workbook = new Workbook();
            // Clear the default worksheet
            workbook.Worksheets.Clear();

            // Create SQLite connection
            using (SQLiteConnection connection = new SQLiteConnection($"Data Source={sqliteFilePath};Version=3;"))
            {
                connection.Open();

                // Get all table names
                DataTable tables = connection.GetSchema("Tables");

                // Iterate through each table
                foreach (DataRow tableRow in tables.Rows)
                {
                    string tableName = tableRow["TABLE_NAME"].ToString();

                    // Create a new worksheet
                    Worksheet sheet = workbook.Worksheets.Add(tableName);

                    // Get table data
                    string selectQuery = $"SELECT * FROM [{tableName}]";
                    using (SQLiteCommand command = new SQLiteCommand(selectQuery, connection))
                    {
                        using (SQLiteDataReader reader = command.ExecuteReader())
                        {
                            // Get column names and write them in the first row
                            for (int col = 0; col < reader.FieldCount; col++)
                            {
                                sheet.Range[1, col + 1].Value = reader.GetName(col);
                            }
                            // Set the font style for the header
                            sheet.Rows[0].Style.Font.IsBold = true;
                            sheet.Rows[0].Style.Font.Size = 12;

                            // Write data rows
                            int rowIndex = 2;
                            while (reader.Read())
                            {
                                for (int col = 0; col < reader.FieldCount; col++)
                                {
                                    sheet.Range[rowIndex, col + 1].Value = reader.GetValue(col).ToString();
                                    // Auto-fit column width
                                    sheet.AutoFitColumn(col + 1);
                                }
                                // Set the font style for data rows
                                sheet.Rows[rowIndex - 1].Style.Font.Size = 11;
                                rowIndex++;
                            }
                        }
                    }
                }

                connection.Close();
            }

            // Save the Excel file
            workbook.SaveToFile(excelFilePath);
            workbook.Dispose();
            Console.WriteLine("Data has been successfully exported to the Excel file!");
        }
    }
}

Result of Converting Database to Excel with C#

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#: Group Data in Pivot Table in Excel

2024-11-28 01:07:32 Written by Koohji

Grouping data in a pivot table simplifies data analysis by consolidating similar items into meaningful categories. For example, you can group dates into months or years to see trends over time, or group numbers into ranges like price levels or age groups for easier comparison and analysis. In this article, we will demonstrate how to group data in Excel pivot tables based on dates and numbers 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

Group Pivot Table Data in Excel Based on Dates in C#

The IPivotField.CreateGroup(DateTime start, DateTime end, PivotGroupByTypes[] groupByArray) method in Spire.XLS for .NET allows developers to group data in Excel pivot tables based on date and time. It requires three parameters: a start date time, an end date time, and an array of grouping categories specified by the PivotGroupByTypes enum.

The list below shows the categories that can be used when grouping by date and time:

  • Days
  • Months
  • Quarters
  • Years
  • Seconds
  • Minutes
  • Hours

The steps below demonstrate how to group the data in a pivot table by date and time using Spire.XLS for .NET:

  • Create an instance of the Workbook class.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Access the worksheet that contains the pivot table using the Workbook.Worksheets[] property.
  • Get the pivot table using the Worksheet.PivotTables[] property.
  • Get the specific pivot field that you want to group using the XlsPivotTable.PivotFields[] property.
  • Create two instances of the DateTime class to specify the start date time and end date time.
  • Create a PivotGroupByTypes array to specify the grouping categories, such as days and months.
  • Group the data of the selected pivot field based on the specified grouping categories using the IPivotField.CreateGroup(DateTime start, DateTime end, PivotGroupByTypes[] groupByArray) method.
  • Refresh the pivot table using the XlsPivotTable.IsRefreshOnLoad property.
  • Save the result file using the Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Core.Spreadsheet.PivotTables;
using System;

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

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

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

            // Get the "Date" pivot field 
            PivotField ptField = pt.PivotFields["Date"] as PivotField;
            // Specify the start date time and end date time
            DateTime start = new DateTime(2024, 1, 1);
            DateTime end = new DateTime(2024, 10, 14);

            // Create a PivotGroupByTypes array to specify the grouping categories, such as days and months
            PivotGroupByTypes[] groupByTypes = new PivotGroupByTypes[]
            {
                PivotGroupByTypes.Days,
                PivotGroupByTypes.Months
            };

            // Group the data in the pivot field based on the specified grouping categories
            ptField.CreateGroup(start, end, groupByTypes);

            // Refresh the pivot table
            pt.Cache.IsRefreshOnLoad = true;

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

Group Pivot Table Data in Excel Based on Dates in C#

Group Pivot Table Data in Excel Based on Numbers in C#

In addition to grouping based on date and time, Spire.XLS for .NET also enables developers to group pivot table data based on numeric values using another overload of the CreateGroup() method: CreateGroup(double startValue, double endValue, double intervalValue). The detailed steps are as follows.

  • Create an instance of the Workbook class.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Access the worksheet that contains the pivot table using the Workbook.Worksheets[] property.
  • Get the pivot table using the Worksheet.PivotTables[] property.
  • Get the specific pivot field that you want to group using the XlsPivotTable.PivotFields[] property.
  • Group the data in the selected pivot field based on numeric values using the IPivotField.CreateGroup(double startValue, double endValue, double intervalValue) method.
  • Calculate the pivot table data using the XlsPivotTable.CalculateData() method.
  • Refresh the pivot table using the XlsPivotTable.IsRefreshOnLoad property.
  • Save the result file using the Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Core.Spreadsheet.PivotTables;

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

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

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

            // Group data of the "SalesAmount" pivot field based on based on numeric values
            PivotField ptField = pt.PivotFields["SalesAmount"] as PivotField;
            ptField.CreateGroup(1500, 4500, 200);

            // Calculate the pivot table data
            pt.CalculateData();
            // Refresh the pivot table
            pt.Cache.IsRefreshOnLoad = true;

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

Group Pivot Table Data in Excel Based on Numbers in C#

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 4 of 95
page 4