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.

C#: Create Actions in PDF Documents

2024-11-25 01:09:22 Written by Koohji

Enhancing the interactivity of PDF files is a crucial aspect of document management and user engagement. Creating actions within PDFs using C# in the .NET framework allows developers to add dynamic elements such as file links, web links, and audio that can execute various functions like navigating to different pages, launching external applications, or playing background music, which improves the user experience by making PDFs more functional and engaging. This article demonstrates how to use the Spire.PDF for .NET library to create actions in PDF documents with C#.

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

General Steps for Adding Actions to PDF with C#

Adding actions to a PDF using C# involves integrating interactive elements that enhance user experience, such as navigation buttons, file links, web links, or sound triggers. With the Spire.PDF for .NET library, developers can create various actions in PDF documents with C# code. Below is a table of the classes for commonly used actions and their descriptions:

Class Decryption
PdfGoToAction Represents an action that navigates to a destination within the current document.
PdfLaunchAction Represents an action that opens a file.
PdfSoundAction Represents an action that plays a sound.
PdfJavaScriptAction Represents an action that executes JavaScript code in a PDF document.
PdfUriAction Represents an action that resolves a Uniform Resource Identifier (URI).
PdfGoToAction Represents an action that navigates to a destination within the current document.

For more action classes and their descriptions, refer to Spire.PDF for .NET action API references.

Actions can be added to PDF documents in two primary ways:

1. Using Action Annotations

This method involves creating an action and linking it to an annotation on the page. The action is displayed and triggered when the annotation is clicked.

General Steps:

  • Create an instance of PdfDocument class and load a PDF document using PdfDocument.LoadFromFile() method.
  • Get a page using PdfDocument.Pages[] property.
  • Create an instance of the class that represents the action and set the action properties.
  • Create an instance of PdfActionAnnotation class in a rectangular area on the page using the action.
  • Add the cue word for the action to the page (optional).
  • Add the action annotation to the page using PdfPageBase.Annotations.Add() method.
  • Save the result document using PdfDocument.SaveToFile() method.

2. Assigning Actions to Document Events

Actions can also be assigned to document-level events such as opening, closing, or printing the document. These actions are triggered automatically when the specified events occur.

General Steps:

  • Create an instance of PdfDocument class and load a PDF document using PdfDocument.LoadFromFile() method.
  • Create an instance of the class that represents the action and set the action properties.
  • Assign the action to a document event using the following properties:
    • PdfDocument.AfterOpenAction
    • PdfDocument.AfterSaveAction
    • PdfDocument.AfterPrintAction
    • PdfDocument.BeforeCloseAction
    • PdfDocument.BeforeSaveAction
    • PdfDocument.BeforePrintAction
  • Save the result document using PdfDocument.SaveToFile() method.

Create Navigation Actions in PDF with C#

Navigation actions can be created using the PdfGoToAction class, which defines navigation within the document to a specified destination. To achieve this, developers can create a PdfDestination object and pass it as a parameter to a PdfGoToAction instance.

The following is a code example of adding a navigation action to a PDF:

  • C#
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.General;
using Spire.Pdf.Graphics;
using System.Drawing;

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

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

            // Create a PdfDestination instance and set the destination
            PdfDestination destination = new PdfDestination(pdf.Pages[1]);
            destination.Location = new PointF(0, 0);
            destination.Mode = PdfDestinationMode.Location;
            destination.Zoom = 0.8f;

            // Create a PdfGoToAction based on the destination
            PdfGoToAction action = new PdfGoToAction(destination);

            // Create a rectangle and draw it on the first page
            RectangleF rect = new RectangleF(70, pdf.PageSettings.Size.Height - 120, 140, 20);
            pdf.Pages[0].Canvas.DrawRectangle(PdfBrushes.LightGray, rect);
            // Draw cue words on the rectangle
            PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 14);
            PdfStringFormat stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            pdf.Pages[0].Canvas.DrawString("To Page 2", font, PdfBrushes.Green, rect, stringFormat);

            // Create a PdfActionAnnotation instance based on the rectangle and the action
            PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, action);

            // Add the action annotation to the first page
            pdf.Pages[0].Annotations.Add(actionAnnotation);

            // Save the document
            pdf.SaveToFile("output/NavigationButton.pdf");
            pdf.Close();
        }
    }
}

Result of Creating Navigation Buttons with C#

Create File Launch Actions in PDF with C#

The PdfLaunchAction class defines a file open action in a PDF that enables users to open a specific file by clicking a button embedded on a PDF page. When implementing this action, developers can set the file path (absolute or relative) and decide whether the file should open in a new window. Here is a code example for adding a file launch action in a PDF document:

  • C#
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.Graphics;
using System.Drawing;

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

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

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

            // Draw a rectangle on the page
            RectangleF rect = new RectangleF(50, 50, 180, 20);
            page.Canvas.DrawRectangle(PdfBrushes.LightGray, rect);
            // Darw the cue words in the rectangle
            PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 14);
            PdfStringFormat stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            pdf.Pages[0].Canvas.DrawString("Click to launch Sample2", font, PdfBrushes.Green, rect, stringFormat);

            // Create a PdfLaunchAction instance
            PdfLaunchAction action = new PdfLaunchAction("C:/Sample2.pdf", PdfFilePathType.Absolute);
            // Set the launch mode to open in new window
            action.IsNewWindow = true;

            // Create a PdfActionAnnotation instance based on the rectangle and the launch action
            PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, action);

            // Add the action annotation to the first page
            page.Annotations.Add(actionAnnotation);

            // Save the document
            pdf.SaveToFile("output/LaunchAction.pdf");
            pdf.Close();
        }
    }
}

Result of Creating File Launch Actions with C#

Create Sound Actions in PDF with C#

Developers can embed audio as an action in PDF documents with the PdfSoundAction class, enabling the audio to play in response to specific triggers, such as opening the file or clicking a button. Below is a code example for creating a sound action in a PDF document:

  • C#
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.Graphics;
using Spire.Pdf.General;
using System.Drawing;

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

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

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

            // Darw the cue image on the page
            PdfImage image = PdfImage.FromFile("Sound.png");
            page.Canvas.DrawImage(image, new PointF(30, 30));

            // Create a PdfSoundAction instance and set its property
            PdfSoundAction action = new PdfSoundAction("Wave.wav");
            // Set the sound parameters
            action.Sound.Bits = 16;
            action.Sound.Channels = PdfSoundChannels.Stereo;
            action.Sound.Encoding = PdfSoundEncoding.Signed;
            action.Sound.Rate = 44100;
            // Set the play options
            action.Volume = 0;
            action.Repeat = true;
            action.Mix = true;
            action.Synchronous = true;

            // Create a PdfActionAnnotation instance using the sound action at the location of the cue image
            RectangleF rect = new RectangleF(30, 30, image.Width, image.Height);
            PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, action);

            // Add the action annotation to the first page
            page.Annotations.Add(actionAnnotation);

            // Set the sound action to play after the document is opened
            pdf.AfterOpenAction = action;

            // Save the document
            pdf.SaveToFile("output/SoundAction.pdf");
            pdf.Close();
        }
    }
}

Result of Creating Sound Actions with C#

Create Web Link Actions in PDF with C#

Developers can use the PdfUriAction class to create a web link action in PDF documents, allowing users to open a web link when performing specific actions, such as clicking a button. Below is a code example for creating a web link action in a PDF document:

  • C#
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.Graphics;
using System.Drawing;

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

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

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

            // Draw a rectangle on the page
            RectangleF rect = new RectangleF(30, 30, 120, 20);
            page.Canvas.DrawRectangle(PdfBrushes.LightGray, rect);
            // Draw the cue words in the rectangle
            PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 14);
            PdfStringFormat stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            page.Canvas.DrawString("Go to Google Search", font, PdfBrushes.LightSkyBlue, rect);

            // Create a PdfUriAction instance and set its property
            PdfUriAction action = new PdfUriAction();
            action.Uri = "https://www.google.com/";

            // Create a PdfActionAnnotation instance using the web link action and the rectangle
            PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, action);

            // Add the action annotation to the first page
            page.Annotations.Add(actionAnnotation);

            // Save the document
            pdf.SaveToFile("output/WebLinkAction.pdf");
            pdf.Close();
        }
    }
}

Result of Creating Web Link Actions with C#

Create JavaScript Actions in PDF with C#

The PdfJavaScriptAction represents a JavaScript action in PDF, which allows developers to create complex interactions such as form validations, data calculations, and custom user interfaces. Below is a code example for adding a simple JavaScript action to a PDF document with C#:

  • C#
using Spire.Pdf;
using Spire.Pdf.Actions;

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

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

            // Define JavaScript code
            var jsCode =
            "app.alert({" +
            "    cMsg: 'Welcome to the article about the Evolution and Advantages of LCD Screens!\\n\\nThis article explores the history and benefits of LCD technology, including its impact on visual experiences across various devices.', " +
            "    nIcon: 3, " +
            "    cTitle: 'Document Introduction'" +
            "});";

            // Create a PdfJavaScriptAction instance using the JavaScript code
            PdfJavaScriptAction action = new PdfJavaScriptAction(jsCode);

            // Set the action to be executed when the PDF document is launched
            pdf.AfterOpenAction = action;

            // Save the document
            pdf.SaveToFile("output/PDFJavaScriptAction.pdf");
            pdf.Close();
        }
    }
}

Result of Creating JavaScript Actions 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.

In PowerPoint, comments are a very useful feature that can help you add notes or feedback to your slides. In addition to adding or removing comments, sometimes you may need to modify existing comments to correct errors or outdated information. Or in a collaborative editing scenario, you may need to extract comments to collect suggestions of all members. This article will demonstrate how to modify or extract comments in PowerPoint in C# using Spire.Presentation for .NET.

Install Spire.Presentation for .NET

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

PM> Install-Package Spire.Presentation

Modify Comments on a Presentation Slide in C#

The ISlide.Comments[].Text property provided by Spire.Presentation for .NET allows you to update the content of a specified comment with new text. The following are the detailed steps.

  • Create a Presentation instance.
  • Load a PowerPoint presentation using Presentation.LoadFromFile() method.
  • Get a specified slide through Prenstion.Slides[] property.
  • Update a specified comment on the slide through ISlide.Comments[].Text property.
  • Save the result file using Presentation.SaveToFile() method.
  • C#
using Spire.Presentation;

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

            // Load a PowerPoint presentation
            presentation.LoadFromFile("Comments.pptx");

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

            // Update the first comment in the slide
            slide.Comments[0].Text = "Replace comment";

            // Save the result file
            presentation.SaveToFile("ModifyComment.pptx", FileFormat.Pptx2016);

        }
    }
}

Modify the first comment on the first slide with new text

Extract Comments from a Presentation Slide in C#

To extract comments from a slide, you need to get all the comments in the slide via the ISlide.Comments property, and then iterate through each comment to get its text content via the Comment.Text property. The following are the detailed steps.

  • Create a Presentation instance.
  • Load a PowerPoint presentation using Presentation.LoadFromFile() method.
  • Create a StringBuilder instance.
  • Get a specified slide through Prenstion.Slides[] property.
  • Get all comments in the slide through ISlide.Comments property.
  • Iterate over each comment to get its text content through Comment.Text property, and then append to the StringBuilder instance.
  • Write to a text file using Presentation.SaveToFile() method.
  • C#
using Spire.Presentation;
using System.IO;
using System.Text;

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

            // Load a PowerPoint presentation
            presentation.LoadFromFile("Comments.pptx");

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

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

            // Get all comments in the slide
            Comment[] comments = slide.Comments;

            // Append the comment text to the StringBuilder instance
            for (int i = 0; i < comments.Length; i++)
            {
                str.Append(comments[i].Text + "\r\n");
            }

            // Write to a text file
            File.WriteAllText("ExtractComment.txt", str.ToString());
        }
    }
}

Get all the comments on the first slide and export to a text 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.

Sections in PowerPoint let you group related slides together, making it easy to segment a presentation by topics, chapters, or any other logical structure. When working with large, multi-section presentations, automating slide operations - such as insertion, retrieval, reordering, and removal - can significantly improve productivity. In this article, we will explain how to insert, retrieve, reorder, and remove slides in PPT sections in C# using Spire.Presentation for .NET.

Install Spire.Presentation for .NET

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

PM> Install-Package Spire.Presentation

Insert Slides into a PowerPoint Section in C#

Inserting slides is often needed when you need to add new content to a section. With Spire.Presentation for .NET, you can insert a slide into a section using the Section.Insert() method. The detailed steps are as follows.

  • Create an instance of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Get a specific section through its index (0-based) using the Presentation.SectionList(index) property.
  • Add a new slide to presentation, then insert it into the section using the Section.Insert() method.
  • Remove the added slide from the presentation.
  • Save the resulting presentation using the Presentation.SaveToFile() method.
  • C#
using Spire.Presentation;
using System.Collections.Generic;

namespace InsertSlidesInSection
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the Presentation class
            using (Presentation presentation = new Presentation())
            {
                // Load a PowerPoint presentation
                presentation.LoadFromFile("Example.pptx");

                // Access the first section
                Section firstSection = presentation.SectionList[0];

                // Add a new slide to the presentation and insert it at the start of the section
            ISlide slide = presentation.Slides.Append();
            firstSection.Insert(0, slide);
            // Remove the added slide from the presentation
            presentation.Slides.Remove(slide);

                // Save the modified presentation
                presentation.SaveToFile("InsertSlidesInSection.pptx", FileFormat.Pptx2016);
            }
        }
    }
}

Insert Slides into a PowerPoint Section in C#

Retrieve Slides from a PowerPoint Section in C#

Extracting slides from a specific section allows you to focus on a subset of slides for targeted operations, like slide reordering or applying specific formatting. Using the Section.GetSlides() method in Spire.Presentation for .NET, you can easily retrieve all slides within a given section. The detailed steps are as follows.

  • Create an instance of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Get a specific section through its index (0-based) using the Presentation.SectionList(index) property.
  • Retrieve the slides within the section using the Section.GetSlides() method.
  • Iterate through the retrieved slides and get the slide number (1-based) of each slide.
  • C#
using Spire.Presentation;
using System;

namespace RetrieveSlidesInSection
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the Presentation class
            using (Presentation presentation = new Presentation())
            {
                // Load a PowerPoint presentation
                presentation.LoadFromFile("Example.pptx");

                // Retrieve the slides in the 3rd section
                Section section = presentation.SectionList[2];
                ISlide[] slides = section.GetSlides();

                // Output the slide number for each slide in the section
                foreach (ISlide slide in slides)
                {
                    Console.Write(slide.SlideNumber + " ");
                }                               
                Console.ReadKey();
            }
        }
    }
}

Retrieve Slides from a PowerPoint Section in C#

Reorder Slides in a PowerPoint Section in C#

Reordering slides is essential for ensuring that related content follows a logical sequence. Spire.Presentation for .NET offers the Section.Move() method for moving a slide in a section to another position. The detailed steps are as follows.

  • Create an instance of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Get a specific section through its index (0-based) using the Presentation.SectionList(index) property.
  • Move a specific slide in the section to another position using the Section.Move() method.
  • Save the resulting presentation using the Presentation.SaveToFile() method.
  • C#
using Spire.Presentation;

namespace ReorderSlidesInSection
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the Presentation class
            using (Presentation presentation = new Presentation())
            {
		   // Load a PowerPoint presentation
                presentation.LoadFromFile("Example.pptx");

                // Access the 3rd section
                Section section = presentation.SectionList[2];

                // Retrieve the slides in the section
                ISlide[] slides = section.GetSlides();

                // Move the 1st slide in the section to the specified position
                section.Move(2, slides[0]);                                  

                // Save the modified presentation
                presentation.SaveToFile("ReorderSlidesInSection.pptx", FileFormat.Pptx2016);
            }
        }
    }
}

Reorder Slides in a PowerPoint Section in C#

Remove Slides from a PowerPoint Section in C#

Removing slides from a section helps streamline your presentation, especially when certain slides become outdated or irrelevant. With the Section.RemoveAt() or Section.RemoveRange() method in Spire.Presentation for .NET, you can easily delete an individual slide or a range of slides from a section. The detailed steps are as follows.

  • Create an instance of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Get a specific section through its index (0-based) using the Presentation.SectionList(index) property.
  • Remove a specific slide or a range of slides from the presentation using the Section.RemoveAt() or Section.RemoveRange() method.
  • Save the resulting presentation using the Presentation.SaveToFile() method.
  • C#
using Spire.Presentation;

namespace RemoveSlidesInSection
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the Presentation class
            using (Presentation presentation = new Presentation())
            {
                // Load a PowerPoint presentation
                presentation.LoadFromFile("Course.pptx");

                // Access the 3rd section
                Section section = presentation.SectionList[2];
                
                // Remove the first slide from the section
                section.RemoveAt(0);

                // Or remove a range of slides from the section
                //section.RemoveRange(0, 2);

                // Save the modified presentation
                presentation.SaveToFile("RemoveSlidesInSection.pptx", FileFormat.Pptx2016);
            }
        }
    }
}

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.

HTML is widely used to present content in web browsers, but preserving its exact layout when sharing or printing can be challenging. PDF, by contrast, is a universally accepted format that reliably maintains document layout across various devices and operating systems. Converting HTML to PDF is particularly useful in web development, especially when creating printable versions of web pages or generating reports from web data.

Spire.PDF for .NET now supports a streamlined method to convert HTML to PDF in C# using the ChromeHtmlConverter class. This tutorial provides step-by-step guidance on performing this conversion effectively.

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

Install Google Chrome

This method requires Google Chrome to perform the conversion. If Chrome is not already installed, you can download it from this link and install it.

Convert HTML to PDF using ChromeHtmlConverter in C#

You can utilize the ChromeHtmlConverter.ConvertToPdf() method to convert an HTML file to a PDF using the Chrome plugin. This method accepts 3 parameters, including the input HTML file path, output PDF file path, and ConvertOptions which allows customization of conversion settings like conversion timeout, PDF paper size and page margins. The detailed steps are as follows.

  • Create an instance of the ChromeHtmlConverter class and provide the path to the Chrome plugin (chrome.exe) as a parameter in the class constructor.
  • Create an instance of the ConvertOptions class.
  • Customize the conversion settings, such as the conversion timeout, the paper size and page margins of the converted PDF through the properties of the ConvertOptions class.
  • Convert an HTML file to PDF using the ChromeHtmlConverter.ConvertToPdf() method.
  • C#
using Spire.Additions.Chrome;

namespace ConvertHtmlToPdfUsingChrome
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Specify the input URL and output PDF file path
            string inputUrl = @"https://www.e-iceblue.com/Tutorials/Spire.PDF/Spire.PDF-Program-Guide/C-/VB.NET-Convert-Image-to-PDF.html";            
            string outputFile = @"HtmlToPDF.pdf";

            //Specify the path to the Chrome plugin
            string chromeLocation = @"C:\Program Files\Google\Chrome\Application\chrome.exe";

            //Create an instance of the ChromeHtmlConverter class
            ChromeHtmlConverter converter = new ChromeHtmlConverter(chromeLocation);

            // Create an instance of the ConvertOptions class
            ConvertOptions options = new ConvertOptions();
            //Set conversion timeout
            options.Timeout = 10 * 3000;
            //Set paper size and page margins of the converted PDF
            options.PageSettings = new PageSettings()
            {
                PaperWidth = 8.27,
                PaperHeight = 11.69,
                MarginTop = 0,
                MarginLeft = 0,
                MarginRight = 0,
                MarginBottom = 0

            };

            //Convert the URL to PDF
            converter.ConvertToPdf(inputUrl, outputFile, options);
        }
    }
}

The converted PDF file maintains the same appearance as if the HTML file were printed to PDF directly through the Chrome browser:

C#: Convert HTML to PDF using ChromeHtmlConverter

Generate Output Logs During HTML to PDF Conversion in C#

Spire.PDF for .NET enables you to generate output logs during HTML to PDF conversion using the Logger class. The detailed steps are as follows.

  • Create an instance of the ChromeHtmlConverter class and provide the path to the Chrome plugin (chrome.exe) as a parameter in the class constructor.
  • Enable Logging by creating a Logger object and assigning it to the ChromeHtmlConverter.Logger property.
  • Create an instance of the ConvertOptions class.
  • Customize the conversion settings, such as the conversion timeout, the paper size and page margins of the converted PDF through the properties of the ConvertOptions class.
  • Convert an HTML file to PDF using the ChromeHtmlConverter.ConvertToPdf() method.
  • C#
using Spire.Additions.Chrome;

namespace ConvertHtmlToPdfUsingChrome
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Specify the input URL and output PDF file path
            string inputUrl = @"https://www.e-iceblue.com/Tutorials/Spire.PDF/Spire.PDF-Program-Guide/C-/VB.NET-Convert-Image-to-PDF.html";
            string outputFile = @"HtmlToPDF.pdf";

            // Specify the log file path
            string logFilePath = @"Logs.txt";

            //Specify the path to the Chrome plugin
            string chromeLocation = @"C:\Program Files\Google\Chrome\Application\chrome.exe";

            //Create an instance of the ChromeHtmlConverter class
            ChromeHtmlConverter converter = new ChromeHtmlConverter(chromeLocation);
            //Enable logging
            converter.Logger = new Logger(logFilePath);

            //Create an instance of the ConvertOptions class
            ConvertOptions options = new ConvertOptions();
            //Set conversion timeout
            options.Timeout = 10 * 3000;
            //Set paper size and page margins of the converted PDF
            options.PageSettings = new PageSettings()
            {
                PaperWidth = 8.27,
                PaperHeight = 11.69,
                MarginTop = 0,
                MarginLeft = 0,
                MarginRight = 0,
                MarginBottom = 0

            };

            //Convert the URL to PDF
            converter.ConvertToPdf(inputUrl, outputFile, options);
        }
    }
}

Here is the screenshot of the output log file:

C#: Convert HTML to PDF using ChromeHtmlConverter

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 Word to Markdown

2024-10-31 06:06:12 Written by Koohji

Markdown, with its lightweight syntax, offers a streamlined approach to web content creation, collaboration, and document sharing, particularly in environments where tools like Git or Markdown-friendly editors are prevalent. By converting Word documents to Markdown files, users can enhance their productivity, facilitate easier version control, and ensure compatibility across different systems and platforms. In this article, we will explore the process of converting Word documents to Markdown files using Spire.Doc for .NET, providing simple C# code examples.

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

Convert Word to Markdown with C#

Using Spire.Doc for .NET, we can convert a Word document to a Markdown file by loading the document using Document.LoadFromFile() method and then convert it to a Markdown file using Document.SaveToFile(filename: String, FileFormat.Markdown) method. The detailed steps are as follows:

  • Create an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Convert the document to a Markdown file using Document.SaveToFile(filename: String, FileFormat.Markdown) method.
  • Release resources.
  • C#
using Spire.Doc;

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

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

            // Convert the document to a Markdown file
            doc.SaveToFile("output/WordToMarkdown.md", FileFormat.Markdown);
            doc.Dispose();
        }
    }
}

C#: Convert Word to Markdown

Convert Word to Markdown Without Images

When using Spire.Doc for .NET to convert Word documents to Markdown files, images are stored in Base64 encoding by default, which can increase the file size and affect compatibility. To address this, we can remove the images during conversion, thereby reducing the file size and enhancing compatibility.

The following steps outline how to convert Word documents to Markdown files without images:

  • Create an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Iterate through the sections and then the paragraphs in the document.
  • Iterate through the document objects in the paragraphs:
    • Get a document object through Paragraph.ChildObjects[] property.
    • Check if it’s an instance of DocPicture class. If it is, remove it using Paragraph.ChildObjects.Remove(DocumentObject) method.
  • Convert the document to a Markdown file using Document.SaveToFile(filename: String, FileFormat.Markdown) method.
  • Release resources.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

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

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

            // Iterate through the sections in the document
            foreach (Section section in doc.Sections)
            {
                // Iterate through the paragraphs in the sections
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    // Iterate through the document objects in the paragraphs
                    for (int i = 0; i < paragraph.ChildObjects.Count; i++)
                    {
                        // Get a document object
                        DocumentObject docObj = paragraph.ChildObjects[i];
                        // Check if it is an instance of DocPicture class
                        if (docObj is DocPicture)
                        {
                            // Remove the DocPicture instance
                            paragraph.ChildObjects.Remove(docObj);
                        }
                    }
                }
            }

            // Convert the document to a Markdown file
            doc.SaveToFile("output/WordToMarkdownNoImage.md", FileFormat.Markdown);
            doc.Dispose();
        }
    }
}

C#: Convert Word 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.

Page 4 of 95
page 4