Convert HTML to Plain Text using C#

In .NET development, converting HTML to plain text is a common task, whether you need to extract content from web pages, process HTML emails, or generate lightweight text reports. However, HTML’s rich formatting, tags, and structural elements can complicate workflows that require clean, unformatted text. This is why using C# for HTML to text conversion becomes essential.

Spire.Doc for .NET simplifies this process: it’s a robust library for document manipulation that natively supports loading HTML files/strings and converting them to clean plain text. This guide will explore how to convert HTML to plain text in C# using the library, including detailed breakdowns of two core scenarios: converting HTML strings (in-memory content) and HTML files (disk-based content).


Why Use Spire.Doc for HTML to Text Conversion?

Spire.Doc is a .NET document processing library that stands out for HTML-to-text conversion due to:

  • Simplified Code: Minimal lines of code to handle even complex HTML.
  • Structure Preservation: Maintains logical formatting (line breaks, list indentation) in the output text.
  • Special Character Support: Automatically converts HTML entities to their plain text equivalents.
  • Lightweight: Avoids heavy dependencies, making it suitable for both desktop and web applications

Installing Spire.Doc

Spire.Doc is available via NuGet, the easiest way to manage dependencies:

  1. In Visual Studio, right-click your project > Manage NuGet Packages.
  2. Search for Spire.Doc and install the latest stable version.
  3. Alternatively, use the Package Manager Console:
Install-Package Spire.Doc

After installing, you can dive into the C# code to extract text from HTML.


Convert HTML Strings to Text in C#

This example renders an HTML string into a Document object, then uses SaveToFile() to save it as a plain text file.

using Spire.Doc;
using Spire.Doc.Documents;

namespace HtmlToTextSaver
{
    class Program
    {
        static void Main(string[] args)
        {
            // Define HTML content
            string htmlContent = @"
                    <html>
                        <body>
                            <h1>Sample HTML Content</h1>
                            <p>This is a paragraph with <strong>bold</strong> and <em>italic</em> text.</p>
                            <p>Another line with a <a href='https://example.com'>link</a>.</p>
                            <ul>
                                <li>List item 1</li>
                                <li>List item 2 (with <em>italic</em> text)</li>
                            </ul>
                            <p>Special characters: &copy; &amp; &reg;</p>
                        </body>
                    </html>";

            // Create a Document object
            Document doc = new Document();
            // Add a section to hold content
            Section section = doc.AddSection();
            // Add a paragraph
            Paragraph paragraph = section.AddParagraph();
            // Render HTML into the paragraph
            paragraph.AppendHTML(htmlContent); 

            // Save as plain text
            doc.SaveToFile("HtmlStringtoText.txt", FileFormat.Txt);
        }
    }
}

How It Works:

  • HTML String Definition: We start with a sample HTML string containing headings, paragraphs, formatting tags (<strong>, <em>), links, lists, and special characters.
  • Document Setup: A Document object is created to manage the content, with a Section and Paragraph to structure the HTML rendering.
  • HTML RenderingAppendHTML() parses the HTML string and converts it into the document's internal structure, preserving content hierarchy.
  • Text ConversionSaveToFile() with FileFormat.Txt converts the rendered content to plain text, stripping HTML tags while retaining readable structure.

Output:

Convert an HTML string to plain text using C#

Extended reading: Parse or Read HTML in C#


Convert HTML File to Text in C#

This example directly loads an HTML file and converts it to text. Ideal for batch processing or working with pre-existing HTML documents (e.g., downloaded web pages, local templates).

using Spire.Doc;
using Spire.Doc.Documents;

namespace HtmlToText
{
    class Program
    {
        static void Main()
        {
            // Create a Document object
            Document doc = new Document();

            // Load an HTML file
            doc.LoadFromFile("sample.html", FileFormat.Html, XHTMLValidationType.None);

            // Convert HTML to plain text
            doc.SaveToFile("HTMLtoText.txt", FileFormat.Txt);
            doc.Dispose();
        }
    }
}

How It Works:

  • Document Initialization: A Document object is created to handle the file operations.
  • HTML File LoadingLoadFromFile() imports the HTML file, with FileFormat.Html specifying the input type. XHTMLValidationType.None ensures compatibility with non-strict HTML.
  • Text ConversionSaveToFile() with FileFormat.Txt converts the loaded HTML content to plain text.

Convert an HTML file to plain text using C#

To preserve the original formatting and style, you can refer to the C# tutorial to convert the HTML file to Word.


FAQs

Q1: Can Spire.Doc process malformed HTML?

A: Yes. Spire.Doc includes built-in tolerance for malformed HTML, but you may need to disable strict validation to ensure proper parsing.

When loading HTML files, use XHTMLValidationType.None (as shown in the guide) to skip strict XHTML checks:

doc.LoadFromFile("malformed.html", FileFormat.Html, XHTMLValidationType.None);

This setting tells Spire.Doc to parse the HTML like a web browser (which automatically corrects minor issues like unclosed <p> or <li> tags) instead of rejecting non-compliant content.

Q2: Can I extract specific elements from HTML (like only paragraphs or headings)?

A: Yes, after loading the HTML into a Document object, you can access specific elements through the object model (like paragraphs, tables, etc.) and extract text from only those specific elements rather than the entire document.

Q3: Can I convert HTML to other formats besides plain text using Spire.Doc?

A: Yes, Spire.Doc supports conversion to multiple formats, including Word DOC/DOCX, PDF, image, RTF, and more, making it a versatile document processing solution.

Q4: Does Spire.Doc work with .NET Core/.NET 5+?

A: Spire.Doc fully supports .NET Core, .NET 5/6/7/8, and .NET Framework 4.0+. There’s no difference in functionality across these frameworks, which means you can use the same code (e.g., DocumentAppendHTML()SaveToFile()) regardless of which .NET runtime you’re targeting.


Conclusion

Converting HTML to text in C# is straightforward with the Spire.Doc library. Whether you’re working with HTML strings or files, Spire.Doc simplifies the process by handling HTML parsing, structure preservation, and text conversion. By following the examples in this guide, you can seamlessly integrate HTML-to-text conversion into your C# applications.

You can request a free 30-day trial license here to unlock full functionality and remove limitations of the Spire.Doc library.

How to Parse HTML in C#

The need to efficiently parse HTML in C# is a common requirement for many development tasks, from web scraping, data extraction to content automation. While .NET offers built-in tools (e.g., HtmlAgilityPack), Spire.Doc simplifies HTML parsing in C# with its intuitive object model and seamless integration.

This guide explores how to leverage Spire.Doc for .NET to parse HTML, including loading HTML from various sources, navigating document structure, and extracting critical data.


Setting Up Spire.Doc

The easiest way to integrate the C# HTML parser library into your project is via NuGet:

  • Open your project in Visual Studio.
  • Right-click the project in the Solution Explorer → Select Manage NuGet Packages.
  • In the NuGet Package Manager, search for Spire.Doc.
  • Select the latest stable version and click Install.

Alternatively, download the library directly from the E-iceblue website, extract the ZIP file, and reference Spire.Doc.dll in your project.


How Spire.Doc Parses HTML

Spire.Doc converts HTML into a structured object model, where elements like <p>, <a>, and <table> are mapped to classes you can programmatically access. Key components include:

  • Document: Acts as the container for parsed HTML content.
  • Section: Represents a block of content (similar to HTML’s <body> or <div> sections).
  • Paragraph: Maps to HTML block elements like <p>, <h1>, or <li>.
  • DocumentObject: Base class for all elements within a Paragraph (images, links, etc.).

This model ensures that HTML structures are preserved and accessible via intuitive C# properties and methods.


How to Load and Parse HTML Content

Spire.Doc supports parsing HTML from strings, local files, or even remote URLs (when combined with HTTP clients). Below are detailed examples for each scenario.

Parse an HTML String in C#

Parse an HTML string (e.g., from a web API or database) into Spire.Doc’s object model for inspection.

using Spire.Doc;
using Spire.Doc.Documents;

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

            // Add a section to act as a container
            Section section = doc.AddSection();
            // Add a paragraph
            Paragraph para = section.AddParagraph();

            // Define HTML content to parse
            string htmlContent = @"
                <h2>Sample HTML String</h2>
                <p>This is a paragraph with <strong>bold text</strong> and a <a href='https://www.e-iceblue.com/'>link</a>.</p>
                <ul>
                    <li>List item 1</li>
                    <li>List item 2</li>
                </ul>
            ";

            // Parse the HTML string into the paragraph
            para.AppendHTML(htmlContent);

            // Print all paragraph text
            Console.WriteLine("Parsed HTML Content:");
            Console.WriteLine("---------------------");

            foreach (Paragraph paragraph in section.Paragraphs)
            {
                Console.WriteLine(paragraph.Text);
            }
        }
    }
}

In this code, the method AppendHTML() automatically converts HTML tags to corresponding Spire.Doc objects (e.g., <h1> → Heading1 style, <ul> → list paragraphs).

Output:

Parse an HTML string using C#

Pro Tip: You can also call the SaveToFile() method to convert the HTML string to Word in C#.

Parse an HTML File in C#

For HTML content stored in a file (e.g., downloaded web pages, static HTML reports), load it via LoadFromFile() and then analyze its structure (e.g., extracting headings, paragraphs).

using Spire.Doc;
using Spire.Doc.Documents;

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

            // Load an HTML file
            doc.LoadFromFile("sample.html", FileFormat.Html);

            // Traverse sections (HTML body blocks)
            foreach (Section section in doc.Sections)
            {
                Console.WriteLine($"Section {doc.Sections.IndexOf(section) + 1}:");
                Console.WriteLine("---------------------------------");

                // Traverse paragraphs in the section
                foreach (Paragraph para in section.Paragraphs)
                {
                    // Print paragraph text and style (e.g., heading level)
                    string styleName = para.StyleName;
                    Console.WriteLine($"[{styleName}] {para.Text}"+ "\n");
                }
                Console.WriteLine();
            }
        }
    }
}

This C# code example loads a local HTML file and then uses the Paragraph.StyleName and Paragraph.Text properties to extract content along with its styling information.

Output:

Load and parse an HTML file using C#

Spire.Doc’s object model allows you to interact with an HTML file just like you would with a Word document. In addition to extracting text content, you can also extract elements like links, tables from HTML.

Parse a URL in C#

To parse HTML from a web page, combine Spire.Doc with HttpClient to fetch the HTML content first, then parse it.

using Spire.Doc;
using Spire.Doc.Documents;

namespace HtmlUrlParsing
{
    class Program
    {
        // HttpClient instance for web requests
        private static readonly HttpClient httpClient = new HttpClient();

        static async Task Main(string[] args)
        {
            try
            {
                // Fetch HTML from a URL
                string url = "https://www.e-iceblue.com/privacypolicy.html";
                Console.WriteLine($"Fetching HTML from: {url}");
                string htmlContent = await FetchHtmlFromUrl(url);

                // Parse the fetched HTML
                Document doc = new Document();
                Section section = doc.AddSection();
                Paragraph paragraph = section.AddParagraph();
                paragraph.AppendHTML(htmlContent);

                // Extract key information
                Console.WriteLine("\nParsed Content Summary:");
                Console.WriteLine($"Sections: {doc.Sections.Count}");
                Console.WriteLine($"Paragraphs: {section.Paragraphs.Count}");
                Console.WriteLine("-------------------------------------------");

                // Extract all heading paragraphs
                foreach (Paragraph para in section.Paragraphs)
                {
                    if (para.StyleName.StartsWith("Heading"))
                    {
                        string headings = para.Text;
                        Console.WriteLine($"Headings: {headings}");
                    }
                }
                
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }

        // Helper method to fetch HTML from a URL
        private static async Task<string> FetchHtmlFromUrl(string url)
        {
            // Set a user-agent to avoid being blocked by servers
            httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64)");

            // Send GET request and return HTML content
            HttpResponseMessage response = await httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode(); // Throw on HTTP errors (4xx, 5xx)
            return await response.Content.ReadAsStringAsync();
        }
    }
}

This C# code combines web scraping (fetching HTML from a URL) with document parsing (using Spire.Doc) to extract structured information (like headings) from web content. It’s useful for scenarios like content analysis or web data extraction.

Output:

Parse HTML from a web URL using C#


Conclusion

Spire.Doc for .NET provides a comprehensive solution for reading HTML in C# applications. Whether you're working with HTML strings, local files, or even web URLs, this library streamlines the process with intuitive APIs and reliable performance. By following the examples outlined in this guide, you can efficiently integrate HTML parsing capabilities into your .NET projects.

To fully experience the capabilities of Spire.Doc for .NET, request a free 30-day trial license here.


Common Questions

Q1: Why use Spire.Doc for HTML parsing instead of HtmlAgilityPack?

A: Spire.Doc and HtmlAgilityPack serve different primary goals, so the choice depends on your needs:

  • HtmlAgilityPack: A lightweight library only for parsing and manipulating raw HTML (e.g., extracting tags, fixing invalid HTML). It does not handle document formatting or export to Word.
  • Spire.Doc: Designed for document manipulation first - it parses HTML and maps it directly to structured Word elements (sections, paragraphs, styles like headings/bold). This is critical if you need to:
    • Preserve HTML structure in an editable Word file.
    • Extract styled content (e.g., identify "Heading 1" vs. "Normal" text).
    • Export parsed HTML to RTF, TXT, PDF, etc.

Q2. How do I convert HTML to Text in C#

A: To convert an HTML file to plain text in C#, get its text content via the GetText() method and then write the result to a .txt file.

// Create a Document object
Document doc = new Document();

// Load an HTML file
doc.LoadFromFile("sample.html", FileFormat.Html);

// Get text from HTML
string text = doc.GetText();

// Write to a text file
File.WriteAllText("HTMLText.txt", text);

Q3: Can Spire.Doc handle malformed or incomplete HTML?

A: Spire.Doc has good error tolerance and can handle imperfect HTML to some extent. However, severely malformed HTML might cause parsing issues. For best results, ensure your HTML is well-formed or use HTML sanitization libraries before parsing with Spire.Doc.

Q3: Can I use Spire.Doc in ASP.NET Core applications?

A: Yes, Spire.Doc is fully compatible with ASP.NET Core applications. The installation and usage process is the same as in other .NET applications.

Step-by-step C# guide for Markdown to HTML conversion

Markdown (md) is a widely adopted lightweight markup language known for its simplicity and readability. Developers, technical writers, and content creators often use it for documentation, README files, blogs, and technical notes. While Markdown is easy to write and read in its raw form, displaying it on websites or integrating it into web applications requires HTML. Converting Markdown to HTML is therefore a fundamental task for developers working with content management systems, documentation pipelines, or web-based applications.

In this tutorial, you will learn how to convert Markdown to HTML in C#. The guide covers converting both Markdown strings and files to HTML, as well as batch processing multiple Markdown documents efficiently. By the end, you’ll have practical, ready-to-use examples that you can apply directly to real-world projects.

Table of Contents

Understanding Markdown and HTML: Key Differences and Use Cases

What is Markdown?

Markdown is a lightweight markup language that allows developers and writers to create structured documents using plain text. It uses straightforward syntax for headings, lists, links, images, code blocks, and more. Its readability in raw form makes it ideal for writing documentation, README files, technical blogs, and collaborative notes.

Example Markdown:

# Project Title

This is a **bold** statement.

- Feature 1

- Feature 2

What is HTML?

HTML (HyperText Markup Language) is the foundational language of the web. Unlike Markdown, HTML provides precise control over document structure, formatting, multimedia embedding, and web interactivity. While Markdown focuses on simplicity, HTML is indispensable for web pages and application content.

Example HTML Output:

<h1>Project Title</h1>
<p>This is a <strong>bold</strong> statement.</p>
<ul>
  <li>Feature 1</li>
  <li>Feature 2</li>
</ul>

Key Differences and Use Cases

Feature Markdown HTML
Complexity Simple, minimal syntax More detailed, verbose
Readability Readable in raw form Harder to read directly
Use Cases Documentation, readmes, blogs Websites, web apps, emails

Use Case Tip: Use Markdown for author-friendly writing, then convert it to HTML for web display, automated documentation pipelines, or content management systems.

C# Library for Markdown to HTML Conversion

For C# developers, one of the most practical libraries for Markdown-to-HTML conversion is Spire.Doc for .NET. This library offers robust document processing capabilities, supporting not only loading Markdown files and converting content to HTML, but also extending to other formats, such as Markdown to Word and PDF. With this flexibility, developers can easily choose the output format that best fits their project needs.

Key Features

  • Load Markdown files and convert to HTML
  • Preserve headings, lists, links, images, and other Markdown formatting in HTML output
  • Batch process multiple Markdown documents efficiently
  • Integrate seamlessly with .NET applications without requiring Microsoft Office
  • Compatible with .NET Framework and .NET Core

Installation

You can easily add the required library to your C# project in two ways:

  • Using NuGet (Recommended)
    Run the following command in your Package Manager Console:
    Install-Package Spire.Doc
    
    This method ensures that the library and its dependencies are automatically downloaded and integrated into your project.
  • Manual Installation
    Alternatively, you can download the library DLL and manually add it as a reference in your project. This approach is useful if you need offline installation or prefer direct control over the library files.

Tip: Using NuGet is generally recommended for faster setup and easier version management.

Convert a Markdown String to HTML in C# (Step-by-Step)

In many applications, Markdown content may be generated dynamically or stored in a database as a string. This section demonstrates how you can convert a Markdown string into a fully formatted HTML file using C#.

Steps to Convert a Markdown String to HTML

  • Prepare the Markdown string that you want to convert.
  • Save the Markdown string to a .md file with WriteAllText.
  • Load the Markdown file into a Document object using LoadFromFile with FileFormat.Markdown.
  • Save the document as an HTML file using SaveToFile with FileFormat.Html.

Example Code

using Spire.Doc;
using System;
using System.IO;

namespace MarkdownToHtml
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Define the markdown string
            string markdown = @"
# Welcome to C# Markdown Tutorial

This tutorial demonstrates **Markdown syntax** in a more detailed way.
Here is a [link](https://example.com).

## Features
- Headings, bold, and italic text
- Links and images
- Ordered and unordered lists
- Code blocks and inline code
- Blockquotes
- Tables
";
            // Define the file paths
            string markdownFilePath = "example.md"; // Path to save the Markdown file
            string outputHtmlPath = "output.html";   // Path to save the converted HTML file

            // Create a Markdown file from the markdown string
            File.WriteAllText(markdownFilePath, markdown);

            // Load the Markdown file
            Document document = new Document();
            document.LoadFromFile(markdownFilePath, FileFormat.Markdown);

            // Save as HTML
            document.SaveToFile(outputHtmlPath, FileFormat.Html);

            // Close the document
            document.Close();

            Console.WriteLine($"Markdown string converted to HTML at: {outputHtmlPath}");
        }
    }
}

C# Example to Convert Markdown String to HTML

Convert a Single Markdown File to HTML in C# (Step-by-Step)

If you have a Markdown file ready, converting it to HTML for web pages or email templates is straightforward. With Spire.Doc, you can load your Markdown file and export it as a fully formatted HTML document, preserving all styling, including headings, lists, links, images, and other formatting elements.

Steps to Convert a Markdown File to HTML

  • Prepare the Markdown file you want to convert.
  • Load the file into a Document object using LoadFromFile with the FileFormat.Markdown parameter.
  • Save the loaded document as HTML using SaveToFile with FileFormat.Html.

Example Code

using Spire.Doc;
using System;

namespace MarkdownToHtml
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Path to the Markdown file
            string markdownFile = @"C:\Docs\example.md";
            // Path to save the converted HTML file
            string htmlFile = @"C:\Docs\example.html";

            // Load the Markdown file
            Document document = new Document();
            document.LoadFromFile(markdownFile, FileFormat.Markdown);

            // Save as HTML file
            document.SaveToFile(htmlFile, FileFormat.Html);

            // Close the document
            document.Close();

            Console.WriteLine($"Converted '{markdownFile}' to HTML successfully!");
        }
    }
}

C# Example to Convert Markdown File to HTML

Batch Convert Multiple Markdown Files to HTML in C#

If you have a collection of Markdown files that need to be converted at once, you can use the following C# example to batch process and convert them into HTML.

Example Code

using Spire.Doc;
using System;
using System.IO;

namespace MarkdownToHtml
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Define the input folder containing Markdown files
            string inputFolder = @"C:\Docs\MarkdownFiles";
            // Define the output folder where converted HTML files will be saved
            string outputFolder = @"C:\Docs\HtmlFiles";

            // Create the output folder if it does not already exist
            Directory.CreateDirectory(outputFolder);

            // Loop through all Markdown (.md) files in the input folder
            foreach (string file in Directory.GetFiles(inputFolder, "*.md"))
            {
                // Load the Markdown file into a Document object
                Document doc = new Document();
                doc.LoadFromFile(file, FileFormat.Markdown);

                // Get the file name without extension
                string fileName = Path.GetFileNameWithoutExtension(file);
                // Build the output path with .html extension
                string outputPath = Path.Combine(outputFolder, fileName + ".html");

                // Save the document as an HTML file
                doc.SaveToFile(outputPath, FileFormat.Html);

                // Print a confirmation message for each converted file
                Console.WriteLine($"Converted {file} to HTML.");
            }

            // Print a final message when batch conversion is complete
            Console.WriteLine("Batch conversion complete.");
        }
    }
}

Additional Tips for Efficient Markdown to HTML Conversion in C#

Converting Markdown to HTML is straightforward, but applying a few practical strategies can help handle advanced scenarios, improve performance, and ensure your HTML output is clean and consistent. Here are some key tips to enhance your conversion workflow:

  • Implement Error Handling When processing multiple files, wrap your conversion logic in try-catch blocks to handle invalid Markdown, missing files, or access permission issues. This ensures your batch conversion won’t fail entirely due to a single problematic file.

    try
    {
        Document doc = new Document();
        doc.LoadFromFile(filePath, FileFormat.Markdown);
        doc.SaveToFile(outputPath, FileFormat.Html);
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Failed to convert {filePath}: {ex.Message}");
    }
    
  • Optimize Batch Conversion Performance
    For large numbers of Markdown files, consider using asynchronous or parallel processing. This reduces conversion time and avoids high memory usage:

    Parallel.ForEach(Directory.GetFiles(inputFolder, "*.md"), file =>
    {
        // Conversion logic
    });
    
  • Post-Process HTML Output
    After conversion, you can enhance the HTML by injecting CSS styles, adding custom attributes, or minifying the output. This is especially useful when integrating HTML into web pages or applications.

    string htmlContent = File.ReadAllText(outputPath);
    htmlContent = "<link rel='stylesheet' href='https://cdn.e-iceblue.com/style.css'>" + htmlContent;
    File.WriteAllText(outputPath, htmlContent);
    
  • Maintain UTF-8 Encoding
    Always save Markdown and HTML files with UTF-8 encoding to preserve special characters, symbols, and multilingual content, ensuring consistent rendering across browsers and devices.

Conclusion

In this tutorial, you learned how to convert Markdown to HTML in C#, covering single Markdown strings, individual files, and batch processing multiple documents.

These examples provide a solid foundation for integrating Markdown to HTML conversion into various .NET applications, including documentation systems, blogs, and other content-driven projects. By applying these methods, you can efficiently manage Markdown content and produce consistent, well-structured HTML output.

FAQs

Q1: Can I convert Markdown with images and links using Spire.Doc in C#?

A1: Yes. The library allows you to convert Markdown files that include images, hyperlinks, headings, lists, and code blocks into fully formatted HTML. This ensures the output closely matches your source content.

Q2: Do I need Microsoft Office installed to convert Markdown to HTML in C#?

A2: No. Spire.Doc is a standalone library for .NET, so you can convert Markdown to HTML in C# without Microsoft Office, making it easy to integrate into both desktop and web applications.

Q3: How can I batch convert multiple Markdown files to HTML in C# efficiently?

A3: You can loop through all Markdown files in a folder and convert them using Spire.Doc’s Document.LoadFromFile and SaveToFile methods. This approach allows batch conversion of Markdown documents to HTML in .NET quickly and reliably.

Q4: Can I convert Markdown to HTML dynamically in an ASP.NET application using C#?

A4: Yes. You can dynamically convert Markdown content stored as strings or files to HTML in ASP.NET using Spire.Doc, which is useful for web apps, blogs, or CMS platforms.

Q5: Is Spire.Doc compatible with .NET Core and .NET 6 for Markdown to HTML conversion?

A5: Yes. It supports .NET Framework, .NET Core, .NET 5, and .NET 6+, making it ideal for modern C# projects that require Markdown to HTML conversion.

Q6: Can I customize the HTML output after converting Markdown in C#?

A6: Yes. After conversion, you can add CSS, modify HTML tags, or inject styles programmatically in C# to match your website or application’s design requirements.

Q7: Can Spire.Doc convert other document formats besides Markdown?

A7: Yes. It can convert a wide range of formats, such as Word to PDF or Word to HTML, giving you flexibility to manage different document types in C# projects.

Q8: How do I preserve special characters and encoding when converting Markdown to HTML in C#?

A8: Always save your Markdown files with UTF-8 encoding to ensure special characters, symbols, and multilingual content are preserved during Markdown to HTML conversion.

C# Convert PDF to JPG

Working with PDF documents is a common requirement in modern applications. Whether you are building a document management system , an ASP.NET web service , or a desktop viewer application , there are times when you need to display a PDF page as an image. Instead of embedding the full PDF viewer, you can convert PDF pages to JPG images and use them wherever images are supported.

In this guide, we will walk through a step-by-step tutorial on how to convert PDF files to JPG images using Spire.PDF for .NET. We’ll cover the basics of converting a single page, handling multiple pages, adjusting resolution and quality, saving images to streams, and even batch converting entire folders of PDFs.

By the end, you’ll have a clear understanding of how to implement PDF-to-image conversion in your .NET projects.

Table of Contents:

Install .NET PDF-to-JPG Converter Library

To perform the conversion, we’ll use Spire.PDF for .NET , a library designed for developers who need full control over PDFs in C#. It supports reading, editing, and converting PDFs without requiring Adobe Acrobat or any third-party dependencies.

Installation via NuGet

You can install Spire.PDF directly into your project using NuGet Package Manager Console:

Install-Package Spire.PDF

Alternatively, open NuGet Package Manager in Visual Studio, search for Spire.PDF , and click Install.

Licensing Note

Spire.PDF offers a free version with limitations, allowing conversion of only the first few pages. For production use, a commercial license unlocks the full feature set.

Core Method: SaveAsImage

The heart of PDF-to-image conversion in Spire.PDF lies in the SaveAsImage() method provided by the PdfDocument class.

Here’s what you need to know:

  • Syntax (overload 1):

  • Image SaveAsImage(int pageIndex, PdfImageType imageType);

    • pageIndex: The zero-based index of the PDF page you want to convert.
    • imageType: The type of image to generate, typically PdfImageType.Bitmap.
  • Syntax (overload 2 with resolution):

  • Image SaveAsImage(int pageIndex, PdfImageType imageType, int dpiX, int dpiY);

    • dpiX, dpiY: Horizontal and vertical resolution (dots per inch).

    Higher DPI = better quality but larger file size.

Supported PdfImageType Values

  • Bitmap → returns a raw image.
  • Metafile → returns a vector image (less common for JPG export).

Most developers use Bitmap when exporting to JPG.

Steps to Convert PDF to JPG in C# .NET

  1. Import the Spire.Pdf and System.Drawing namespaces.
  2. Create a new PdfDocument instance.
  3. Load the PDF file from the specified path.
  4. Use SaveAsImage() to convert one or more pages into images.
  5. Save the generated image(s) in JPG format.

Convert a Single Page to JPG

Here’s a simple workflow to convert a single PDF page to a JPG image:

using Spire.Pdf.Graphics;
using Spire.Pdf;
using System.Drawing.Imaging;
using System.Drawing;

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

            // Load a sample PDF document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");

            // Convert a specific page to a bitmap image
            Image image = doc.SaveAsImage(0, PdfImageType.Bitmap);

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

            // Disposes resources
            doc.Dispose();
        }
    }
}

Output:

Convert a single PDF page to JPG

Spire.PDF supports converting PDF to various other image formats like PNG, BMP, SVG, and TIFF. For more details, refer to the documentation: Convert PDF to Image in C#.

Convert Multiple Pages (All or Range)

Convert All Pages

The following loop iterates over all pages, converts each one into an image, and saves it to disk with page numbers in the filename.

for (int i = 0; i < doc.Pages.Count; i++)
{
    Image image = doc.SaveAsImage(i, PdfImageType.Bitmap);
    string fileName = string.Format("Output\\ToJPG-{0}.jpg", i);
    image.Save(fileName, ImageFormat.Jpeg);
}

Convert a Range of Pages

To convert a specific range of pages (e.g., pages 2 to 4), modify the for loop as follows:

for (int i = 1; i <= 3; i++)
{
    Image image = doc.SaveAsImage(i, PdfImageType.Bitmap);
    string fileName = string.Format("Output\\ToJPG-{0}.jpg", i);
    image.Save(fileName, ImageFormat.Jpeg);
}

Advanced Conversion Options

Set Image Resolution/Quality

By default, the output resolution might be too low for printing or detailed analysis. You can set DPI explicitly:

Image image = doc.SaveAsImage(0, PdfImageType.Bitmap, 300, 300);
image.Save("ToJPG.jpg", ImageFormat.Jpeg);

Tips:

  • 72 DPI : Default, screen quality.
  • 150 DPI : Good for previews and web.
  • 300 DPI : High quality, suitable for printing.

Higher DPI results in sharper images but also increases memory and file size.

Save the Converted Images as Stream

Instead of writing directly to disk, you can store the output in memory streams. This is useful in:

  • ASP.NET applications returning images to browsers.
  • Web APIs sending images as HTTP responses.
  • Database storage for binary blobs.
using (MemoryStream ms = new MemoryStream())
{
    pdf.SaveAsImage(0, PdfImageType.Bitmap, 300, 300).Save(ms, ImageFormat.Jpeg);
    byte[] imageBytes = ms.ToArray();
}

Here, the JPG image is stored as a byte array , ready for further processing.

Batch Conversion (Multiple PDFs)

In scenarios where you need to process multiple PDF documents at once, you can apply batch conversion as shown below:

string[] files = Directory.GetFiles("InputPDFs", "*.pdf");
foreach (string file in files)
{
    PdfDocument doc = new PdfDocument();
    doc.LoadFromFile(file);
    for (int i = 0; i < doc.Pages.Count; i++)
    {
        Image image = doc.SaveAsImage(i, PdfImageType.Bitmap);
        string fileName = Path.GetFileNameWithoutExtension(file);
        image.Save($"Output\\{fileName}-Page{i + 1}.jpg", ImageFormat.Jpeg);
    }
    doc.Dispose();
}

Troubleshooting & Best Practices

Working with PDF-to-image conversion in .NET can come with challenges. Here’s how to address them:

  1. Large PDFs consume memory
    • Use lower DPI (e.g., 150 instead of 300).
    • Process in chunks rather than loading everything at once.
  2. Images are blurry or low quality
    • Increase DPI.
    • Consider using PNG instead of JPG for sharp diagrams or text.
  3. File paths cause errors
    • Always check that the output directory exists.
    • Use Path.Combine() for cross-platform paths.
  4. Handling password-protected PDFs
    • Provide the password when loading:
doc.LoadFromFile("secure.pdf", "password123");
  1. Dispose objects
    • Always call Dispose() on PdfDocument and Image objects to release memory.

Conclusion

Converting PDF to JPG in .NET is straightforward with Spire.PDF for .NET . The library provides the SaveAsImage() method, allowing you to convert a single page or an entire document with just a few lines of code. With options for custom resolution, stream handling, and batch conversion , you can adapt the workflow to desktop apps, web services, or cloud platforms.

By following best practices like managing memory and adjusting resolution, you can ensure efficient, high-quality output that fits your project’s requirements.

If you’re exploring more advanced document processing, Spire also offers libraries for Word, Excel, and PowerPoint, enabling a complete .NET document solution.

FAQs

Q1. Can I convert PDFs to formats other than JPG?

Yes. Spire.PDF supports PNG, BMP, SVG, and other common formats.

Q2. What DPI should I use?

  • 72 DPI for thumbnails.
  • 150 DPI for web previews.
  • 300 DPI for print quality.

Q3. Does Spire.PDF support encrypted PDFs?

Yes, but you need to provide the correct password when loading the file.

Q4. Can I integrate this in ASP.NET?

Yes. You can save images to memory streams and return them as HTTP responses.

Q5. Can I convert images back to PDF?

Yes. You can load JPG, PNG, or BMP files and insert them into PDF pages, effectively converting images back into a PDF.

Get a Free License

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

Convert HTML file or string to RTF in C#

Converting HTML to RTF in C# is a key task for developers working with web content that needs to be transformed into editable, universally compatible documents. HTML excels at web display with dynamic styles and structure, while RTF is ideal for shareable, editable files in tools like Word or WordPad.

For .NET developers, using libraries like Spire.Doc can streamline the process. In this tutorial, we'll explore how to use C# to convert HTML to RTF, covering everything from basic implementations to advanced scenarios such as handling HTML images, batch conversion.


Why Use Spire.Doc for HTML to RTF Conversion?​

Spire.Doc for .NET is a lightweight, feature-rich library for creating, editing, and converting Word and RTF documents in .NET applications (supports .NET Framework, .NET Core, and .NET 5+). For HTML to rich text conversion, it offers key benefits:​

  • Preserves HTML formatting (fonts, colors, links, lists, tables).​
  • Supports loading HTML from strings or local files.​
  • No dependency on Microsoft Word or other third-party software.​
  • Intuitive API with minimal code required.​

Getting Started

1. Create a C# Project

If you’re starting from scratch, create a new Console App (.NET Framework/.NET Core) project in Visual Studio. This example uses a console app for simplicity, but the code works in WinForms, WPF, or ASP.NET projects too.

2. Install Spire.Doc via NuGet​

The fastest way to add Spire.Doc to your C# project is through NuGet Package Manager:​

  • Open your C# project in Visual Studio.​
  • Right-click the project in the Solution Explorer → Select Manage NuGet Packages.​
  • Search for Spire.Doc and click Install to add the latest version to your project.​

Alternatively, use the NuGet Package Manager Console with this command:

Install-Package Spire.Doc

Convert HTML to RTF (C# Code Examples)

Spire.Doc’s Document class handles HTML loading and RTF saving. Below are two common scenarios:​

Scenario 1: Convert HTML String to RTF in C#

Use this when HTML content is dynamic (e.g., from user input, APIs, or databases).

using Spire.Doc;
using Spire.Doc.Documents;

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

            // Define your HTML content
            string htmlString = @"
                    <html>
                        <body>
                            <h1 style='color: #00BFFF; font-family: Arial'>HTML to RTF Conversion</h1>
                            <p>This is a <b>bold paragraph</b> with a <a href='https://www.e-iceblue.com'>link</a>.</p>
                            <ul>
                                <li>Item 1 </li>
                                <li>Item 2</li>
                            </ul>
                            <table border='1' cellpadding='5'>
                                <tr><td>Name</td><td>Gender</td><td>Age</td></tr>
                                <tr><td>John</td><td>Male</td><td>30</td></tr>
                                <tr><td>Kate</td><td>Female</td><td>26</td></tr>
                            </table>
                        </body>
                    </html>";

            // Add a paragraph in Word
            Paragraph para = doc.AddSection().AddParagraph();

            // Append the HTML string to the paragraph
            para.AppendHTML(htmlString);

            // Save the document as RTF
            doc.SaveToFile("HtmlStringToRtf.rtf", FileFormat.Rtf);
            doc.Dispose();

        }
    }
}

In this code:

  • Document Object: Represents an empty document.​
  • HTML String: You can customize this to include any valid HTML (styles, media, or dynamic content from databases/APIs).​
  • AppendHTML(): Parses HTML tags (e.g., <h1>, <table>, <a>) and inserts them into a paragraph.​
  • SaveToFile(): Writes the converted content to an RTF file.

Output:

Convert HTML string to an RTF file in C#

The SaveToFile method accepts different FileFormat parameters. You can change it to implement HTML to Word conversion in C#.

Scenario 2: Convert HTML File to RTF File​

For static HTML files (e.g., templates or saved web pages), use LoadFromFile with parameter FileFormat.Html:

using Spire.Doc;

namespace ConvertHtmlToRTF
{
    class Program
    {
        static void Main()
        {
            // Create a Document object
            Document doc = new Document();

            // Load an HTML file
            doc.LoadFromFile("Test.html", FileFormat.Html);

            // Save the HTML file as rtf format
            doc.SaveToFile("HTMLtoRTF.rtf", FileFormat.Rtf);
            doc.Dispose();
        }   
    }
}

This code simplifies HTML-to-RTF conversion into three core steps:

  • Creates a Document object.
  • Loads an existing HTML file using LoadFromFile() with the FileFormat.Html parameter.
  • Saves the loaded HTML as an RTF format using SaveToFile() with the FileFormat.Rtf parameter.

Output:

Convert an HTML file to an RTF file in C#

Spire.Doc supports bidirectional conversion, so you can convert the RTF file back to HTML in C# when needed.


Advanced Conversion Scenarios

1. Handling Images in HTML

Spire.Doc preserves images embedded in HTML (via <img> tags). For local images, ensure the src path is correct. For remote images (URLs), Spire.Doc automatically downloads and embeds them.

// HTML with local and remote images
string htmlWithImages = @"<html>
    <body>
        <h3>HTML with Images</h3>
        <p>Local image: <img src='https://cdn.e-iceblue.com/C:\Users\Administrator\Desktop\HelloWorld.png' alt='Sample Image' width='200'></p>
        <p>Remote image: <img src='https://www.e-iceblue.com/images/art_images/csharp-html-to-rtf.png' alt='Online Image'></p>
    </body>
    </html>";

// Append the HTML string to a paragraph
Paragraph para = doc.AddSection().AddParagraph();
para.AppendHTML(htmlWithImages);

// Save the document as RTF
doc.SaveToFile("HtmlWithImage.rtf", FileFormat.Rtf);

2. Batch Conversion of Multiple HTML Files

Process an entire directory of HTML files with a loop:

string inputDir = @"C:\Input\HtmlFiles";
string outputDir = @"C:\Output\RtfFiles";

// Create output directory if it doesn't exist
Directory.CreateDirectory(outputDir);

// Get all .html files in input directory
foreach (string htmlFile in Directory.EnumerateFiles(inputDir, "*.html"))
{
   using (Document doc = new Document())
   {
      doc.LoadFromFile(htmlFile, FileFormat.Html, XHTMLValidationType.None);

      // Use the same filename but with .rtf extension
      string fileName = Path.GetFileNameWithoutExtension(htmlFile) + ".rtf";
      string outputPath = Path.Combine(outputDir, fileName);

      doc.SaveToFile(outputPath, FileFormat.Rtf);

Final Thoughts​

Converting HTML to RTF in C# is straightforward with Spire.Doc for .NET. This library eliminates the need for manual parsing and ensures consistent formatting across outputs. Whether you’re working with HTML strings or files, this article provides practical code examples to handle both scenarios.

For further exploration, refer to the Spire.Doc documentation.


Common Questions

Q1: Is Spire.Doc free to use?

A: For large-scale projects, you can request a free 30-day trial license to fully evaluate it. Alternatively, Spire.Doc offers a free community edition without any watermarks (but with certain page/functionality limits).

Q2: Does Spire.Doc preserve HTML hyperlinks, images, and tables in the RTF output?

A: Yes. Spire.Doc retains most HTML elements:

  • Hyperlinks<a> tags are converted to clickable links in RTF.
  • Images: Local (<img src="/path">) and remote (<img src="/URL">) images are embedded in the RTF.
  • Tables: HTML tables (with border, cellpadding, etc.) are converted to RTF tables with preserved structure.

Q3: Can I style the RTF output further after loading the HTML?

A: Absolutely. After loading the HTML content into the Document object, you can use the full Spire.Doc API to programmatically modify the document before saving it as RTF.

Q4: Can I convert HTML to other formats with Spire.Doc?

A: Yes. Apart from converting to RTF, the library also supports converting HTML to Word, HTML to XML, and HTML to images, etc.

Professional office scene illustrating exporting a C# DataSet to Excel

In C# development, DataSet is widely used to manage in-memory data, often as a result of database queries or integration processes. There are many scenarios where you may need to create Excel files from DataSet in C# — for example, generating reports, sharing structured data with non-developers, or archiving records for future reference.

In this guide, we’ll walk through different approaches to export DataSet to Excel in C# using Spire.XLS for .NET, including creating an Excel file, writing multiple DataTables into separate sheets, applying formatting, and handling large data volumes.

Here's what's covered in this guide:


1. DataSet Basics and Environment Setup for Excel Export

What is a DataSet?

A DataSet in C# is an in-memory representation of structured data. It can hold multiple DataTables, including their rows, columns, and relationships, making it useful for working with relational-style data without direct database connections.

Why Export DataSet to Excel?

  • Data exchange – Excel is widely supported and easy to share across teams.
  • Data analysis – Analysts can manipulate Excel data directly using formulas, pivot tables, and charts.
  • Archiving – Storing query results or processed data in a readable, portable format.

Compared to raw text or CSV, Excel supports rich formatting, multiple sheets, and better readability.

Environment Setup

To export a DataSet to an Excel file in C#, we will use Spire.XLS for .NET, which provides APIs for handling Excel files. Install Spire.XLS via NuGet:

Install-Package Spire.XLS

Add the required namespaces:

using Spire.Xls;
using System.Data;
using System.Drawing; // for Color

2. Creating an Excel File from DataSet in C#

Exporting a DataSet to Excel involves two key steps: preparing the data and writing it into a workbook. In practice, the DataSet may come from queries or APIs, but for clarity, we’ll demonstrate with a simple example. First, we’ll build a DataSet in memory, then show how to export it into an Excel file where each DataTable becomes its own worksheet.

2.1 Initialize a DataSet with Sample Data

First, we’ll build a DataSet using C#. The following sample DataSet contains multiple business-style tables and a variety of column types (int, string, DateTime, decimal).

using System;
using System.Data;

class Program
{
    static DataSet CreateSampleDataSet()
    {
        DataSet ds = new DataSet("CompanyData");

        // Employees
        DataTable employees = new DataTable("Employees");
        employees.Columns.Add("ID", typeof(int));
        employees.Columns.Add("Name", typeof(string));
        employees.Columns.Add("DepartmentID", typeof(int));
        employees.Columns.Add("HireDate", typeof(DateTime));
        employees.Columns.Add("Salary", typeof(decimal));

        employees.Rows.Add(1, "Alice", 101, new DateTime(2020, 5, 12), 5500.00m);
        employees.Rows.Add(2, "Bob", 102, new DateTime(2019, 3, 8), 7200.50m);
        employees.Rows.Add(3, "Charlie", 103, new DateTime(2021, 11, 20), 4800.75m);

        // Departments
        DataTable departments = new DataTable("Departments");
        departments.Columns.Add("DepartmentID", typeof(int));
        departments.Columns.Add("DepartmentName", typeof(string));
        departments.Rows.Add(101, "HR");
        departments.Rows.Add(102, "IT");
        departments.Rows.Add(103, "Finance");

        // Projects
        DataTable projects = new DataTable("Projects");
        projects.Columns.Add("ProjectID", typeof(int));
        projects.Columns.Add("ProjectName", typeof(string));
        projects.Columns.Add("OwnerID", typeof(int));
        projects.Columns.Add("StartDate", typeof(DateTime));
        projects.Rows.Add(1001, "Recruitment System", 1, new DateTime(2023, 1, 15));
        projects.Rows.Add(1002, "ERP Upgrade", 2, new DateTime(2023, 4, 10));
        projects.Rows.Add(1003, "Budget Planning", 3, new DateTime(2023, 7, 5));

        ds.Tables.Add(employees);
        ds.Tables.Add(departments);
        ds.Tables.Add(projects);

        return ds;
    }
}

2.2 Export DataSet to Excel File

With the DataSet prepared, the next step is generating the Excel file. This involves creating a Workbook, iterating through the DataTables, inserting them into worksheets, and saving the workbook to an Excel file.

using Spire.Xls;
using System.Data;

class Program
{
    static void Main()
    {
        DataSet ds = CreateSampleDataSet();

        Workbook workbook = new Workbook();

        // Export each DataTable as a separate worksheet
        for (int i = 0; i < ds.Tables.Count; i++)
        {
            Worksheet sheet = (i == 0)
                ? workbook.Worksheets[0]
                : workbook.Worksheets.Add(ds.Tables[i].TableName);

            sheet.InsertDataTable(ds.Tables[i], true, 1, 1);
            sheet.Name = ds.Tables[i].TableName; // ensure sheet is named after the table
        }

        workbook.SaveToFile("DatasetToExcel.xlsx", ExcelVersion.Version2016);
    }
}

About the Exporting Process

  • Each DataTable is written into a separate worksheet.
  • InsertDataTable(DataTable table, bool columnHeaders, int row, int column) inserts data starting from a specific cell.
  • SaveToFile() writes the workbook to disk in the specified format.

In addition to creating separate worksheets for each DataTable, you can also insert multiple DataTables into the same worksheet by adjusting the starting row and column parameters of the InsertDataTable method.

Result preview

Below is a quick preview of the output workbook showing three sheets populated from the DataSet.

Excel workbook with Employees, Departments, and Projects sheets populated from DataSet

For a practical example of exporting data directly from a database to Excel, see our guide on Export Database to Excel in C#.


3. Adding Formatting to Excel Sheets Using C#

Raw data often isn’t enough for reporting. Formatting improves readability and makes the Excel file more professional. With Spire.XLS, you can style fonts, apply background colors, add borders, and format numbers and dates.

using System.Drawing;
using Spire.Xls;

// Get the first sheet
Worksheet sheet1 = workbook.Worksheets["Employees"];

// 1) Header styling (A1:E1)
CellRange header = sheet1.AllocatedRange.Rows[0];
header.Style.Font.IsBold = true;
header.Style.Font.Size = 12;
header.Style.Font.Color = Color.White;
header.Style.Color = Color.SteelBlue;

// Borders around the header row
header.BorderAround(LineStyleType.Thin);

// 2) Number formats for entire columns (D: HireDate, E: Salary)
sheet1.AllocatedRange.Columns[3].Style.NumberFormat = "yyyy-mm-dd";
sheet1.AllocatedRange.Columns[4].Style.NumberFormat = "$#,##0.00";

// 3) Optional: zebra stripes for data area (A2:E4 here as example)
CellRange data = sheet1.Range["A2:E4"];
// CellRange data = sheet1.Range[2, 1, 4, 5];
data.Style.Color = Color.FromArgb(245, 247, 250);
data.BorderAround(LineStyleType.Thin);

// Auto-fit after formatting
sheet1.AllocatedRange.AutoFitColumns();
sheet1.AllocatedRange.AutoFitRows();

How Formatting Works

  • Style.Font — font properties such as IsBold, Size, Color.
  • Style.Color — background fill color for the selected range.
  • Borders / BorderAround — draw borders on edges/around ranges with LineStyleType.
  • NumberFormat — Excel-native formats (e.g., dates, currency, percentages).
  • AutoFitColumns() / AutoFitRows() — adjust column widths / row heights to fit content.

For more formatting options, refer to the API reference for CellRange and CellStyle.

Formatting preview

The following image shows styled headers, borders, and proper date/currency formats applied.

Styled header with blue background and white bold text; date and currency columns properly formatted


4. Handling Large DataSet Exports

When exporting large datasets, performance and memory become critical. Consider:

  • Split across sheets — When rows approach Excel/version limits or for logical separation.
  • Batch writing — Insert data in segments (e.g., table-by-table or range-by-range).
  • Lightweight formatting — Minimize heavy styling to reduce file size and processing time.
  • Streaming (where applicable) — Prefer APIs that avoid loading everything into memory at once.

5. Bonus: Read Excel into DataSet in C#

In addition to exporting, the reverse workflow is equally important: reading Excel data back into a DataSet for processing or migration. This is useful when importing data from external reports, integrating spreadsheets with applications, or performing preprocessing before database insertion.

using System.Data;
using Spire.Xls;

class Program
{
    static DataSet ReadExcelIntoDataSet(string filePath)
    {
        DataSet ds = new DataSet();
        Workbook workbook = new Workbook();
        workbook.LoadFromFile(filePath);

        foreach (Worksheet sheet in workbook.Worksheets)
        {
            DataTable dt = sheet.ExportDataTable();
            dt.TableName = sheet.Name;
            ds.Tables.Add(dt);
        }

        return ds;
    }
}

The ExportDataTable method allows each worksheet to be converted into a DataTable object, preserving both the structure and the cell values. By assigning the sheet name to TableName and adding it into a DataSet, you can combine multiple sheets into a single in-memory data container that is ready for further processing.

For a complete workflow on persisting Excel data into a database, see our guide on Import Excel into Database in C#.


Conclusion

Exporting a DataSet to Excel in C# allows you to generate reports, share data, and make information easier to analyze or present. With Spire.XLS for .NET, you can create Excel files directly from DataSet objects, apply formatting, manage multiple sheets, and handle large datasets efficiently. You can also import Excel data back into a DataSet for integration with applications or databases.

To explore more advanced features, you may request a free temporary license or use Free Spire.XLS for .NET for smaller projects.


FAQ: C# DataSet and Excel Integration

Q1: How can I export multiple DataTables from a DataSet into different Excel sheets?

Loop through ds.Tables and call InsertDataTable for each one, creating a new worksheet per DataTable.

Q2: Can I export a DataSet to a specific worksheet in an existing Excel file?

Yes. Load the file using Workbook.LoadFromFile(), then choose the worksheet and use InsertDataTable.

Q3: Does exporting DataSet to Excel preserve column formatting and data types?

Values are exported with the same data types as in the DataSet. You can also apply formatting (date, currency, alignment, etc.) after inserting.

Q4: How do I handle very large DataSet exports (over 100,000 rows)?

Split into multiple sheets, use batch inserts, and reduce complex formatting to improve performance.

Read and parse CSV files in C#/.NET

CSV (Comma-Separated Values) files remain one of the most widely used formats for data exchange between applications. Whether you’re processing financial data, user records, or analytics reports, efficiently reading CSV files in C# is a common task in .NET development.

In this comprehensive guide, we'll explore how to parse CSV files in C# using Spire.XLS for .NET, covering both direct reading and converting CSV to DataTable.


Install the C# CSV File Reader Library

While primarily designed for Excel files, Spire.XLS can also be used as a .NET CSV reader. It provides excellent support for CSV files, offering a range of features that make CSV processing efficient and straightforward.

The first step is to install the Spire.XLS package in your project. Here's how:

  • Open your project in Visual Studio
  • Right-click on your project in the Solution Explorer
  • Select "Manage NuGet Packages"
  • In the NuGet Package Manager, search for "Spire.XLS"
  • Click "Install" to add the package to your project

Alternatively, you can install it using the Package Manager Console:

PM> Install-Package Spire.XLS

This will add the necessary dependencies to your project, allowing you to use Spire.XLS classes.


Read a CSV File in C#

Let's start with the fundamentals: reading a simple CSV file and extracting its data. The C# code example below loads a CSV file, accesses its data, and prints the contents to the console in a tabular format.

using Spire.Xls;

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

            // Load the CSV file
            workbook.LoadFromFile("sample.csv", ",");

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

            // Get the used range
            CellRange range = sheet.AllocatedRange;

            // Iterate through rows and columns
            for (int row = 1; row <= range.RowCount; row++)
            {
                for (int col = 1; col <= range.ColumnCount; col++)
                {
                    // Get cell value
                    string cellValue = range[row, col].Value;
                    Console.Write(cellValue + "\t");
                }
                Console.WriteLine();
            }

            Console.ReadLine();
        }
    }
}

Explanation:

  • Workbook class: Acts as a "container" for your CSV file in memory. Even though CSV isn’t a full Excel file, Spire.Xls treats it as a single-sheet workbook for consistency.
  • Workbook.LoadFromFile(): Loads the CSV file. The parameters are:
    • File path: "sample.csv".
    • Delimiter: "," (comma, default for CSV).
  • Worksheet.AllocatedRange: Retrieves only the cells that contain data.
  • CellRange[row, col].Value: Retrieves the value of a specific cell.

Result: CSV data printed in a clean, tab-separated format.

Read a CSV file to the console in C#

If you need a demo for reading CSV files in VB.NET, convert the code directly using the C# to VB.NET converter.


Read CSV into a DataTable in C#

A DataTable is a versatile in-memory data structure in .NET that simplifies data manipulation (e.g., filtering, sorting, or binding to UI components). Here’s how to load CSV data into a DataTable using Spire.XLS:

using Spire.Xls;
using System.Data;

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

            // Load the CSV file
            workbook.LoadFromFile("sample.csv", ",");

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

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

            // Get row and column count
            Console.WriteLine("\nConversion complete! DataTable information:");
            Console.WriteLine($"Number of columns: {dataTable.Columns.Count}");
            Console.WriteLine($"Number of rows: {dataTable.Rows.Count}");
            Console.WriteLine();

            // Print column names
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                Console.Write(dataTable.Columns[i].ColumnName + "  | ");
            }
            Console.WriteLine();
            Console.WriteLine("----------------------------------------------------------");

            // Print row data
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                for (int j = 0; j < dataTable.Columns.Count; j++)
                {                
                    string value = dataTable.Rows[i][j].ToString();

                    Console.Write(value + "\t");
                }
                Console.WriteLine(); 
            }
        }
    }
}

Explanation:

  • Worksheet.ExportDataTable(): Converts the entire CSV worksheet into a DataTable.
  • Metadata Access: DataTable.Columns.Count and DataTable.Rows.Count shows the size of your dataset, helping you verify that the import was successful.
  • Column Headers and Data Output: Iterates through to display column names and row data.

Result: Structured output with metadata, headers, and rows:

Convert a CSV file to a DataTable in C#

To analyze, calculate, or format the data, you can convert CSV to Excel in C#.


When to Use Each Method

Choose the right approach based on your goal:

Method Best For Use Case Example
Direct CSV Reading Quick data verification Checking if a CSV is loaded correctly.
Convert to DataTable Advanced data processing Filtering rows, sorting, or saving to SQL Server.

Conclusion​

Reading CSV files in C# is streamlined with Spire.XLS for .NET, and converting CSV data to a DataTable adds flexibility for data manipulation. Whether you’re working with small datasets or large files, Spire.XLS offers flexible options to meet your requirements.

The code examples in this guide are ready to use - just copy, paste, and adjust for your CSV file path. For more advanced features, refer to Spire.XLS’s official documentation.


FAQs (Common Questions)

Q1: Why choose Spire.XLS for CSV reading?

A: While the .NET Framework offers built-in StreamReader for CSV handling, Spire.XLS provides several distinct advantages:

  • No dependencies: Doesn't require Microsoft Excel or Office to be installed
  • High performance: Optimized for handling large CSV files efficiently
  • Flexibility: Multiple ways to read CSV data based on your needs
  • Cross-platform: Works with .NET Framework, .NET Core, .NET Standard, and Mono

Q2: Can I use a different delimiter (e.g., semicolon or tab)?

A: Yes. Replace the second parameter of LoadFromFile() method with your delimiter:

// For tab-delimited files
workbook.LoadFromFile("data.txt", "\t");

// For semicolon-delimited files
workbook.LoadFromFile("data.csv", ";");

// For pipe-delimited files
workbook.LoadFromFile("data.csv", "|");

Q3: Can I read specified rows or columns from a CSV file?

A: Yes. You can target a precise subset of your data by defining exact row and column boundaries. This is useful for extracting specific information (e.g., skipping headers, focusing on relevant columns) without processing the entire file.

For example:

// Define the specific range
int startRow = 2;   // Start from row 2 (skip header)
int endRow = 4;     // End at row 4
int startCol = 2;   // Start from column 2
int endCol = 6;     // End at column 6


// Loop through rows and columns
for (int row = startRow; row <= endRow; row++)
{
   for (int col = startCol; col <= endCol; col++)
   {
      // Get cell value
      string cellValue = worksheet.Range[row, col].Value;
      Console.Write(cellValue + "\t"); 

Note: Spire.Xls uses 1-based indexing (like Excel), so the first row/column is numbered 1 (not 0).

Spire.PDFViewer for MAUI is a dedicated PDF viewing component tailored for .NET Multi-platform App UI (MAUI) frameworks. This guide will show you how to configure it in your .NET MAUI project, including environment setup, product installation, and core PDF viewing feature implementation.

1. Prerequisites & Environment Setup

Ensure your development environment meets the following requirements before you begin.

1.1 Required Software

  • IDE: Visual Studio 2022 (version 17.8 or later) for Windows, or Visual Studio 2022 for Mac (version 17.6 or later).
  • Target Frameworks:
    • Android 5.0 (API 21) or higher
    • Windows 11, or Windows 10 Version 1809 or higher

1.2 Install the .NET MAUI Workload

The .NET Multi-platform App UI development workload is mandatory for MAUI projects. Follow these steps to install it:

  • Open Visual Studio Installer:
    • Search for "Visual Studio Installer" in your Start Menu (usually under the "Visual Studio 2022" folder).
    • Alternatively, open Visual Studio, go to “Tools > Get Tools and Features”.
  • Modify Your Installation:
    • Click "Modify" next to your Visual Studio 2022 edition.
    • Navigate to the "Workloads" tab.
    • Check the box for ".NET Multi-platform App UI development".
    • Ensure the optional components you need are selected.
    • Click "Modify" to start the installation

Select the .NET MAUI workload in Visual Studio Installer

2. Create a New .NET MAUI Project

After installing MAUI, follow these steps to create a new .NET MAUI project:

2.1 Select the Project Template

  • Open Visual Studio and click “Create a new project”.
  • Search for "MAUI" and select the .NET MAUI App template (C#).
  • Click “Next” to proceed.

Choose the .NET MAUI App template

2.2 Configure Project Details

  • Enter a project name (e.g., "PdfViewerMauiApp") and choose a Save location.
  • Next, select .NET 7.0 or later (e.g., .NET 8.0) as the target framework.
  • Click “Create” to generate the project.

Select the .NET framework version

3. Install Spire.PDFViewer and Dependencies

To implement the PDF viewer in .NET MAUI, you need to install the dependent NuGet packages and add Spire.PDFViewer DLLs.

3.1 Install Dependent NuGet Packages

  • Go to “Tools > NuGet Package Manager > Package Manager Console”.
  • Run the following command to install all required packages at once:
Install-Package Microsoft.Win32.Registry -Version 5.0.0
Install-Package System.Security.Permissions -Version 4.7.0
Install-Package System.Text.Encoding.CodePages -Version 4.7.0
Install-Package System.Security.Cryptography.Pkcs -Version 4.7.0
Install-Package System.Security.Cryptography.Xml -Version 4.7.1
Install-Package HarfBuzzSharp -Version 8.3.0.1
Install-Package SkiaSharp -Version 3.116.1
Install-Package SkiaSharp.Views.Maui.Controls -Version 2.88.5
Install-Package System.Buffers -Version 4.5.1
Install-Package System.Memory -Version 4.5.5

3.2 Add Spire.PDFViewer DLLs

  • Download the Spire.PdfViewer package from the official website.
  • Unzip the downloaded file to a specified file path.
  • In Visual Studio’s Solution Explorer, right-click the project > Add > Project Reference.
  • Click “Browse”, navigate to the unzipped folder (BIN\NET7.0\windows10.0.19041.0), and add both:
    • Spire.PdfViewer.Maui.dll
    • Spire.Pdf.dll

Add dependencies and Spire.PDFViewer dlls

3.3 Restrict Target Platform to Windows

Currently, the Spire.PDFViewer for MAUI only supports the Windows platform. Therefore, it’s necessary to modify the project file (.csproj) to remove non-Windows target frameworks:

  • In Solution Explorer, right-click the project and select “Edit Project File”.
  • Locate the <TargetFrameworks> element and delete or comment out this line.
  • Save the file (Ctrl+S) and reload the project when prompted by Visual Studio.

Remove non-Windows target frameworks

4. Add PDF Viewer to the Project

4.1 Initialize Spire.PDFViewer

In “MauiProgram.cs”, add the .UseSpirePdfViewer() method in the MauiAppBuilder chain:

Add Spire.PDFViewer initialization code

4.2 Option 1: Use the Default PDF Viewer UI

For a quick setup with a pre-built toolbar (supports loading, zooming, and searching), use the minimal XAML configuration:

  • Replace the default XAML content of “MainPage.xaml” with the following:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:spire="clr-namespace:Spire.PdfViewer.Maui;assembly=Spire.PdfViewer.Maui"
             x:Class="PdfViewerMauiApp.MainPage"> <!-- Modify “PdfViewerMauiApp” to match your project name -->
    
    <Grid ColumnDefinitions="Auto, *" ColumnSpacing="0">
        <!-- Default PDF Viewer with built-in toolbar -->
        <spire:PdfViewer x:Name="PdfDocumentViewer1" Grid.Column="1" />
    </Grid>
</ContentPage>
  • Open “MainPage.xaml.cs” and ensure the namespace matches your project name:
namespace PdfViewerMauiApp; // Match the project name in the x:Class value

public partial class MainPage : ContentPage
{

    public MainPage()
    {
        InitializeComponent();
    }

}

Configure the default PDF viewer

When you run the project, a PDF viewer with a built-in toolbar (Home, Zoom, Find) will appear. You can load PDFs directly via the toolbar and use its default features.

Default Spire.PDFViewer with built-in toolbar

4.3 Option 2: Customize the UI Layout & Functionality

For a tailored experience (e.g., a dedicated "Load PDF" button or page navigation), design a custom layout and implement core logic.

Step 1: Design the Custom UI (MainPage.xaml)

Replace the default XAML content of “MainPage.xaml” with a two-column grid (left: control panel; right: PDF viewer):

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:spire="clr-namespace:Spire.PdfViewer.Maui;assembly=Spire.PdfViewer.Maui"
             x:Class="PdfViewerMauiApp.MainPage"> <!-- Modify “PdfViewerMauiApp” to match your project name -->
    
    <Grid ColumnDefinitions="Auto, *" ColumnSpacing="0">
        <!-- Left Control Panel -->
        <VerticalStackLayout Grid.Column="0" WidthRequest="220"
                           Padding="10" Spacing="10">
            <!-- Button to load PDF files -->
            <Button Text="Load PDF File"
                   Clicked="LoadFromFile_Clicked"
                   HeightRequest="40"/>

            <!-- Page Navigation: Entry + Button -->
            <HorizontalStackLayout Spacing="10">
                <Entry x:Name="pageEntry"
                       WidthRequest="100"
                       HeightRequest="40"
                       Keyboard="Numeric"
                       Placeholder="Page Number"/>

                <Button Text="Go To"
                       Clicked="GoPages_Clicked"
                       WidthRequest="80"
                       HeightRequest="40"/>
            </HorizontalStackLayout>
            <Label x:Name="lbl1" HeightRequest="30"/>
        </VerticalStackLayout>

        <!-- Right PDF Viewing Area -->
        <spire:PdfDocumentViewer x:Name="PdfDocumentViewer1" Grid.Column="1" />
    </Grid>
</ContentPage>

Step 2: Add Functionality (MainPage.xaml.cs)

Add event handlers in “MainPage.xaml.cs” to enable PDF loading and page navigation:

namespace PdfViewerMauiApp; // Match your project name

    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        // Click event for the Load PDF File button
        private async void LoadFromFile_Clicked(object sender, EventArgs e)
        {
            try
            {
                // Restrict file picker to PDF files only
                var result = await FilePicker.PickAsync(new PickOptions
                {
                    FileTypes = FilePickerFileType.Pdf,
                    PickerTitle = "Choose a PDF file"
                });

                if (result != null)
                {
                    // Load the PDF file from the selected path
                    PdfDocumentViewer1.LoadFromFile(result.FullPath);

                }
            }
            catch (Exception ex)
            {
                // Display error message
                lbl1.Text = $"Loading failed: {ex.Message}";
            }
        }

        // Click event for page navigation button
        private void GoPages_Clicked(object sender, EventArgs e)
        {
             
            if (int.TryParse(pageEntry.Text, out int pageNumber) && pageNumber > 0)
            {
                    // Verify that the page number is within the valid range.
                if (pageNumber <= PdfDocumentViewer1.PageCount)
                 {
                        // Jump to a specific page number
                     PdfDocumentViewer1.GotoPage(pageNumber, true);
                     lbl1.Text = $"Navigated to Page: {pageNumber}/{PdfDocumentViewer1.PageCount}";
                 }
                 else
                 {
                     lbl1.Text = $"Out of Range (Max Page: {PdfDocumentViewer1.PageCount})";
                 }
             }
             else
             {
                 lbl1.Text = "Please enter a valid page number.";
             }
         }
     }

Step 3: Run the Project

Run the application, and test the PDF viewer functionality:

  • Click “Load PDF File” to select and open a PDF.

  • Enter a page number and click “Go To” to navigate to that page.

Custom PDF viewer with page navigation

Integrating Spire.PDFViewer into a .NET MAUI project enables developers to quickly add robust, user-friendly PDF viewing capabilities, including document loading, page navigation, and built-in/ custom UI controls. By following the steps outlined here, developers can avoid common pitfalls (e.g., version mismatches, missing dependencies) and deploy a functional PDF viewer in minimal time.

Write to Excel in C#

Excel remains one of the most widely used tools for managing and analyzing data due to its powerful features and user-friendly interface. In C# applications, developers often need to generate reports, export database results, or automate tasks by writing directly to Excel files.

To achieve this efficiently, developers often turn to third-party libraries. Spire.XLS for .NET makes it simple to write to Excel programmatically without relying on Microsoft Excel. With Spire.XLS, you can insert text, numbers, dates, formulas, or even bulk datasets such as arrays, DataTables, and lists into Excel worksheets. This provides a fast, flexible, and reliable way to automate Excel writing in C# applications.

On this page:

Getting Started with Spire.XLS for .NET

What’s Spire.XLS for .NET

Spire.XLS for .NET is a professional .NET Excel library developed by E-iceblue. It allows developers to write to Excel files in C# and perform a wide range of operations including creating, editing, reading, and exporting Excel documents—without requiring Microsoft Excel to be installed.

Key features include:

  • Write and update Excel files programmatically.
  • Support for Excel formats (XLS, XLSX, CSV, ODS).
  • Advanced features such as formulas, charts, pivot tables, and data validation.
  • Export Excel to PDF, HTML, and image formats.
  • High performance with large datasets, suitable for desktop, server, and web applications.

How to Install Spire.XLS for .NET

Option 1: Install via NuGet (recommended)

  • Open Visual Studio.
  • Navigate to Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
  • Search for Spire.XLS and install it.

Or, install it directly using the Package Manager Console :

PM> Install-Package Spire.XLS

Option 2: Manual installation

Once installed, you’re ready to start writing to Excel in C#.

How to Create a New Excel File in C#

The first step is to create a new workbook and add a worksheet. Here’s how:

using Spire.Xls;

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

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

            // Add a worksheet
            Worksheet sheet = workbook.Worksheets.Add("Report");

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

At this point, you have created an empty Excel file with a worksheet named “Report”. Next, let’s write data into it.

Write Different Data Types to Excel Cells in C#

Spire.XLS allows you to write various data types directly to Excel cells. Below are common examples:

Write Text Values

sheet.Range["A1"].Text = "Hello Excel!";

Write Numeric Values

sheet.Range["A2"].NumberValue = 123.45;

Write Date and Time

sheet.Range["A3"].DateTimeValue = DateTime.Now;
sheet.Range["A3"].NumberFormat = "yyyy-mm-dd hh:mm";

Write Boolean Values

sheet.Range["A4"].BooleanValue = true;

Write TimeSpan Values

sheet.Range["A5"].TimeSpanValue = new TimeSpan(2, 30, 0); // 2 hours 30 minutes;
sheet.Range["A5"].NumberFormat = "[h]:mm:ss";

Insert Formulas

sheet.Range["A6"].Formula = "=SUM(A2,100)";

Insert HTML Formatted Strings

string htmlText = "<span style=\"font-family: Times New Roman; color: blue; font-size: 15pt;\">Hello
<strong>Spire.XLS</strong></span>";
sheet.Range["A7"].HtmlString = htmlText;

Write General Values Without Specific Type

sheet.Range["A8"].Value = "General Value";

Output:

C# Write various data types to Excel

You might also be interested in: How to Read Excel Files in C#

Write Bulk Data to Excel Sheets in C#

When dealing with larger datasets, writing values cell by cell isn’t efficient. Spire.XLS provides methods to insert arrays , and DataTables directly. Other data structures can be converted to arrays or DataTables before being written to the Excel sheet.

Write Arrays to Excel

Spire.XLS provides the Worksheet.InsertArray(string[] stringArray, int firstRow, int firstColumn, bool isVertical) method, allowing developers to insert one-dimensional or two-dimensional arrays into a specified range of cells in a worksheet.

string[,] data = {
    { "Name", "Age", "Country" },
    { "Alice", "30", "USA" },
    { "Bob", "28", "UK" },
    { "Charlie", "35", "Canada" }
};
sheet.InsertArray(data, 1, 1);

Output:

Insert Array to Excel in C#

Write DataTables to Excel

To import data from a DataTable to a worksheet, use the Worksheet.InsertDataTable(DataTable dataTable, bool columnHeaders, int firstRow, int firstColumn, bool transTypes) method.

using System.Data;

DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Product", typeof(string));
dt.Columns.Add("Price", typeof(double));

// Add rows
dt.Rows.Add(1, "Laptop", 1200.5);
dt.Rows.Add(2, "Tablet", 450.99);
dt.Rows.Add(3, "Phone", 799.0);

// Insert DataTable starting at cell A1
sheet.InsertDataTable(dt, true, 1, 1, true);

Output:

Insert DataTable to Excel in C#

On the contrary, you can export data from Excel to DataTable by using the ExportDataTable method of the Worksheet class.

Write Lists to Excel

While Spire.XLS does not provide a direct method for writing lists to Excel, you can convert lists to a DataTable and then use the InsertDataTable method to write the DataTable to Excel.

using Spire.Xls;
using System.Data;

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

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

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

            // Create a list with student data
            List<Student> students = new List<Student>
            {
                new Student("Michael", "Johnson", 20, "Computer Science", 3.8),
                new Student("Sarah", "Williams", 22, "Mathematics", 3.6),
                new Student("Jessica", "Brown", 19, "Physics", 3.9),
                new Student("David", "Smith", 21, "Chemistry", 3.7),
                new Student("Emily", "Davis", 23, "Biology", 3.5)
            };

            // Convert the list to DataTable
            DataTable dataTable = ConvertListToDataTable(students);

            // Write DataTable to the worksheet
            worksheet.InsertDataTable(dataTable, true, 1, 1, true);

            // Set column width
            worksheet.AllocatedRange.ColumnWidth = 12;

            // Align content to left
            worksheet.AllocatedRange.HorizontalAlignment = HorizontalAlignType.Left;

            // Save to an Excel file
            workbook.SaveToFile("InsertStudents.xlsx", ExcelVersion.Version2016);

            // Dispose resources
            workbook.Dispose();
        }

        static DataTable ConvertListToDataTable(List<Student> students)
        {
            DataTable dataTable = new DataTable();

            // Add columns
            dataTable.Columns.Add("FirstName", typeof(string));
            dataTable.Columns.Add("LastName", typeof(string));
            dataTable.Columns.Add("Age", typeof(int));
            dataTable.Columns.Add("Major", typeof(string));
            dataTable.Columns.Add("GPA", typeof(double));

            // Add rows
            foreach (var student in students)
            {
                DataRow row = dataTable.NewRow();
                row["FirstName"] = student.FirstName;
                row["LastName"] = student.LastName;
                row["Age"] = student.Age;
                row["Major"] = student.Major;
                row["GPA"] = student.GPA;
                dataTable.Rows.Add(row);
            }

            return dataTable;
        }
    }

    class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public string Major { get; set; }
        public double GPA { get; set; }

        public Student(string firstName, string lastName, int age, string major, double gpa)
        {
            FirstName = firstName;
            LastName = lastName;
            Age = age;
            Major = major;
            GPA = gpa;
        }
    }
}

Output:

Insert List to Excel in C#

Save and Export Excel Files

After writing data, you’ll want to save or export the Excel file. Spire.XLS supports multiple formats including XLSX, CSV, and PDF .

// Save as XLSX
workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2016);

// Save as CSV
workbook.SaveToFile("Output.csv", ",", Encoding.UTF8);

// Export as PDF
workbook.SaveToFile("Output.pdf", FileFormat.PDF);

For web applications, you can also save to a MemoryStream :

using (MemoryStream ms = new MemoryStream())
{
    workbook.SaveToStream(ms, FileFormat.Version2016);
    // Write to Response in ASP.NET if needed
}

Common Issues and Solutions

1. Incorrect Date or Time Format

Issue: Dates/times appear as serial numbers.

Solution :

  • Apply a proper number format to the cell:
sheet.Range["A1"].DateTimeValue = DateTime.Now;
sheet.Range["A1"].NumberFormat = "yyyy-mm-dd hh:mm";

2. Data Overwriting or Misaligned

Issue : Writing arrays or DataTables overwrites existing data unintentionally.

Solution :

  • Check firstRow and firstColumn parameters in InsertArray() or InsertDataTable().
  • Use separate worksheets or offset ranges if necessary.

3. Large Dataset Performance Issues

Issue : Writing thousands of rows is slow.

Solution :

  • Use bulk writing methods instead of looping cell by cell.
  • Apply styles after inserting data to avoid repeated formatting overhead.

4. Formula Not Calculating Correctly

Issue : Excel formulas inserted via sheet.Range["A1"].Formula do not return expected results.

Solution :

  • Ensure the formula syntax is correct for Excel (e.g., =SUM(A2:A10)).
  • Call workbook.CalculateAllValue() to update all formulas before saving if needed.

Conclusion

Writing to Excel in C# doesn’t have to be complex. With Spire.XLS for .NET , you can seamlessly write different data types—whether individual values or large datasets—into Excel worksheets. The library also provides support for styling, formulas, and advanced formatting, ensuring your Excel files are not only accurate but also presentation-ready.

By using efficient bulk-writing techniques like arrays and DataTables, you can handle both small and large data operations with ease. If your goal is to write to Excel files quickly and reliably , Spire.XLS gives you the tools you need—without the overhead of Microsoft Excel.

FAQs

Q1. Can I write to an existing Excel file with Spire.XLS?

Yes. Use workbook.LoadFromFile("file.xlsx") to open an existing file, then modify and save it.

Q2. Does Spire.XLS require Microsoft Excel to be installed?

No. It’s a standalone library that works without Excel.

Q3. Can Spire.XLS handle large Excel files with thousands of rows?

Yes. It’s optimized for high performance with large datasets.

Q4. How do I format cells while writing data?

You can style cells using properties like font, color, borders, and alignment:

sheet.Range["A1"].Style.Font.IsBold = true;
sheet.Range["A1"].Style.Color = Color.Yellow;
sheet.Range["A1"].Style.HorizontalAlignment  = HorizontalAlignType.Left;

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.

Create PDF in ASP.NET Core

Creating PDFs in ASP.NET applications is a common requirement, whether you're generating invoices, reports, forms, or exporting dynamic content. To streamline this process, you can utilize Spire.PDF for .NET, a professional and lightweight library that enables developers to easily create and manipulate PDF documents programmatically, without the need for complex APIs or third-party printer drivers.

In this tutorial, we’ll show you how to create PDF documents in an ASP.NET Core Web application using Spire.PDF for .NET, with examples of creating a PDF from scratch and converting HTML to PDF.

On this page:

Why Use Spire.PDF for .NET?

There are many ways to create PDF in ASP.NET, but most involve trade-offs: some depend on printer drivers, others have limited layout control, and many require heavy third-party frameworks. Spire.PDF for .NET offers a more streamlined approach. It’s a dedicated .NET library that handles the majority of PDF creation and manipulation tasks on its own, without external tools.

Key advantages include:

  • No Adobe dependency – Generate and manage PDFs without Acrobat installed.
  • Full-featured PDF toolkit – Beyond creation, you can edit, merge, split, protect, or annotate PDFs.
  • High-fidelity rendering – Preserve fonts, CSS, images, and layouts when exporting content.
  • ASP.NET ready – Compatible with both ASP.NET Web Forms/MVC and ASP.NET Core projects.
  • Flexible generation options – Create PDFs from scratch, images, or streams.

(Note: HTML-to-PDF conversion requires a lightweight external plugin such as Qt WebEngine.)

Step-by-Step: Generate PDF in ASP.NET Core Web App

Step 1. Create a New ASP.NET Core Web App

  • Open Visual Studio .
  • Select Create a new project .
  • Choose ASP.NET Core Web App (Model-View-Controller) → Click Next .
  • Enter a project name, e.g., PdfDemoApp.
  • Select your target framework (e.g., . NET 6 , 7 , or 8 ).
  • Click Create .

Step 2. Install Spire.PDF via NuGet

  • Right-click on your project → Manage NuGet Packages .
  • Search for Spire.PDF .
  • Install the package Spire.PDF (latest stable version).

Or install using the Package Manager Console :

Install-Package Spire.PDF

Step 3. Add a Controller for PDF Generation

  • Right-click on the Controllers folder → Add → Controller → MVC Controller – Empty .
  • Name it: PdfController.cs.
  • Replace the default code with this:
using Microsoft.AspNetCore.Mvc;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace PdfDemoApp.Controllers
{
    public class PdfController : Controller
    {
        public IActionResult CreatePdf()
        {
            // Create a new PDF document
            PdfDocument doc = new PdfDocument();
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(40));

            // Draw text on the page
            PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 25f);
            PdfSolidBrush brush = new PdfSolidBrush(Color.Black);
            page.Canvas.DrawString("Hello from ASP.NET Core!", font, brush, 10, 50);

            // Save to memory stream
            using (MemoryStream ms = new MemoryStream())
            {
                doc.SaveToStream(ms);
                doc.Close();
                ms.Position = 0;

                // Return PDF file
                return File(ms.ToArray(), "application/pdf", "Generated.pdf");
            }
        }
    }
}

Step 4: (Optional) Add a Button or Link in Your View

Open Views/Home/Index.cshtml (or whichever view is your homepage).

Add a button or link like this:

<div>
    <a asp-controller="Pdf" asp-action="CreatePdf" class="btn btn-primary">
        Create PDF from Scratch
    </a>
</div>

This uses ASP.NET Core tag helpers to generate the correct route (/Pdf/CreatePdf).

Step 5. Run and Test

  • Press F5 to run your app.
  • On the home page, click the "Create PDF from Scratch" button. This will call the CreatePdf method in PdfController and trigger a download of the generated PDF.
  • If you didn’t add the button, you can still run the CreatePdf method directly by visiting this URL in your browser:

https://localhost:xxxx/Pdf/CreatePdf

(where xxxx is your local port number).

Output:

Create PDF from ASP.NET Core

In addition to text, Spire.PDF supports adding a wide range of elements to PDF, such as images, shapes, tables, lists, hyperlinks, annotations, and watermarks. For more details and advanced usage, check the .NET PDF Tutorials.

Create PDF from HTML in ASP.NET Core

Spire.PDF allows you to convert HTML content directly into PDF files. This feature is particularly useful for generating invoices, reports, receipts, or exporting styled web pages with consistent formatting.

To render HTML as PDF, Spire.PDF relies on an external rendering engine. You can choose between Qt WebEngine or Google Chrome . In this guide, we’ll use Qt WebEngine .

Setup the Qt plugin:

  1. Download the Qt WebEngine plugin for your operating system:

  2. Extract the package to obtain the plugins directory, e.g.: C:\plugins-windows-x64\plugins

  3. Register the plugin path inyour code:

HtmlConverter.PluginPath = @"C:\plugins-windows-x64\plugins";

Once the plugin is ready, you can follow the steps from the previous section and add the code snippet below to your controller to generate PDF output from HTML content.

using Microsoft.AspNetCore.Mvc;
using Spire.Additions.Qt;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace PdfDemoApp.Controllers
{
    public class PdfController : Controller
    {
        [HttpGet]
        public IActionResult HtmlToPdf()
        {
            // Example HTML string
            string html = @"
                <html>
                  <head>
                    <style>
                      body { font-family: Arial, sans-serif; }
                      h1 { color: #2563eb; }
                    </style>
                  </head>
                  <body>
                    <h1>ASP.NET Core: Create PDF from HTML</h1>
                    <p>This PDF was generated using the Qt-based converter.</p>
                  </body>
                </html>";

            // Path to the Qt plugin folder
            // ⚠️ Ensure this folder exists on your server/deployment environment
            string pluginPath = @"C:\plugins-windows-x64\plugins";
            HtmlConverter.PluginPath = pluginPath;

            // Create a temp file path (on server side)
            string tempFile = Path.GetTempFileName();

            // Convert HTML string → PDF using Qt
            HtmlConverter.Convert(
                html,
                tempFile,
                enableJavaScript: true,
                timeout: 100000,                        // milliseconds
                pageSize: new SizeF(595, 842),          // A4 page size in points
                margins: new PdfMargins(40),            // 40pt margins
                LoadHtmlType.SourceCode                 // Load from HTML string
            );

            // Read the generated PDF into memory
            byte[] fileBytes = System.IO.File.ReadAllBytes(tempFile);

            // Clean up temp file
            System.IO.File.Delete(tempFile);

            // Return PDF to browser as download
            return File(fileBytes, "application/pdf", "HtmlToPdf.pdf");
        }
    }
}

Output:

Create PDF from HTML ASP.NET

This example converts inline HTML into a properly formatted PDF. You can also load external HTML files or URLs - see our detailed guide on Convert HTML to PDF in C# for more information.

Best Practices for ASP.NET PDF Generation

  • Use memory streams instead of disk storage for performance and scalability.
  • Cache static PDFs (like terms & conditions or forms) to reduce server load.
  • Use HTML-to-PDF for dynamic reports with CSS styling.
  • Consider templates (like Word-to-PDF with Spire.Doc) when documents have complex layouts.
  • Secure sensitive PDFs with password protection or access permissions.

Conclusion

With Spire.PDF for .NET, you can easily generate PDF in ASP.NET Core applications. Whether you’re creating PDFs from scratch or performing HTML-to-PDF conversion in C# , Spire.PDF provides a reliable, developer-friendly solution—no external dependencies required.

If you also need to generate PDFs from Word documents, that feature is available via Spire.Doc for .NET, another product in the Spire family. Together, they cover the full range of PDF document generation scenarios.

By integrating these tools, developers can streamline workflows, reduce reliance on Adobe or other third-party components, and ensure consistent, professional-quality output. This makes your ASP.NET PDF solutions more scalable, maintainable, and ready for enterprise use.

FAQs

Q1. Do I need Adobe Acrobat installed on the server?

No. Spire.PDF is a standalone library and works independently of Adobe Acrobat.

Q2. Can I generate PDFs from both raw content and HTML?

Yes. You can build documents programmatically (drawing text, shapes, tables) or convert HTML pages to PDF.

Q3. Can I convert Word documents to PDF with Spire.PDF?

No. Word-to-PDF is supported by Spire.Doc for .NET, not Spire.PDF. You can use them together if your project requires it.

Q4. How can I protect generated PDFs?

Spire.PDF supports setting passwords, permissions, and digital signatures for document security.

Q5. Does Spire.PDF support ASP.NET Framework?

Yes. It works with both ASP.NET Core and ASP.NET Framework.

Get a Free License

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

Page 2 of 95
page 2