Conversion

Conversion (31)

Tutorial on how to convert databases to PDF in C# using Spire.XLS for .NET

Exporting database query results to PDF is a common requirement in applications such as reporting, data archiving, and document generation. In these scenarios, SQL query results need to be transformed into structured, readable documents that can be easily shared or printed.

Because database data is inherently tabular, preserving its structure during the export process is essential for maintaining clarity and usability. Without proper layout control, the resulting document can quickly become difficult to read, especially when dealing with large datasets.

This article demonstrates how to convert databases to PDF in C# using Spire.XLS for .NET, including examples on retrieving query results, organizing them into a structured table, and exporting them as a formatted PDF document.

Table of Contents


1. Understanding the Task

Converting database content to PDF typically involves several key steps:

  • Data retrieval: Execute SQL queries and load results into memory
  • Data structuring: Organize query results into a consistent tabular format
  • PDF export: Generate a document that preserves layout and readability

In practice, this workflow is commonly used for generating reports, creating invoices, or archiving query results, where maintaining a clear and structured presentation of data is essential.


2. Convert Database to PDF Using C# (Step-by-Step)

This section provides a complete workflow for converting database query results into a PDF document, including data retrieval, table structuring, formatting, and export.

2.1 Environment Setup

Before implementing the solution, make sure your development environment is ready:

  • .NET environment
    Install Visual Studio or use the .NET CLI with a compatible .NET version (e.g., .NET 6 or later).

  • Database access
    Prepare a SQL Server database (or any relational database) and ensure you have a valid connection string. For modern .NET applications, use the recommended SQL client library:

    dotnet add package Microsoft.Data.SqlClient
    

    This package provides the ADO.NET implementation for SQL Server and replaces the legacy System.Data.SqlClient.

  • Spire.XLS for .NET Install Spire.XLS via NuGet to handle table formatting and PDF export:

    dotnet add package Spire.XLS
    

    You can also download the Spire.XLS for .NET package and add it to your project manually.

Once configured, you can retrieve data from the database and use Spire.XLS to generate and export PDF documents.

2.2 Read Data from Database

The first step is to execute a SQL query and load the results into a DataTable. This structure preserves the schema and data types of the query result, making it suitable for further transformation.

using System.Data;
using Microsoft.Data.SqlClient;

string connectionString = "Server=localhost\\SQLEXPRESS;Database=SalesDB;User ID=demouser;Password=YourPassword;Encrypt=true;TrustServerCertificate=true;";
string query = @"
    SELECT o.OrderID, c.CustomerName, o.OrderDate, o.TotalAmount
    FROM Orders o
    JOIN Customers c ON o.CustomerID = c.CustomerID
    WHERE YEAR(o.OrderDate) = 2026;
";

DataTable dataTable = new DataTable();

using (SqlConnection conn = new SqlConnection(connectionString))
{
    SqlDataAdapter adapter = new SqlDataAdapter(query, conn);
    adapter.Fill(dataTable);
}

This example uses Microsoft.Data.SqlClient, the modern SQL client library for .NET, which is recommended over the legacy System.Data.SqlClient.

The SqlDataAdapter acts as a bridge between the database and in-memory data. It executes the query and fills the DataTable without requiring explicit connection management for reading operations.

In practical scenarios, this step can be extended to include:

  • Parameterized queries to avoid SQL injection
  • Stored procedures for complex data retrieval
  • Data filtering and aggregation directly in SQL

By preparing clean and structured data at this stage, you reduce the complexity of downstream formatting and improve overall performance.

For a similar scenario involving exporting database query results to Excel instead of PDF, you can also refer to this guide: Export Database to Excel in C#.

2.3 Import Data and Export to PDF with Formatting

After retrieving the data, the next step is to map it into a worksheet, apply formatting, and export it as a PDF document. This approach leverages worksheet-based layout control to ensure the output remains structured and readable.

using Spire.Xls;
using System.Drawing;

// Create workbook and worksheet
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];

// Import DataTable with headers
sheet.InsertDataTable(dataTable, true, 1, 1);

// Format header row
CellRange headerRange = sheet.Range[1, 1, 1, dataTable.Columns.Count];
headerRange.Style.Font.IsBold = true;
headerRange.Style.Font.Size = 11;
headerRange.Style.Color = Color.LightGray;

// Apply borders to enhance table structure
CellRange dataRange = sheet.AllocatedRange;
dataRange.BorderAround(LineStyleType.Thin);
dataRange.BorderInside(LineStyleType.Thin);

// Align content for consistency
dataRange.Style.HorizontalAlignment = HorizontalAlignType.Center;
dataRange.Style.VerticalAlignment = VerticalAlignType.Center;

// Auto-fit columns for better layout
sheet.AllocatedRange.AutoFitColumns();

// Center the content horizontally in the page
sheet.PageSetup.CenterHorizontally = true;

// Export to PDF
workbook.SaveToFile("SalesReport_2026.pdf", FileFormat.PDF);

This step combines layout control and PDF generation into a single workflow.

Key points to note:

  • Worksheet as layout engine The worksheet acts as a structured canvas where database data is arranged into rows and columns. This ensures the original tabular structure is preserved in the final document.

  • Formatting directly impacts PDF output Adjustments such as column width, font style, and borders are not just visual improvements—they determine how the content is rendered in the PDF. Poor formatting can lead to truncated text or unreadable layouts.

  • Automatic pagination When exporting, the worksheet content is automatically split across pages based on layout and paper size, which is particularly useful for large datasets.

For further layout optimization, you can enhance the table formatting by:

If your project requires more flexible PDF structure control, you can also explore converting DataTable to PDF in C# directly using Spire.PDF for .NET, which provides more advanced document-level layout capabilities for complex reporting needs.


3. Complete C# Example for Converting Databases to PDF

Below is the complete implementation that combines database retrieval, data formatting, and PDF export into a single workflow.

using System;
using System.Data;
using Microsoft.Data.SqlClient;
using Spire.Xls;
using System.Drawing;

class Program
{
    static void Main()
    {
        // Step 1: Retrieve data from database
        string connectionString = "Server=localhost\\SQLEXPRESS;Database=SalesDB;User ID=demouser;Password=YourPassword;Encrypt=true;TrustServerCertificate=true;";
        string query = @"
            SELECT o.OrderID, c.CustomerName, o.OrderDate, o.TotalAmount
            FROM Orders o
            JOIN Customers c ON o.CustomerID = c.CustomerID
            WHERE YEAR(o.OrderDate) = 2026;
        ";

        DataTable dataTable = new DataTable();

        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            SqlDataAdapter adapter = new SqlDataAdapter(query, conn);
            adapter.Fill(dataTable);
        }

        // Step 2: Create workbook and import data
        Workbook workbook = new Workbook();
        Worksheet sheet = workbook.Worksheets[0];
        sheet.InsertDataTable(dataTable, true, 1, 1);

        // Step 3: Apply professional formatting
        // Format header row
        CellRange headerRange = sheet.Range[1, 1, 1, dataTable.Columns.Count];
        headerRange.Style.Font.IsBold = true;
        headerRange.Style.Font.Size = 11;
        headerRange.Style.Color = Color.LightGray;

        // Apply borders
        CellRange dataRange = sheet.AllocatedRange;
        dataRange.BorderAround(LineStyleType.Thin);
        dataRange.BorderInside(LineStyleType.Thin);

        // Set alignment
        dataRange.Style.HorizontalAlignment = HorizontalAlignType.Center;
        dataRange.Style.VerticalAlignment = VerticalAlignType.Center;

        // Auto-fit columns
        sheet.AllocatedRange.AutoFitColumns();

        // Center the content horizontally in the pages
        sheet.PageSetup.CenterHorizontally = true;

        // Step 4: Export to PDF
        workbook.SaveToFile("SalesReport_2026.pdf", FileFormat.PDF);

        Console.WriteLine("Database query results successfully exported to PDF.");
    }
}

Below is a preview of the generated PDF:

Convert Database Query Results to PDF with C#

This example demonstrates an end-to-end workflow from SQL query execution to PDF generation.


4. Advanced Scenarios

In real-world applications, exporting database data to PDF often requires more than just basic conversion. You may need to handle batch exports, improve document readability, or adjust layout settings for better presentation. The following examples demonstrate common enhancements for real-world usage.

Export Multiple Query Results

For scenarios such as batch report generation or scheduled tasks, you may need to execute multiple queries and export each result as a separate PDF document:

string[] queries = {
    "SELECT * FROM Orders WHERE Status = 'Pending'",
    "SELECT * FROM Customers WHERE Region = 'North'"
};

for (int i = 0; i < queries.Length; i++)
{
    DataTable dt = ExecuteQuery(queries[i]);
    Workbook wb = new Workbook();
    Worksheet ws = wb.Worksheets[0];
    ws.InsertDataTable(dt, true, 1, 1);
    ws.AllocatedRange.AutoFitColumns();
    wb.SaveToFile($"Report_{i + 1}.pdf", FileFormat.PDF);
}

This approach is useful for automating report generation where multiple datasets need to be exported independently.

Add Title and Metadata

To improve readability and provide context, you can add a title row above the data before exporting to PDF:

// Insert title row
sheet.InsertRow(1);
sheet.Range[1, 1].Text = "Sales Report - 2026";
sheet.Range[1, 1].Style.Font.IsBold = true;
sheet.Range[1, 1].Style.Font.Size = 14;

// Merge title cells
sheet.Range[1, 1, 1, dataTable.Columns.Count].Merge();

// Auto-fit the title row
sheet.AutoFitRow(1);

The following image shows the generated PDF with the title row applied:

Convert Database Query Results to PDF with C#

Adding a title helps users quickly understand the context of the document, especially when sharing or printing reports.

Set Page Size, Orientation, and Margins

To ensure the PDF layout fits your data properly, you can configure page size, orientation, and margins before exporting:

// Set the page size and orientation
sheet.PageSetup.PaperSize = PaperSizeType.PaperA4;
sheet.PageSetup.Orientation = PageOrientationType.Portrait;

// Set the page margins
sheet.PageSetup.TopMargin = 0.5f;
sheet.PageSetup.BottomMargin = 0.2f;
sheet.PageSetup.LeftMargin = 0.2f;
sheet.PageSetup.RightMargin = 0.2f;

Adjusting these settings helps prevent content overflow and ensures consistent layout across different reports.

Control Page Layout and Scaling

When working with large tables, you may need to control how content is distributed across pages. By default, content is split automatically, but you can adjust scaling behavior to fit more data within a page.

// Fit content to page width
workbook.ConverterSetting.SheetFitToWidth = true;

// Fit entire sheet into a single page (may reduce readability)
workbook.ConverterSetting.SheetFitToPage = true;
  • SheetFitToWidth ensures the table fits within the page width while allowing vertical pagination
  • SheetFitToPage scales the entire worksheet to fit into a single page

These settings are useful when generating compact reports, but should be used carefully to avoid making text too small.

Add Headers and Footers

Headers and footers are useful for adding contextual information such as report titles, timestamps, or page numbers:

sheet.PageSetup.LeftHeader = "&\"Arial,Bold\"&16 Sales Report - 2026";
sheet.PageSetup.RightHeader = "&\"Arial,Italic\"&10 Generated on &D";
sheet.PageSetup.CenterFooter = "&\"Arial,Regular\"&16 Page &P of &N";

The following image shows the generated PDF with headers and footers applied:

Convert Database Query Results to PDF with C#

These elements improve document navigation and are especially valuable for multi-page reports.

Encrypt PDFs

To protect sensitive data, you can apply encryption to the exported PDF:

workbook.ConverterSetting.PdfSecurity.Encrypt("openpsd");

Encryption ensures that only authorized users can access the document, which is important for reports containing confidential or business-critical data.

For more related scenarios involving document export and PDF customization, you can also explore Excel to PDF conversion in C#.


5. Common Pitfalls

Database Connection Issues

Ensure the connection string is correct and the database server is accessible. Verify authentication settings (e.g., SQL authentication or integrated security) and confirm that encryption-related parameters match your environment configuration.

Empty Query Results

Check whether the DataTable contains data before proceeding. Empty result sets may lead to blank PDFs or unexpected formatting behavior.

if (dataTable.Rows.Count == 0)
{
    Console.WriteLine("No data found for the specified query.");
    return;
}

In production scenarios, you may also choose to generate a placeholder PDF or log the issue instead of exiting the process.

Column Width Overflow

When working with long text fields, AutoFitColumns() may produce excessively wide columns, which can negatively affect PDF layout.

To improve readability, consider:

  • Setting a maximum column width
  • Enabling text wrapping for long content
  • Manually adjusting key columns based on data type

This is especially important when exporting large datasets with variable-length text.

Missing Font Support

If the exported PDF contains special characters (e.g., non-Latin text) or custom fonts, ensure the required fonts are installed and accessible at runtime.

Missing fonts may cause text rendering issues or fallback substitutions, which can affect document appearance and readability.

Unexpected PDF Layout

If the exported PDF layout appears compressed or improperly scaled, check page setup and scaling options such as SheetFitToWidth or SheetFitToPage.

Improper scaling may cause content to appear too small or distort the original table structure.


Conclusion

This article demonstrated a practical approach to converting database query results to PDF in C#. By combining structured data retrieval with worksheet-based formatting, you can generate clear and professional documents directly from SQL data.

This method is particularly effective for report generation and data presentation scenarios where maintaining table structure and readability is essential.

If you are evaluating Spire.XLS, you can request a free temporary license to remove evaluation limitations during development.


FAQ

Can Spire.XLS export database data to PDF without third-party tools?

Yes. Spire.XLS performs all operations independently and does not require Microsoft Office or any other external tools.

How do I handle large datasets when exporting to PDF?

For large datasets, consider paginating the results or filtering the query to retrieve only necessary data. You can also adjust PDF page settings to optimize output size.

Can I customize the PDF page layout?

Yes. Spire.XLS allows you to configure page settings including orientation, margins, and paper size before exporting to PDF.

Does this method work with databases other than SQL Server?

Yes. The approach works with any database that supports ADO.NET data providers, including MySQL, PostgreSQL, and Oracle. Simply use the appropriate connection class and data adapter.

Should I use Microsoft.Data.SqlClient or System.Data.SqlClient?

For modern .NET applications, it is recommended to use Microsoft.Data.SqlClient. It is actively maintained and provides better support for newer SQL Server features, while System.Data.SqlClient is considered legacy and no longer receives major updates.

Conversion between Excel and JSON in C# .NET

Converting between Excel and JSON formats is a valuable skill for developers dealing with data exchange, API integration, and modern web applications.

Excel files (.xls, .xlsx) are excellent for organizing and analyzing tabular data, while JSON (JavaScript Object Notation) is lightweight, human-readable, and ideal for transmitting data across platforms.

In this step-by-step tutorial, you’ll learn how to seamlessly convert Excel to JSON and JSON to Excel in C# using the Spire.XLS for .NET library. Whether you’re exporting Excel data for frontend apps, feeding structured datasets into APIs, or importing JSON into spreadsheets, this guide provides clear explanations, complete code samples, and tips to help you get started quickly.

What You Will Learn

Why Convert Between Excel and JSON Formats?

Converting between Excel and JSON can be beneficial for several reasons:

  • Data Exchange: JSON is a standard format for data interchange in web applications, making it easier to share data across platforms.
  • Integration with APIs: Many web APIs require data in JSON format, necessitating conversion from Excel for seamless integration.
  • Lightweight and Compact: JSON files are generally smaller in size compared to Excel files, leading to faster data transfer and reduced storage needs.
  • Readability: JSON is human-readable and easier to understand, which can simplify data analysis and troubleshooting.
  • Compatibility with NoSQL Databases: JSON format is commonly used in NoSQL databases, facilitating easy data migration and storage.

Prerequisites

Before we start, ensure you have the following:

  • Visual Studio or any C# development IDE installed.
  • .NET Framework or .NET Core installed.
  • Spire.XLS package installed for handling Excel files.
  • Newtonsoft.Json package installed for handling JSON serialization and deserialization.

Installing Required Packages

You can install the required packages using NuGet Package Manager in Visual Studio:

Install-Package Spire.XLS
Install-Package Newtonsoft.Json

How to Convert Excel to JSON in C# .NET (Step-by-Step)

Exporting Excel files to JSON format in C# involves extracting data from Excel spreadsheets and transforming it into a structured JSON string. This process is particularly useful for applications that require data interchange between web services or databases. Below are detailed steps to guide you through the conversion process.

Steps to Export Excel to JSON

  1. Load the Excel File:
    • Begin by creating a Workbook object that will hold the Excel file's content using the Spire.XLS library. Load the Excel file into this object.
  2. Access the Desired Worksheet:
    • Identify and access the specific worksheet from which you want to extract data. This is done by referencing the appropriate index of the Worksheets collection.
  3. Export to DataTable:
    • Utilize the ExportDataTable() method to convert the worksheet's content into a DataTable. This provides a structured representation of the data, making it easier to manipulate.
  4. Serialize to JSON:
    • Use the Newtonsoft.Json library to serialize the DataTable into a JSON string. This step involves converting the structured data into a JSON format, which is human-readable and suitable for web applications.
  5. Save the JSON to a File:
    • Finally, write the generated JSON string to a file. This allows for easy access and reuse of the data in future applications or processes.

Complete Code Example: Excel to JSON

Here’s a complete code example demonstrating the process:

using Newtonsoft.Json;
using Spire.Xls;
using System.Data;
using System.IO;

namespace ConvertExcelToJSON
{
    class Program
    {        
        static void Main(string[] args)
        {
            // Path to the Excel file
            string excelFilePath = @"Sample.xlsx";

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

            // Load the Excel file
            workbook.LoadFromFile(excelFilePath);

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

            // Export the worksheet content to a DataTable
            DataTable dataTable = worksheet.ExportDataTable();

            // Convert the DataTable to a JSON string
            string jsonResult = JsonConvert.SerializeObject(dataTable, Formatting.Indented);

            // Save JSON string to a text file
            File.WriteAllText("output.txt", jsonResult);
        }
    }
}

Excel to JSON conversion example in C# using Spire.XLS

How to Convert JSON to Excel in C# .NET (Step-by-Step)

Importing JSON data into an Excel file is a valuable process, especially when you need to analyze or present data in a more user-friendly format. JSON is easy for humans to read and write, and easy for machines to parse and generate. However, for many users, Excel remains the preferred tool for data analysis, reporting, and visualization.

In the following steps, we will outline the process of importing JSON into Excel, enabling you to effectively utilize your JSON data within Excel for further analysis and reporting.

Steps to Import JSON into Excel

  1. Read the JSON String:
    • Start by reading the JSON data from a file or other sources. This could include API responses, local files, or even hardcoded strings for testing purposes.
  2. Deserialize to DataTable:
    • Use the Newtonsoft.Json library to deserialize the JSON string into a DataTable. This structured format makes it easy to manipulate data before inserting it into Excel.
  3. Create a New Excel Workbook:
    • Initialize a new Workbook instance using the Spire.XLS library. This workbook will serve as the container for your Excel data.
  4. Insert the DataTable into the Worksheet:
    • Use the InsertDataTable() method to transfer the contents of the DataTable into the first worksheet of the workbook. This method allows you to include column headers and organize the data neatly.
  5. Apply Optional Formatting:
    • Enhance the visual appeal of your Excel file by applying formatting to headers and data cells. This step involves defining styles for fonts, background colors, and borders, making the data easier to read.
  6. Save the Workbook:
    • Finally, save the populated workbook as an Excel file. Choose an appropriate file format (e.g., .xlsx) to ensure compatibility with modern Excel versions.

Complete Code Example: JSON to Excel

Here’s a complete code snippet demonstrating the conversion process:

using Newtonsoft.Json;
using Spire.Xls;
using System.Data;
using System.Drawing;

namespace ConvertJSONToExcel
{
    class Program
    {        
        static void Main(string[] args)
        {
            // Sample JSON data
            string json = @"
        [
            {""Name"":""John Smith"",""Age"":30,""Department"":""Sales"",""StartDate"":""2020-05-12"",""FullTime"":true},
            {""Name"":""Jane Doe"",""Age"":25,""Department"":""Marketing"",""StartDate"":""2021-09-01"",""FullTime"":false},
            {""Name"":""Michael Lee"",""Age"":40,""Department"":""IT"",""StartDate"":""2018-03-15"",""FullTime"":true},
            {""Name"":""Emily Davis"",""Age"":35,""Department"":""Finance"",""StartDate"":""2019-07-20"",""FullTime"":true}
        ]";

            // Deserialize JSON into DataTable
            DataTable dataTable = JsonConvert.DeserializeObject<DataTable>(json);

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

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

            // Insert DataTable into worksheet with column headers
            worksheet.InsertDataTable(dataTable, true, 1, 1);

            // (Optional) Applying formatting to Excel data
            // Set style for heading row
            CellStyle headerStyle = workbook.Styles.Add("HeaderStyle");
            headerStyle.Font.IsBold = true;
            headerStyle.Font.Size = 12;
            headerStyle.Font.Color = Color.White;
            headerStyle.HorizontalAlignment = HorizontalAlignType.Center;
            headerStyle.VerticalAlignment = VerticalAlignType.Center;
            headerStyle.Color = Color.DarkBlue;

            int colCount = dataTable.Columns.Count;
            for (int c = 1; c <= colCount; c++)
            {
                worksheet.Range[1, c].CellStyleName = "HeaderStyle";
            }

            // Set style for data cells
            CellStyle dataStyle = workbook.Styles.Add("DataStyle");
            dataStyle.HorizontalAlignment = HorizontalAlignType.Center;
            dataStyle.VerticalAlignment = VerticalAlignType.Center;
            dataStyle.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
            dataStyle.Borders[BordersLineType.EdgeRight].LineStyle = LineStyleType.Thin;
            dataStyle.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin;
            dataStyle.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;

            int rowCount = dataTable.Rows.Count;
            worksheet.Range[2, 1, rowCount + 1, colCount].CellStyleName = "DataStyle";

            // Auto-fit column widths
            worksheet.AllocatedRange.AutoFitColumns();

            // Save Excel file
            workbook.SaveToFile("output.xlsx", ExcelVersion.Version2013);
            // Release resources
            workbook.Dispose();
        }
    }
}

JSON to Excel conversion example in C# using Spire.XLS

Tips and Best Practices

When converting between Excel and JSON, following best practices can help ensure data integrity and usability. Here are some key tips to keep in mind:

  • Validate Data Types: Ensure that data types (e.g., dates, numbers) are correctly formatted to avoid issues during conversion.
  • Handle Empty Cells: Decide how to treat empty cells (e.g., convert to null or omit) to maintain data integrity.
  • Use Consistent Naming Conventions: Standardize column names in Excel for clear and consistent JSON keys.
  • Test Thoroughly: Always test the conversion processes to ensure valid JSON output and accurate Excel representation.
  • Include Headers: When converting JSON to Excel, always insert headers for improved readability and usability.

Conclusion

Converting Excel to JSON and JSON to Excel is a common but critical operation in modern C# development, especially for applications involving data exchange and API integration. Using Spire.XLS together with Newtonsoft.Json simplifies this process with intuitive APIs and robust functionality.

This guide has walked you through every step—from installing necessary packages to implementing complete converters—with clear explanations and sample code. With these tools and knowledge, you can confidently integrate Excel-JSON conversion into your applications, improving flexibility and interoperability.

Further Reading

FAQs

Q1: How to convert multiple worksheets to JSON at once?

You can iterate through the Workbook.Worksheets collection and export each worksheet’s data individually, supporting batch Excel to JSON conversion.

Q2: How to customize JSON output formatting?

JsonConvert.SerializeObject allows you to set indentation, camelCase naming, or ignore null values. You can also use custom converters for more control.

Q3: How to improve readability when converting JSON to Excel?

Keep column headers, set alignment, apply borders and styles to generate a clear and easy-to-read Excel report.

Q4: Is this method compatible with .NET Core?

Yes, it is fully compatible. Both Spire.XLS and Newtonsoft.Json support .NET Core and .NET Framework, making it usable in various C# projects.

Markdown to PDF and Excel Conversion Using C#

Markdown is a lightweight markup language widely used for writing formatted text using simple plain syntax. Favored by developers, writers, and technical content creators for its readability and ease of use, Markdown is perfect for drafting documents, notes, and technical content. However, Markdown files (.md) often need to be converted into other formats such as PDF for official distribution or Excel for data analysis and reporting.

In this comprehensive guide, you will learn how to convert Markdown files to PDF and Excel using C# and Spire.XLS for .NET — a powerful and easy-to-use library that supports direct Markdown loading and exporting to multiple formats. Whether you want to generate polished PDF documents or structured Excel spreadsheets, this tutorial covers everything you need.

Table of Contents

Why Convert Markdown to PDF and Excel?

Markdown is great for writing, but it has limitations when sharing or processing documents:

  • PDF files provide a fixed-layout, platform-independent format ideal for sharing polished reports, manuals, or official documentation. PDFs maintain the original style and layout regardless of device or software.
  • Excel files are essential when Markdown contains tabular data that you want to analyze, manipulate, or integrate into business processes. Converting Markdown tables to Excel spreadsheets lets you utilize formulas, filters, charts, and data tools effectively.

By converting Markdown to these formats programmatically in C#, you can automate documentation workflows, batch-process files, and integrate with other .NET applications.

Prerequisites (Library & Environment Setup)

Before you start converting Markdown files, ensure your development environment meets the following requirements:

  • .NET Framework or .NET Core installed.
  • Spire.XLS for .NET: A comprehensive Excel library that supports loading Markdown and exporting to PDF and Excel formats.

Install Spire.XLS via NuGet

You can easily install Spire.XLS in your C# project via NuGet by opening the NuGet Package Manager and executing the following command:

Install-Package Spire.XLS

This package provides all the necessary classes and methods to load Markdown and export documents without relying on Microsoft Office automation.

How to Convert Markdown to PDF in C# (Step-by-Step with Code)

To convert a Markdown file to PDF in C#, follow the steps below:

Step 1: Load the Markdown File

Create a new instance of the Workbook class and load your Markdown file:

Workbook workbook = new Workbook();
workbook.LoadFromMarkdown("test.md");

This method parses the Markdown content, including text and tables, into an Excel workbook structure that Spire.XLS can manipulate.

Step 2: Customize Conversion Settings (Optional)

After loading the Markdown file, you can apply conversion settings to ensure the PDF output retains a clean and readable layout. For example, enabling the SheetFitToPage option ensures that the entire Markdown content fits within a single PDF page.

workbook.ConverterSetting.SheetFitToPage = true;

Step 3: Export as PDF

Save the workbook as a PDF file:

workbook.SaveToFile("output.pdf", FileFormat.PDF);

This generates a well-formatted PDF document preserving the Markdown layout and styling suitable for printing or sharing.

PDF output generated from Markdown file using Spire.XLS in C#

How to Convert Markdown to Excel in C# (Step-by-Step with Code)

After loading the Markdown file into the workbook, you can also export it to an Excel spreadsheet format:

workbook.SaveToFile("output.xls", ExcelVersion.Version97to2003);

You may also choose other Excel versions depending on your target compatibility:

workbook.SaveToFile("output.xlsx", ExcelVersion.Version2016);

The exported Excel file retains tables and structured data from your Markdown, allowing further analysis or manipulation.

Excel spreadsheet generated from Markdown content using C# and Spire.XLS

Complete C# Code Example: Convert Markdown to PDF and Excel in One Go

Here’s the full example combining both PDF and Excel exports in a single run:

using Spire.Xls;

namespace MarkdownToPdfAndExcel
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Initialize the workbook
            Workbook workbook = new Workbook();

            // Load Markdown content
            workbook.LoadFromMarkdown("test.md");

            // Fit the sheet data to one page (optional)
            workbook.ConverterSetting.SheetFitToPage = true;

            // Export to PDF
            workbook.SaveToFile("output.pdf", FileFormat.PDF);

            // Export to xls (Excel 97-2003 format) 
            workbook.SaveToFile("output.xls", ExcelVersion.Version97to2003);

            // Export to xlsx (Excel 2016 format)
            workbook.SaveToFile("output.xlsx", ExcelVersion.Version2016);

            workbook.Dispose();
        }
    }
}

Best Practices for Markdown Conversion

  • Use UTF-8 Encoding: Ensure your Markdown files use UTF-8 encoding, especially if they contain special or non-English characters. This ensures proper character display and avoids encoding errors during conversion.
  • Maintain Clean and Well-Formatted Markdown Tables: To achieve accurate and reliable Excel conversions, structure your Markdown tables carefully. Use consistent pipe (|) delimiters and avoid malformed syntax to preserve table integrity in the output spreadsheet.
  • Load Once, Export Multiple Formats: For optimal performance, load your Markdown content into the Workbook object a single time, then export it to various formats such as PDF and Excel. This reduces processing overhead and speeds up batch conversions.
  • Assess Markdown Complexity: Spire.XLS effectively supports basic Markdown syntax, such as headings and tables. However, advanced features like embedded images or code blocks with syntax highlighting might require pre-processing or conversion through intermediate formats like HTML.
  • Choose Appropriate Excel Export Versions: To maximize compatibility with your users’ software, select the Excel file format based on their environment. For example, use the .xls format for legacy Excel 97–2003 users, and .xlsx for Excel 2007 and later versions to ensure broad accessibility and full feature support.

Conclusion

Converting Markdown to PDF and Excel using C# and Spire.XLS is a fast, flexible, and reliable approach to modern document workflows. With minimal code, developers can automate the transformation of lightweight Markdown into professional PDFs for distribution and Excel spreadsheets for business analytics.

This method streamlines technical writing, reporting, and data handling tasks within .NET applications and enables seamless integration with other business processes.

FAQs

Q1: Can I batch convert multiple Markdown files using Spire.XLS in C#?

A1: Yes, you can loop through multiple Markdown files, load each one using Spire.XLS, and export them individually to PDF or Excel formats within the same C# project.

Q2: Is Microsoft Office required to use Spire.XLS for Markdown conversion?

A2: No, Spire.XLS is a standalone library and does not rely on Microsoft Office or Excel being installed on the machine.

Q3: Is Spire.XLS free to use?

A3: Spire.XLS offers a free version with some limitations. A commercial license is available for full features.

Get a Free License

To fully experience the capabilities of Spire.XLS for .NET without any evaluation limitations, you can request a free 30-day trial license.

How to Convert TXT to Excel in C#

2025-05-15 08:33:11 Written by Administrator

In data processing and management scenarios, efficiently transforming raw text (TXT) files into structured Excel spreadsheets is a common requirement. For developers who are automating reports or processing log files, converting TXT to Excel using C# streamlines data organization and analysis. This guide explores how to achieve this using Spire.XLS for .NET, a powerful library designed to handle Excel XLS or XLSX files without requiring Microsoft Office.

Why Convert TXT to Excel Programmatically?

Text files are simple but lack the analytical power of Excel. Key advantages of converting TXT to XLS or XLSX format include:

  • Automation: Process large or recurring files without manual intervention.
  • Data Structuring: Organize raw text into rows, columns, and sheets.
  • Advanced Features: Leverage Excel formulas, charts, and pivot tables.
  • Integration: Embed conversion feature into .NET applications or APIs.

How to Convert Text Files to Excel in C# (Step-by-Step Guide)

Install Spire.XLS for .NET

Spire.XLS for .NET is a professional Excel document processing component, provides efficient and convenient APIs that allow developers to achieve TXT to Excel conversion through simple code.

Before getting started, you can choose one of these methods to install the library:

Method 1: NuGet Package Manager

  • Open your project in Visual Studio.
  • Right-click on the project in the Solution Explorer and select "Manage NuGet Packages."
  • Search for "Spire.XLS" and click "Install".

Method 2: Package Manager Console

  • Go to "Tools > NuGet Package Manager > Package Manager Console."
  • Run the following command in the console:
    PM> Install-Package Spire.XLS

Method 3: Manual Installation with DLL Files

  • Visit the Spire.XLS Download Page and get the latest version.
  • Extract the files and then add the Spire.Xls.dll to your project.

Import a Text File into Excel Using C#

Follow the below steps to write the data in a txt file into an Excel worksheet:

  • Read TXT File: use the File.ReadAllLines() method to read all lines in a text file and returns them as an array of strings.
  • Parse each line:
    • Use the string.Trim() method to remove the leading/trailing whitespaces.
    • Use the string.Split() method to split the data based on specified delimiters.
    • Add the split text data to a list.
  • Create a Workbook instance and get a worksheet
  • Write Data to specified cells:
    • Iterate through the rows and columns in the list.
    • Assign the data in the list to the corresponding Excel cells through the Worksheet.Range[].Value property.
  • Save the Excel File.

Code Example:

  • C#
using Spire.Xls;
using System.IO;
using System.Collections.Generic;

class TxtToExcelConverter
{
    static void Main()
    {
        // Open a text file and read all lines in it
        string[] lines = File.ReadAllLines("Data.txt");

        // Create a list to store the data in text file
        List data = new List();

        // Split data into rows and columns and add to the list
        foreach (string line in lines)
        {
            data.Add(line.Trim().Split('\t')); // Adjust delimiter as needed
        }

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

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

        // Iterate through the rows and columns in the data list
        for (int row = 0; row < data.Count; row++)
        {
            for (int col = 0; col < data[row].Length; col++)
            {
                // Write the text data in specified cells
                sheet.Range[row + 1, col + 1].Value = data[row][col];

                // Set the header row to Bold
                sheet.Range[1, col + 1].Style.Font.IsBold = true;
            }
        }

        // Autofit columns
        sheet.AllocatedRange.AutoFitColumns();

        // Save the Excel file
        workbook.SaveToFile("TXTtoExcel.xlsx", ExcelVersion.Version2016);
        workbook.Dispose();
    }
}

Result:

Import a text file to an Excel file.

Pro Tips for TXT to Excel Conversion

  • Handling Different Delimiters:

If your TXT file uses a different delimiter (e.g., space, comma, semicolon), modify the parameter of the Split(params char[] separator) method.

  • Format Cells:

After a text file being converted to an Excel file, you can take advantage of the Spire.XLS library’s rich features to format cells, such as setting the background colors, adding cell borders, applying number formats, etc.

Conclusion

By following this step-by-step guide, you can efficiently transform unstructured text data into organized Excel spreadsheets, which is ideal for data analysis, reporting, and management. Remember to optimize your implementation for your specific delimiters and leverage Spire.XLS's advanced features for complex conversion scenarios.

Get a Free License

To fully experience the capabilities of Spire.XLS for .NET without any evaluation limitations, you can request a free 30-day trial license.

Microsoft Excel is a powerful tool for data management; however, its proprietary format can pose challenges for sharing and integrating data into web workflows. In contrast, Markdown is a lightweight and widely supported markup language that simplifies text formatting for documentation, wikis, and platforms like GitHub.

By converting Excel files to Markdown, you can seamlessly incorporate structured data into technical documents, READMEs, and static websites. This article will guide you through the steps to programmatically convert Excel files to Markdown format using C# and the Spire.XLS for .NET library.

Install Spire.XLS for .NET

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

PM> Install-Package Spire.XLS

Convert an Excel XLS or XLSX File to Markdown in C#

Developers can effortlessly convert Excel XLS or XLSX files to Markdown files by using the Workbook.SaveToMarkdown() method provided by Spire.XLS for .NET. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load a sample Excel XLS or XLSX file into the Workbook object using the Workbook.LoadFromFile() method.
  • Save the Excel file as a Markdown file using the Workbook.SaveToMarkdown() method.
  • C#
using Spire.Xls;

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

            // Save the Excel file as a Markdown file
            workbook.SaveToMarkdown("output.md");
            // Release the resources used by the Workbook object
            workbook.Dispose();
        }
    }
}

Convert Excel to Markdown in C#

Get a Free License

To fully experience the capabilities of Spire.XLS for .NET without any evaluation limitations, you can request a free 30-day trial license.

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.

This article demonstrates how to convert shapes and SmartArt graphics in Excel to Image in C# using Spire.XLS for .NET.

The input Excel file:

Convert Shapes and SmartArt in Excel to Image in C#, VB.NET

C#
using Spire.Xls;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;

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

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

            //Create a SaveShapeTypeOption object
            SaveShapeTypeOption shapelist = new SaveShapeTypeOption();
            //Save shapes and SmartArt graphics in the worksheet to images
            List<Bitmap> images = sheet.SaveShapesToImage(shapelist);

            //Save images to file
            int index = 0;
            foreach (Image img in images)
            {
                img.Save("Image/" + "toImage" + index + ".Png", ImageFormat.Png);
                index++;
            }
        }
    }
}
VB.NET
Imports Spire.Xls
Imports System.Collections.Generic
Imports System.Drawing.Imaging

Namespace Convert_Shapes_and_SmartArt_to_Image
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Workbook object
            Dim workbook As Workbook = New Workbook()
            'Load the Excel file
            workbook.LoadFromFile("Sample.xlsx")

            'Get the first worksheet
            Dim sheet As Worksheet = workbook.Worksheets(0)

            'Create a SaveShapeTypeOption object
            Dim shapelist As SaveShapeTypeOption = New SaveShapeTypeOption()
            'Save shapes and SmartArt graphics in the worksheet to images
            Dim images As List(Of Bitmap) = sheet.SaveShapesToImage(shapelist)

            'Save images to file
            Dim index As Integer = 0

            For Each img As Image In images
                img.Save("Image/" & "toImage" & index & ".Png", ImageFormat.Png)
                index += 1
            Next
        End Sub
    End Class
End Namespace

Converted images:

Convert Shapes and SmartArt in Excel to Image in C#, VB.NET

C#: Convert HTML to Excel

2024-08-09 08:19:00 Written by Koohji

HTML (HyperText Markup Language) is primarily used for structuring content on web pages. While it excels at presenting information visually on the web, it lacks the robust analytical capabilities and data manipulation features found in spreadsheet software like Excel. By converting HTML data to Excel, users can leverage Excel's advanced functionalities like formulas, charts, tables, and macros to organize and analyze data efficiently. In this article, we will explain how to convert HTML to 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

Convert HTML to Excel in C#

Spire.XLS for .NET offers the Workbook.LoadFromHtml() method to load an HTML file. After loading the HTML file, you can easily save it in Excel format using the Workbook.SaveToFile() method. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an HTML file using the Workbook.LoadFromHtml() method.
  • Save the HTML file in Excel format using the Workbook.SaveToFile() method.
  • C#
using Spire.Xls;

namespace ConvertHtmlToExcel
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Specify the input HTML file path
            string filePath = @"C:\Users\Administrator\Desktop\Sample.html";

            // Create an object of the workbook class
            Workbook workbook = new Workbook();

            // Load the HTML file
            workbook.LoadFromHtml(filePath);

            // Save the HTML file in Excel XLSX format
            string result = @"C:\Users\Administrator\Desktop\ToExcel.xlsx";
            workbook.SaveToFile(result, ExcelVersion.Version2013);

            workbook.Dispose();
        }
    }
}

C#: Convert HTML to Excel

Insert HTML String to Excel in C#

In addition to converting HTML files to Excel, Spire.XLS for .NET also allows you to insert HTML strings into Excel cells by using the CellRange.HtmlString property. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Get a specific worksheet by its index (0-based) using the Workbook.Worksheets[index] property.
  • Get the cell that you want to add an HTML string to using the Worksheet.Range[] property.
  • Add an HTML sting to the cell using the CellRange.HtmlString property.
  • Save the resulting workbook to a new file using the Workbook.SaveToFile() method.
  • C#
using Spire.Xls;

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

            // Specify the HTML string
            string htmlCode = "<p><font size='12'>This is a <b>paragraph</b> with <span style='color: red;'>colored text</span>.</font></p>";

            // Get the cell that you want to add the HTML string to
            CellRange range = sheet.Range["A1"];
            // Add the HTML string to the cell
            range.HtmlString = htmlCode;

            // Auto-adjust the width of the first column based on its content
            sheet.AutoFitColumn(1);

            // Save the resulting workbook to a new file
            string result = @"C:\Users\Administrator\Desktop\InsertHtmlStringIntoCell.xlsx";
            workbook.SaveToFile(result, ExcelVersion.Version2013);

            workbook.Dispose();
        }
    }
}

C#: Convert HTML to Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

A ChartSheet represents a chart sheet. It is a worksheet that contains only a chart. This article will demonstrate how to convert a chart sheet to SVG stream by using Spire.XLS.

Firstly, view the sample Excel worksheets with two chart sheets.

How to save Excel chart sheet to SVG in C#

Convert all the chart sheets to SVG stream:

using System.Drawing.Imaging;
using System.IO;
namespace Convert
{
    class Program
    {
        static void Main(string[] args)
        {
            //load the document from file
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");

            //call ToSVGStream(Stream stream) method to save each chart sheet to SVG stream 
            for (int i = 0; i < workbook.Chartsheets.Count; i++)
            {
                FileStream fs = new FileStream(string.Format("chartsheet-{0}.svg", i), FileMode.Create);
                workbook.Chartsheets[i].ToSVGStream(fs);
                fs.Flush();
                fs.Close();
            }


        }
    }
}

Effective screenshot of the two chart sheets to SVG.

How to save Excel chart sheet to SVG in C#

using System.Drawing.Imaging;
using System.IO;
namespace Convert
{
    class Program
    {
        static void Main(string[] args)
        {
            //load the document from file
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");

            //get the second chartsheet by name
            ChartSheet cs = workbook.GetChartSheetByName("Chart2");

            //save to SVG stream
            FileStream fs = new FileStream(string.Format("chart2.svg"), FileMode.Create);
            cs.ToSVGStream(fs);
            fs.Flush();
            fs.Close();


        }
    }
}

How to save Excel chart sheet to SVG in C#

Charts are commonly used in Microsoft Excel files to visualize numeric data. In some cases, you may need to save the charts in an Excel file as images in order to use them in other programs or other files such as PDFs and PowerPoint presentations. In this article, we will demonstrate how to convert charts in Excel to images in C# and VB.NET 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

Convert a Specific Chart in an Excel Worksheet to Image in C# and VB.NET

Spire.XLS provides the Workbook.SaveChartAsImage(Worksheet worksheet, int chartIndex) method which enables you to convert a specific chart in a worksheet as image. The following are the detailed steps:

  • Initialize an instance of the Workbook class.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet by its index through Workbook.Worksheets[int worksheetIndex] property.
  • Save a specific chart in the worksheet as image using Workbook.SaveChartAsImage(Worksheet worksheet, int chartIndex) method.
  • Save the image to a PNG file.
  • C#
  • VB.NET
using Spire.Xls;
using System.Drawing;
using System.Drawing.Imaging;

namespace ConvertAExcelChartToImage
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Workbook class
            Workbook workbook = new Workbook();
            //Load a sample Excel file
            workbook.LoadFromFile("Charts.xlsx");

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

            //Save the first chart in the first worksheet as image
            Image image = workbook.SaveChartAsImage(sheet, 0);
            //Save the image to .png file
            image.Save(@"output\chart.png", ImageFormat.Png);
        }
    }
}

C#/VB.NET: Convert Charts in Excel to Images

Convert All Charts in an Excel Worksheet to Images in C# and VB.NET

To convert all charts in an Excel worksheet to images, you can use the Workbook.SaveChartAsImage(Worksheet worksheet) method. The following are the detailed steps:

  • Initialize an instance of the Workbook class.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet by its index through Workbook.Worksheets[int worksheetIndex] property.
  • Save all charts in the worksheet as images using Workbook.SaveChartAsImage(Worksheet worksheet) method.
  • Save the images to PNG files.
  • C#
  • VB.NET
using Spire.Xls;
using System.Drawing;
using System.Drawing.Imaging;

namespace ConvertAllExcelChartsToImages
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Workbook class
            Workbook workbook = new Workbook();
            //Load a sample Excel file
            workbook.LoadFromFile("Charts.xlsx");

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

            //Save charts in the first worksheet as images
            Image[] imgs = workbook.SaveChartAsImage(sheet);

            //Save the images to png files
            for (int i = 0; i < imgs.Length; i++)
            {
                imgs[i].Save(string.Format(@"output\chart-{0}.png", i), ImageFormat.Png);
            }
        }
    }
}

C#/VB.NET: Convert Charts in Excel to Images

Convert a Chart Sheet to Image in Excel in C# and VB.NET

You can use the Workbook.SaveChartAsImage(ChartSheet chartSheet) method to convert a chart sheet in Excel to image. The following are the detailed steps:

  • Initialize an instance of the Workbook class.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specific chart sheet by its index through Workbook.Chartsheets[int chartSheetIndex] property.
  • Save the chart sheet as image using Workbook.SaveChartAsImage(ChartSheet chartSheet) method.
  • Save the image to .png file.
  • C#
  • VB.NET
using Spire.Xls;
using System.Drawing;
using System.Drawing.Imaging;

namespace ConvertExcelChartSheetToImage
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Workbook class
            Workbook workbook = new Workbook();
            //Load a sample Excel file
            workbook.LoadFromFile("ChartSheet.xlsx");

            //Get the first chart sheet
            ChartSheet chartSheet = workbook.Chartsheets[0];

            //Save the first chart sheet as image
            Image image = workbook.SaveChartAsImage(chartSheet);
            //Save the image to .png file
            image.Save(@"output\chartSheet.png", ImageFormat.Png);            
        }
    }
}

C#/VB.NET: Convert Charts in Excel to Images

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Page 1 of 3
page 1