Step‑by‑Step .NET tutorial to create a histogram in Excel

When analyzing numeric datasets such as exam scores, sales figures or sensor readings, professionals often need to visualize data distribution. A histogram chart is the standard statistical chart for this purpose.

With Spire.XLS for .NET, C# developers can programmatically create a histogram chart in Excel without installing Microsoft Office on the runtime machine. This tutorial covers:

What Is a Histogram Chart?

A histogram chart is a statistical chart that shows how numerical data is distributed across a series of ranges called bins. Instead of plotting every individual value, a histogram groups values into intervals and uses each bar's height to show how many values fall into that interval.

In C# automation scenarios, histogram charts help developers quickly reveal a dataset’s central tendency, value spread, shape, and outliers for reporting purposes.

A typical histogram has three core elements:

Element What It Represents
X‑axis The numerical bin intervals — for example, [160, 168), [168, 176), [176, 184)
Y‑axis The frequency or count of values that fall into each bin
Bars One bar per bin; the bar height equals the number of observations in that interval

Unlike a standard column chart, histogram bars usually touch or have a very small gap because the x‑axis represents a continuous numerical range, not separate categories.

Setting Up Your Project

Before you start, make sure you have:

  • Visual Studio (or any .NET IDE)
  • .NET Framework 4.5+, .NET Core, or .NET 5+
  • Spire.XLS 11.10.5 or later installed via NuGet

Install the package from the Package Manager Console:

Install-Package Spire.XLS

Step-by-Step: C# Histogram Chart Generation

Step 1: Load or Create a Workbook with Data

A histogram requires a range of numerical values. If you already have an Excel file with source data, load it as follows:

Workbook workbook = new Workbook();
workbook.LoadFromFile("Data.xlsx");
Worksheet sheet = workbook.Worksheets[0];

If you prefer to build the data in code, you can create a new workbook and write an array of numbers into a column. Example:

Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];

// Sample raw numeric data: student exam scores
sheet.Range["A1"].Text = "Exam Scores";
double[] scores = { 55, 62, 68, 70, 72, 75, 77, 80, 82, 85, 88, 90, 91, 94, 96 };
for (int i = 0; i < scores.Length; i++)
{
    sheet.Range[$"A{i + 2}"].NumberValue = scores[i];
}

Step 2: Add a Chart Object and Set the Type to Histogram

With the data in place, add a chart to the worksheet and explicitly set its type to ExcelChartType.Histogram. This is the core step that tells Spire.XLS to render a histogram rather than a standard column chart.

Chart histogramChart = sheet.Charts.Add();
histogramChart.ChartType = ExcelChartType.Histogram;

✅ Remarks: The ExcelChartType enumeration contains over 70 chart types, including pie chart, bar chart, waterfall chart, etc.

Step 3: Bind the Data Range to Chart

Next, assign the numerical data range to the chart. For a histogram, you typically select a single column of values — the chart engine automatically calculates the frequency distribution for you.

histogramChart.DataRange = sheet.Range["A1:A16"];

Step 4: Configure the Bins (Axis Grouping)

Spire.XLS gives you two primary ways to control binning on the category axis. Enable only one of the following:

// Option A: Set a fixed bin width
histogramChart.PrimaryCategoryAxis.BinWidth = 10;
// Option B: Specify the number of bins
histogramChart.PrimaryCategoryAxis.NumberOfBins = 5;

Step 5: Format the Chart for Readability

Default generated charts often need adjustment for presentation: bar gap, titles, legend, position, and data labels.

// Set Gap Width
histogramChart.Series[0].DataFormat.Options.GapWidth = 6;

// Add Chart and Axis Titles
histogramChart.ChartTitle = "Distribution of Exam Scores";
histogramChart.PrimaryValueAxis.Title = "Frequency";
histogramChart.PrimaryCategoryAxis.Title = "Score Bins";

// Chart position
histogramChart.LeftColumn = 3;
histogramChart.TopRow = 3;
histogramChart.RightColumn = 10;
histogramChart.BottomRow = 20;

// Hide the Legend
histogramChart.HasLegend = false;

// Show data labels
var labels = histogramChart.Series[0].DataPoints.DefaultDataPoint.DataLabels;
labels.HasValue = true;
labels.Size = 9;

Step 6: Save the Workbook

Finally, save the workbook to an .xlsx file. Spire.XLS supports multiple Excel versions, but as histogram charts require Excel 2016 or later; save as ExcelVersion.Version2016 or newer.

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

Full C# Code for Creating a Histogram in Excel

using Spire.Xls;

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

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

            // Sample raw numeric data: student exam scores
            sheet.Range["A1"].Text = "Exam Scores";
            double[] scores = { 55, 62, 68, 70, 72, 75, 77, 80, 82, 85, 88, 90, 91, 94, 96 };
            for (int i = 0; i < scores.Length; i++)
            {
                sheet.Range[$"A{i + 2}"].NumberValue = scores[i];
            }

            // Add histogram chart to sheet
            Chart histogramChart = sheet.Charts.Add();
            histogramChart.ChartType = ExcelChartType.Histogram;

            // Bind data range to the histogram
            histogramChart.DataRange = sheet.Range["A1:A16"];

            // Set a Fixed Bin Width
            histogramChart.PrimaryCategoryAxis.BinWidth = 10;
            // (Optional) Specify the Number of Bins
            // histogramChart.PrimaryCategoryAxis.NumberOfBins = 5;

            // Set Gap Width
            histogramChart.Series[0].DataFormat.Options.GapWidth = 6;

            // Add Chart and Axis Titles
            histogramChart.ChartTitle = "Distribution of Exam Scores";
            histogramChart.PrimaryValueAxis.Title = "Frequency";
            histogramChart.PrimaryCategoryAxis.Title = "Score Bins";

            // Chart position
            histogramChart.LeftColumn = 3;
            histogramChart.TopRow = 3;
            histogramChart.RightColumn = 10;
            histogramChart.BottomRow = 20;

            // Hide the Legend
            histogramChart.HasLegend = false;

            // Show data labels
            var labels = histogramChart.Series[0].DataPoints.DefaultDataPoint.DataLabels;
            labels.HasValue = true;
            labels.Size = 9;

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

        }
    }
}

After running the code, open the Histogram_chart.xlsx file, you will see a fully rendered histogram with the bin settings, titles, and formatting applied.

Create an Excel histogram chart with C# and Spire.XLS

Frequently Asked Questions

Q: What is the difference between BinWidth and NumberOfBins?

  • BinWidth fixes the width of each interval and calculates the number of bins automatically.
  • NumberOfBins fixes the number of intervals and calculates the width automatically.

For histograms, you generally use one or the other depending on whether you want consistent interval sizes or a specific level of detail.

Q: Does Spire.XLS support exporting the histogram to PDF or images?

Yes. After building the chart, you can call workbook.SaveToFile("output.pdf", FileFormat.PDF) or use the chart‑to‑image conversion methods to export the chart as an image for reports or web dashboards.

Q: Can I create multiple histograms in one workbook?

Yes. Add separate charts to worksheets or to different positions on the same sheet. For multiple distributions, creating one histogram per numeric column is usually clearer than combining them.

Q: Is a histogram the same as a column chart?

No. A histogram shows the distribution of continuous numerical data across bins; a column chart compares values across separate categories.

Conclusion

Making a histogram chart in Excel with C# is a straightforward process when you use Spire.XLS for .NET. By following the steps in this guide, developers can embed automated histogram generation directly into .NET workflows, eliminating manual chart creation in Excel. It supports flexible customization of axes, styles, and chart titles to fit different reporting and data analysis requirements.

Explore the official documentation for additional charting and Excel‑processing capabilities.

Export data to Excel in C# with Spire.XLS: source data, workbook, formatted XLSX

An export starts from one of five places: a DataTable built in code, a SQL query, a List<T>, a DataSet, or the grid a user is looking at. All five end at the same method — Worksheet.InsertDataTable — and the real work is getting each source into that shape without losing its types along the way.

This guide covers the full distance with Spire.XLS for .NET, a library that writes XLSX files without Microsoft Excel or Office Interop installed. The examples follow one logistics ledger: a shipment table, the SQL Server query behind it, a carrier list, a returns table, and a grid bound to the same rows. The layout is deliberate — sections 4 through 8 build the workbook, section 9 polishes it, section 10 keeps it standing under large result sets, and section 11 hands it to the user.

Quick Navigation

  1. Which Export Path Fits Your Data
  2. Why Not Excel Interop
  3. Set Up the Project
  4. Export a DataTable to Excel in C#
  5. Export Database Data to Excel in C#
  6. Export a List to Excel in C#
  7. Export a DataSet to Multiple Worksheets
  8. Export DataGridView and GridView Data
  9. Format the Exported Worksheet
  10. Keep Data Types and Handle Large Exports
  11. Serve the Export from ASP.NET Core
  12. Frequently Asked Questions
  13. Summary

1. Which Export Path Fits Your Data

The source object decides how much conversion happens before the insert. InsertDataTable accepts a DataTable, so every other source is a small transformation into that shape:

Source Convert to Main call Output
DataTable Nothing Worksheet.InsertDataTable() One worksheet
SQL query / DbDataReader DataTable DataAdapter.Fill(), then InsertDataTable() One worksheet
List<T> DataTable InsertDataTable() after property mapping One worksheet
DataSet Nothing per table InsertDataTable() inside a table loop One worksheet per table
DataGridView / GridView The bound DataTable, or a copy of the rows InsertDataTable() One worksheet
Any of the above, for a download MemoryStream Workbook.SaveToStream() Browser download

Two facts about InsertDataTable carry through every section below. Header text comes from DataColumn.ColumnName or the property name. Cell types come from the column's DataType: a column typed as string stays text in Excel even when every value looks like a number. That is exactly what you want for product codes and postal codes, and it is also the usual reason dates and amounts arrive as text — the column type was wrong at the source.


2. Why Not Excel Interop

Search for this topic and one of the top results is a Microsoft article from 2005 that automates Excel through COM Interop. It answered the question twenty years ago. Today the same approach breaks in the environments where C# code actually runs: web servers, Windows services, build agents, Linux containers.

Interop drives the Excel application itself. The code starts Excel, opens a workbook, writes cells one COM call at a time, then quits the application. Every step assumes a machine with Office installed and an interactive desktop session a user could log into. Microsoft's own guidance, "Considerations for server-side automation of Office", states that Office was never designed for unattended server use. Application pools recycle, desktop sessions disappear, and the EXCEL.EXE processes your code started keep running with nobody left to close them. On a Linux container there is no Excel to start, so the code fails before it writes a single cell.

A library that writes the XLSX file format directly takes the application out of the picture. Spire.XLS builds the package itself, so nothing needs Excel installed, there are no COM references to release, and the same code runs on Windows, Linux, and macOS:

Excel Interop Spire.XLS
Excel installed on the machine Required Not required
Interactive desktop session Required Not required
Windows service / IIS app pool Unsupported by Microsoft Supported
Linux / macOS containers Not available Supported
Cleanup Release every COM object, or EXCEL.EXE processes leak Dispose the Workbook
Writing rows One COM call per cell One bulk insert per block

The rest of this guide uses Spire.XLS for those reasons. If you maintain existing Interop code, the migration is mechanical: the per-cell write loops become single InsertDataTable calls, and the application lifecycle code goes away entirely.


3. Set Up the Project

Install the package:

Install-Package Spire.XLS

Add the namespace to the file that builds the workbook:

using Spire.Xls;

The library targets .NET Framework 4.6.2 and later, .NET Core, and .NET 5 through .NET 10, and runs on Windows, Linux, and macOS servers. Nothing in this guide references Microsoft.Office.Interop.Excel or asks for an Office installation.


4. Export a DataTable to Excel in C#

A DataTable is already the shape InsertDataTable expects, which makes it the baseline every other section builds on. The method takes the table, a flag for column headers, the starting row and column, and a flag that converts column types to Excel cell types.

using System;
using System.Data;
using Spire.Xls;

class Program
{
    static void Main()
    {
        DataTable shipments = BuildShipments();

        Workbook workbook = new Workbook();
        workbook.Worksheets.Clear();
        Worksheet sheet = workbook.Worksheets.Add("Shipments");

        // Headers on, start at A1, convert DataTable types to Excel types
        sheet.InsertDataTable(shipments, true, 1, 1, true);

        sheet.AllocatedRange.AutoFitColumns();
        workbook.SaveToFile("shipments.xlsx", FileFormat.Version2016);
    }

    static DataTable BuildShipments()
    {
        DataTable table = new DataTable("Shipments");
        table.Columns.Add("Shipment ID", typeof(int));
        table.Columns.Add("Destination", typeof(string));
        table.Columns.Add("Shipped On", typeof(DateTime));
        table.Columns.Add("Weight (kg)", typeof(double));
        table.Columns.Add("Freight Cost", typeof(decimal));
        table.Columns.Add("Delivered", typeof(bool));

        table.Rows.Add(4812, "Rotterdam", new DateTime(2026, 9, 3), 1240.5, 3180.00m, true);
        table.Rows.Add(4813, "Hamburg", new DateTime(2026, 9, 4), 860.0, 2145.50m, true);
        table.Rows.Add(4814, "Lyon", new DateTime(2026, 9, 7), 2750.25, 5960.75m, false);
        table.Rows.Add(4815, "Gdańsk", new DateTime(2026, 9, 8), 415.75, 980.00m, false);

        return table;
    }
}

The saved workbook holds one sheet named Shipments, with the six headers in row 1 and eight data rows below them. Numeric columns arrive as numbers, the DateTime column as dates, and Delivered as TRUE/FALSE. AutoFitColumns() sizes each column to its widest value.

A new Workbook opens with three blank worksheets. Worksheets.Clear() removes them before the named sheet is added; without it, the file ships with Sheet2 and Sheet3 sitting next to your data. Clearing first is shorter than deleting the extras afterward, and it keeps the sheet order predictable.

Exported DataTable opened in Excel: headers in row 1, typed columns, fitted widths

InsertDataTable returns the number of rows it wrote. When the source table comes from a query you do not control — the database path in the next section, for instance — that return value is the cheapest way to notice an empty result before your users do.

For the DataTable-only version of this task, see export a DataTable to Excel.


5. Export Database Data to Excel in C#

A database export is a DataTable export with one step in front of it: run the query, fill a DataTable with the result, then reuse the same InsertDataTable call from the previous section. DataAdapter.Fill does the filling. The example below uses Microsoft.Data.SqlClient (Install-Package Microsoft.Data.SqlClient); the same pattern applies to every ADO.NET provider.

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

class Program
{
    static void Main()
    {
        DataTable shipments = QueryShipments(
            "Server=.;Database=FreightLedger;Trusted_Connection=True;TrustServerCertificate=True");

        Workbook workbook = new Workbook();
        workbook.Worksheets.Clear();
        Worksheet sheet = workbook.Worksheets.Add("Shipments");
        sheet.InsertDataTable(shipments, true, 1, 1, true);
        sheet.AllocatedRange.AutoFitColumns();

        workbook.SaveToFile("shipments.xlsx", FileFormat.Version2016);
    }

    static DataTable QueryShipments(string connectionString)
    {
        using SqlDataAdapter adapter = new SqlDataAdapter(
            "SELECT ShipmentID   AS [Shipment ID], " +
            "       Destination, " +
            "       ShippedOn    AS [Shipped On], " +
            "       WeightKg     AS [Weight (kg)], " +
            "       FreightCost  AS [Freight Cost], " +
            "       Delivered " +
            "FROM dbo.Shipments",
            connectionString);

        DataTable table = new DataTable("Shipments");
        adapter.Fill(table);
        return table;
    }
}

Fill opens the connection when it is closed and closes it again when the query finishes, so the connection string is the only thing the method needs. The using on the adapter disposes what Fill creates along the way.

The SQL Server result and the exported workbook: adapter.Fill feeds InsertDataTable

The column types come from the query result, not from anything you declare: INT arrives as Int32, DECIMAL as Decimal, DATETIME2 as DateTime, BIT as Boolean. With transTypes: true those map straight onto Excel cell types, so dates and amounts behave in the spreadsheet. The aliases in the SELECT list (AS [Shipped On]) control the header text. A computed column keeps whatever type SQL gives it — cast CONCAT results if you want them treated as text.

The pattern is identical for other databases. Swap in NpgsqlDataAdapter for PostgreSQL or MySqlDataAdapter from MySqlConnector; both fill a DataTable the same way, and the export code does not change.

Two cautions scale with the data. First, when a result set can run past a million rows, page on the query side — OFFSET/FETCH or keyset pagination — and write one workbook per page, instead of materializing the whole table in memory. Section 10 covers the sheet limits you are paging against. Second, if you are working in EF Core, await context.Shipments.ToListAsync() hands you a List<Shipment>, and the ToDataTable helper in the next section turns it into the DataTable this path expects.

The reverse direction — loading an existing workbook into a DataTable — is covered in import Excel data into a DataTable.


6. Export a List to Excel in C#

InsertDataTable has no List<T> overload, so the list is projected into a DataTable first. A small generic helper carries over the property names and the property types, and those types are what make the exported dates and amounts behave correctly in Excel.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using Spire.Xls;

public class Carrier
{
    public int CarrierId { get; set; }
    public string CarrierName { get; set; }
    public string DispatchEmail { get; set; }
    public int FleetSize { get; set; }
    public double OnTimeRate { get; set; }
    public bool Active { get; set; }
}

static class ListExport
{
    public static DataTable ToDataTable<T>(IEnumerable<T> items)
    {
        PropertyInfo[] properties = typeof(T)
            .GetProperties(BindingFlags.Public | BindingFlags.Instance);

        DataTable table = new DataTable(typeof(T).Name);

        foreach (PropertyInfo property in properties)
        {
            Type columnType = Nullable.GetUnderlyingType(property.PropertyType)
                              ?? property.PropertyType;
            table.Columns.Add(property.Name, columnType);
        }

        foreach (T item in items)
        {
            table.Rows.Add(properties
                .Select(property => property.GetValue(item) ?? DBNull.Value)
                .ToArray());
        }

        return table;
    }

    public static void Export(IEnumerable<Carrier> carriers, string path)
    {
        DataTable table = ToDataTable(carriers);

        Workbook workbook = new Workbook();
        workbook.Worksheets.Clear();
        Worksheet sheet = workbook.Worksheets.Add("Carriers");
        sheet.InsertDataTable(table, true, 1, 1, true);
        sheet.AllocatedRange.AutoFitColumns();

        workbook.SaveToFile(path, FileFormat.Version2016);
    }
}

Call ListExport.Export(...) with the list you already have. A row looks like 201 | Nordic Freight Line | [email protected] | 42 | 0.962 | TRUE, with the property names used as headers.

Exported List<Carrier>: property names as headers, a numeric on-time-rate column

The helper handles nullable value types by exporting the underlying type, so decimal? becomes a numeric column instead of an object column. To leave a property out of the file, filter it from the properties array before the loop, or project the list into a separate export type.

For a list you build by hand rather than project, InsertArray writes a two-dimensional array in one call:

object[,] rows =
{
    { 4812, "Rotterdam", new DateTime(2026, 9, 3), 3180.00m },
    { 4813, "Hamburg",   new DateTime(2026, 9, 4), 2145.50m }
};

workbook.Worksheets.Clear();
Worksheet sheet = workbook.Worksheets.Add("Manual Rows");
sheet.InsertArray(rows, 2, 1);
sheet.Range[1, 1].Text = "Shipment ID";
sheet.Range[1, 2].Text = "Destination";
sheet.Range[1, 3].Text = "Shipped On";
sheet.Range[1, 4].Text = "Freight Cost";

InsertArray(rows, 2, 1) starts at row 2 so the header line stays free. This path suits fixed reports where the columns are known at compile time.

For more on this single source, see export a List to Excel in C#.


7. Export a DataSet to Multiple Worksheets

A DataSet is a collection of DataTable objects, so one worksheet per table is a loop. A DataSet often arrives straight from a database — one adapter can fill several tables in a single Fill call, as in section 5 — and the loop below handles it the same way regardless of where the tables came from.

using System.Data;
using Spire.Xls;

static void ExportDataSet(DataSet ledger, string path)
{
    Workbook workbook = new Workbook();
    workbook.Worksheets.Clear();

    foreach (DataTable table in ledger.Tables)
    {
        Worksheet sheet = workbook.Worksheets.Add(table.TableName);
        sheet.InsertDataTable(table, true, 1, 1, true);
        sheet.AllocatedRange.AutoFitColumns();
    }

    workbook.SaveToFile(path, FileFormat.Version2016);
}

With a DataSet named FreightLedger that holds Shipments and Returns, the result is a two-sheet workbook: Shipments and Returns. Each sheet repeats its own header row, and the two tables keep independent column sets.

DataSet export: one worksheet per DataTable, sheet tabs named after TableName

Excel restricts sheet names to 31 characters and rejects the characters : \ / ? * [ ]. TableName often comes from a query or a user, so normalize it before Worksheets.Add:

static string SafeSheetName(string name)
{
    foreach (char c in new[] { ':', '\\', '/', '?', '*', '[', ']' })
        name = name.Replace(c, '_');

    return name.Length > 31 ? name.Substring(0, 31) : name;
}

Duplicate names also fail. If two tables share a name, append an index before adding the sheet.


8. Export DataGridView and GridView Data

A grid is a view over data you already have. When it is bound to a DataTable, export that table and let the grid stay a display concern:

using System;
using System.Data;
using System.Windows.Forms;
using Spire.Xls;

static void ExportBoundGrid(DataGridView grid, string path)
{
    DataTable table = grid.DataSource as DataTable;
    if (table == null)
        throw new InvalidOperationException("Bind the grid to a DataTable before exporting.");

    Workbook workbook = new Workbook();
    workbook.Worksheets.Clear();
    Worksheet sheet = workbook.Worksheets.Add("Grid Export");
    sheet.InsertDataTable(table, true, 1, 1, true);
    workbook.SaveToFile(path, FileFormat.Version2016);
}

The same idea applies to an ASP.NET Web Forms GridView backed by a DataSet or DataTable: export the source table rather than scraping rendered HTML. A grid bound to a list of objects goes through the ToDataTable helper from section 6.

An unbound DataGridView has no table behind it, so the cells have to be copied into a DataTable first. That path, including column types and the new-row check, is covered in export DataGridView to Excel in C#.


9. Format the Exported Worksheet

A raw export is fine for a machine reader. Before the file goes to a person, it needs a header style, number formats, and a frozen header row. Apply all three after the data is inserted, so the ranges cover the real last row.

using System.Drawing;
using Spire.Xls;

static void FormatSheet(Workbook workbook, Worksheet sheet, int columnCount)
{
    CellStyle headerStyle = workbook.Styles.Add("ShipmentHeader");
    headerStyle.Font.IsBold = true;
    headerStyle.Font.Size = 12;
    headerStyle.Font.Color = Color.White;
    headerStyle.Color = Color.FromArgb(31, 78, 121);
    headerStyle.HorizontalAlignment = HorizontalAlignType.Center;
    headerStyle.VerticalAlignment = VerticalAlignType.Center;

    sheet.Range[1, 1, 1, columnCount].Style = headerStyle;
    sheet.Rows[0].RowHeight = 22;

    int lastRow = sheet.LastRow;
    sheet.Range[2, 3, lastRow, 3].NumberFormat = "yyyy-mm-dd";
    sheet.Range[2, 4, lastRow, 4].NumberFormat = "#,##0.0";
    sheet.Range[2, 5, lastRow, 5].NumberFormat = "#,##0.00";

    sheet.FreezePanes(2, 1);
    sheet.AllocatedRange.AutoFitColumns();
}

The style is registered once through workbook.Styles.Add and assigned to the header range in a single call. FreezePanes(2, 1) keeps row 1 visible while the reader scrolls, and the three NumberFormat assignments give the date and money columns a display format without changing their stored values.

Formatted shipment sheet: styled header, date and currency formats, frozen header row

Number formats are display rules, not type conversions. A decimal column written with #,##0.00 still holds the full value, and Excel can sum it. Text that was stored as a string stays left-aligned no matter which format you apply.

Fonts, colors, borders, and conditional styles are covered in Format Excel Files in C#.


10. Keep Data Types and Handle Large Exports

Three details decide whether a large export arrives usable: the type conversion flag, the sheet limit, and the way rows are written.

Pass transTypes: true. The fifth argument of InsertDataTable converts DataTable column types to Excel cell types. With false, numeric and date columns can land as text. The overload is InsertDataTable(dataTable, columnHeaders, firstRow, firstColumn, transTypes).

Respect the sheet limit. An XLSX worksheet holds 1,048,576 rows and 16,384 columns. A query that returns more rows needs splitting:

const int RowsPerSheet = 1_000_000;

int sheetIndex = 0;
for (int offset = 0; offset < table.Rows.Count; offset += RowsPerSheet)
{
    DataTable slice = table.Clone();
    for (int i = offset; i < Math.Min(offset + RowsPerSheet, table.Rows.Count); i++)
        slice.ImportRow(table.Rows[i]);

    Worksheet sheet = workbook.Worksheets.Add($"Part {++sheetIndex}");
    sheet.InsertDataTable(slice, true, 1, 1, true);
}

Clone() copies the schema without the rows, and ImportRow keeps the column types. The header row repeats on each sheet, which keeps every part readable on its own.

When the source is a database, do this splitting at the query — OFFSET/FETCH per page, as shown in section 5 — rather than materializing the full result set and slicing it in memory. The loop above is for tables you already have in hand.

Write rows in bulk. InsertDataTable and InsertArray cross into the worksheet once per block; assigning each cell through Range crosses once per cell. In a local test with Spire.XLS 16.10.3 on .NET 10, building and saving a 100,000-row, six-column workbook took about 2.5 seconds through InsertDataTable and about 4 seconds through per-cell assignments, which also stored every value as text. For sheets that large, prefer fixed widths (sheet.Columns[i].ColumnWidth = 18) over AutoFitColumns(); autofit has to inspect every cell in the used range to size each column.


11. Serve the Export from ASP.NET Core

Everything so far produced a file on disk. In a web application the export usually ends as a browser download, and the workbook should never touch disk on the way. This section turns the export into a service: one interface, a DI registration, an authorized controller endpoint, and a Minimal API variant that reuses the same service.

The service owns the query and the workbook build. The data source is the database query from section 5, so the web path and the console path share one shape:

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

public interface IShipmentExportService
{
    Workbook Build();
}

public class ShipmentExportService : IShipmentExportService
{
    private const string ShipmentsSql =
        "SELECT ShipmentID  AS [Shipment ID], " +
        "       Destination, " +
        "       ShippedOn   AS [Shipped On], " +
        "       WeightKg    AS [Weight (kg)], " +
        "       FreightCost AS [Freight Cost], " +
        "       Delivered " +
        "FROM dbo.Shipments";

    private readonly string _connectionString;
    private readonly ILogger<ShipmentExportService> _logger;

    public ShipmentExportService(IConfiguration configuration,
        ILogger<ShipmentExportService> logger)
    {
        _connectionString = configuration.GetConnectionString("FreightLedger")
            ?? throw new InvalidOperationException(
                "Connection string 'FreightLedger' is not configured.");
        _logger = logger;
    }

    public Workbook Build()
    {
        using SqlConnection connection = new SqlConnection(_connectionString);
        using SqlDataAdapter adapter = new SqlDataAdapter(ShipmentsSql, connection);

        DataTable shipments = new DataTable("Shipments");
        adapter.Fill(shipments);

        Workbook workbook = new Workbook();
        workbook.Worksheets.Clear();
        Worksheet sheet = workbook.Worksheets.Add("Shipments");

        int rows = sheet.InsertDataTable(shipments, true, 1, 1, true);
        sheet.AllocatedRange.AutoFitColumns();

        _logger.LogInformation("Shipment export wrote {RowCount} rows.", rows);
        return workbook;
    }
}

The query runs synchronously because DataAdapter.Fill has no async overload. If a large result set should not block the request thread, read it with await command.ExecuteReaderAsync() into a DataTable instead — the workbook part stays the same.

Register it as scoped:

builder.Services.AddScoped<IShipmentExportService, ShipmentExportService>();

The controller stays thin — build, save to a MemoryStream, return the bytes:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Spire.Xls;

[ApiController]
[Route("api/shipments")]
public class ShipmentExportController : ControllerBase
{
    private readonly IShipmentExportService _exportService;

    public ShipmentExportController(IShipmentExportService exportService)
    {
        _exportService = exportService;
    }

    [HttpGet("export")]
    [Authorize]
    public IActionResult Export()
    {
        Workbook workbook = _exportService.Build();

        using MemoryStream stream = new MemoryStream();
        workbook.SaveToStream(stream, FileFormat.Version2016);

        return File(
            stream.ToArray(),
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "shipments.xlsx");
    }
}

A Minimal API route reuses the same service without the controller class:

app.MapGet("/api/shipments/export", (IShipmentExportService exportService) =>
{
    Workbook workbook = exportService.Build();

    MemoryStream stream = new MemoryStream();
    workbook.SaveToStream(stream, FileFormat.Version2016);
    stream.Position = 0;

    return Results.File(
        stream,
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "shipments.xlsx");
})
.RequireAuthorization();

Four decisions in this code are worth spelling out.

One Workbook per request, never a singleton. A Workbook is one document held in memory, and it is not thread-safe. A singleton service that kept a Workbook would serialize every request through a single file and leak rows between users. The service above creates the Workbook inside Build, so each request builds its own; the scoped registration matches that lifetime. The FAQ at the end of this guide has a dedicated entry on this, because it is the most common way these exports go wrong.

[Authorize] on the endpoint. An export endpoint returns a full table in one request, which makes it exactly the kind of URL that gets shared around or crawled if it responds anonymously. Require authentication, and if some roles should see fewer columns, shape that in the query or a DTO — the workbook code does not need to know about permissions.

ToArray() versus returning the stream. ToArray() copies the bytes once, which is fine for reports up to a few megabytes and lets the using block dispose the stream early. For large workbooks, skip the copy: save to the stream, set stream.Position = 0, and return File(stream, contentType, fileName) — ASP.NET Core writes it to the response and disposes the stream afterward. The Minimal API variant above shows that form.

Log the row count. InsertDataTable returns the rows it wrote, and the service logs it. When the query returns nothing — a filtered date range with no matches, a connection that fell back to an empty schema — the log tells you before a user opens an empty file and files a report of their own.

The response headers are the part users notice when something is wrong. The file name in the third argument of File() sets Content-Disposition, and the MIME type above is the one Excel and browsers expect for .xlsx. A text/csv type with an .xlsx extension produces a download that opens with a warning.

When the deliverable is a PDF report rather than a workbook, the same worksheet saves straight to PDF — see Convert Worksheet to PDF in C#.


12. Frequently Asked Questions

How do I export a DataTable to Excel in C#?

Create a Workbook, clear its default sheets, add one with Worksheets.Add("Shipments"), and call InsertDataTable(table, true, 1, 1, true). Save with SaveToFile(path, FileFormat.Version2016). The four positional arguments after the table mean headers on, start at row 1, start at column 1, and convert column types.

How do I export SQL query results to Excel in C#?

Fill a DataTable from the query with a DataAdapter — adapter.Fill(table) — then pass the table to InsertDataTable. Section 5 shows the full path, including where the column types come from, how the connection gets released, and how to page large result sets at the query level.

How do I export to Excel without Excel installed?

Use a library that writes the XLSX package directly. Section 2 covers why Interop needs Excel and a desktop session; Spire.XLS uses neither, so the same code runs in a console app, a Windows service, an ASP.NET Core request, a build agent, a Linux container, and Azure App Service.

Why are my dates and numbers stored as text?

The DataTable column type is usually string, because the values came from a CSV import or a SELECT that returned text. Excel stores what the column type says. Declare the column as typeof(DateTime) or typeof(decimal), or cast the values before adding the row. After insertion, a NumberFormat changes only the display, not the stored type.

Why does my exported workbook contain blank Sheet2 and Sheet3?

A new Workbook starts with three worksheets. You renamed or wrote into the first one and left the other two in place. Call workbook.Worksheets.Clear() before adding your own sheet, or remove the extras with workbook.Worksheets[1].Remove() while the count is greater than one.

Can I export to Excel in C# on Linux?

Yes. The code in this guide uses no COM and no Windows-only API. Spire.XLS for .NET writes the XLSX package itself, so the same code runs in a Linux container, on a build agent, and in Azure App Service.

How do I export multiple tables to one workbook?

Loop over the tables, add a worksheet for each one, and call InsertDataTable on that sheet. workbook.Worksheets.Clear() removes the default sheet first. Use TableName for the sheet name after replacing the characters Excel rejects.

How do I export only selected columns?

Build a DataView with the columns you want and export view.ToTable():

DataTable subset = new DataView(shipments).ToTable(false, "Shipment ID", "Destination", "Freight Cost");
sheet.InsertDataTable(subset, true, 1, 1, true);

The false argument means distinct rows are not required. The column list keeps the original order.

How do I keep leading zeros in codes?

Make the column type string, so 00731 stays 00731. A numeric column cannot keep the leading zero: the value is parsed as 731, and a NumberFormat only changes how that number is displayed. String columns are the reliable option for postal codes, SKUs, and account numbers.

Can I register the Workbook as a singleton in ASP.NET Core?

No. A Workbook holds one document in memory and is not thread-safe, so a shared instance would mix rows from concurrent requests. Register the export service as scoped and create a new Workbook per request, as section 11 does.

Can I export to XLS instead of XLSX?

Yes. Pass FileFormat.Version97to2003 to SaveToFile. The legacy XLS format caps a worksheet at 65,536 rows and offers fewer style options, so keep XLSX unless a downstream system requires the older format.


13. Summary

Every path in this guide converges on one method. A DataTable goes into InsertDataTable as it is. A database query fills a DataTable first, with the column types supplied by the query itself. A List<T> is projected through property mapping. A DataSet becomes one worksheet per table. A grid exports the table it is bound to.

Delivery has two exits. SaveToFile writes a file to disk; SaveToStream feeds everything else — an ASP.NET Core download, an email attachment, a blob upload. Wrapping the build in a scoped service keeps the controller thin and gives the same code to a Minimal API route or a background job, with authentication and a row-count log line as the standard trimmings.

The production details hold regardless of source: pass transTypes: true, keep each sheet under 1,048,576 rows, write blocks of rows instead of individual cells, and apply formatting after the data so the ranges match what was actually written.

For commercial use of the advanced capabilities, you can request a free temporary license to evaluate the full build; the evaluation build adds a warning worksheet to saved workbooks.

How to Convert Markdown to PDF in C#

2026-11-27 08:57:50 Written by alice yang

Convert Markdown files and strings to PDF in C#

Markdown is commonly used for README files, technical documentation, release notes, and application-generated reports. Converting Markdown to PDF makes this content easier to share, print, and distribute to readers without a Markdown viewer.

Starting with version 12.11.11, Spire.PDF for .NET supports direct Markdown-to-PDF conversion. This tutorial shows how to convert Markdown files and strings to PDF in C#, customize page size and margins during conversion, and modify the generated PDF before saving it.

Table of Contents

Install Spire.PDF for .NET

To convert Markdown to PDF in C#, install Spire.PDF for .NET via NuGet or download the DLL files and add the appropriate references to your project.

Package Manager Console:

Install-Package Spire.PDF

.NET CLI:

dotnet add package Spire.PDF

Note: Markdown-to-PDF conversion was introduced in Spire.PDF for .NET 12.11.11. Make sure your project references this version or later.

The MarkdownToPdfConverter class in the Spire.Additions.Markdown namespace provides the following conversion methods. Choose a method based on the source of your Markdown content and whether you need a PDF file or a document object for further processing.

Method Input Output
ConvertToFile(string, string) Markdown file path PDF file
ConvertToFileFromText(string, string) Markdown string PDF file
Convert(string) Markdown file path PdfDocument object
Convert(byte[]) Markdown byte array PdfDocument object
ConvertFromText(string) Markdown string PdfDocument object

All five methods also provide overloads that accept an MdLoadOptions object, allowing you to configure the PDF page dimensions and margins during conversion.

Convert a Markdown File to PDF in C#

To convert a local Markdown (.md) file to PDF, use the MarkdownToPdfConverter.ConvertToFile() method. It accepts the source Markdown file path and the output PDF file path, converting and saving the document in a single call.

Sample Markdown File

For this example, create a file named Sample.md with the following content. It includes headings, formatted text, a table, lists, a code block, a hyperlink, and a blockquote.

# Project Status Report

## Project Overview

The customer portal redesign is currently in the development phase.

**Project Manager:** Sarah Wilson

**Reporting Period:** November 2026

**Project Status:** *In Progress*

## Development Progress

| Task | Status | Completion |
|---|---|---:|
| UI Design | Completed | 100% |
| API Integration | In Progress | 75% |
| Testing | Pending | 0% |

## Upcoming Tasks

1. Complete API integration.
2. Conduct functional testing.
3. Prepare deployment documentation.

## Technical Requirements

- REST API integration
- User authentication
- Automated reporting

## Configuration Example

```json
{
  "project": "Customer Portal",
  "environment": "development"
}
```

## References

[Project Documentation](https://example.com)

> The project remains on schedule.

C# Code Example

The following example converts the Markdown file to a PDF document.

using Spire.Additions.Markdown;

namespace ConvertMarkdownFileToPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            // Specify the input Markdown file
            string inputFile = "Sample.md";

            // Specify the output PDF file
            string outputFile = "MarkdownToPDF.pdf";

            // Convert the Markdown file to PDF
            MarkdownToPdfConverter.ConvertToFile(
                inputFile, outputFile);
        }
    }
}

If you use relative paths as shown in this example, make sure that Sample.md is available in the application's working directory. Alternatively, you can specify absolute paths for both the input and output files.

Conversion Result:

Source Markdown file and converted PDF showing headings, tables, lists, and code blocks

Convert a Markdown String to PDF in C#

Markdown content does not always originate from a file. Your application may generate it dynamically from database records, API responses, user input, or AI-generated content.

The MarkdownToPdfConverter.ConvertToFileFromText() method allows you to convert a Markdown string directly to a PDF file without first writing the content to a temporary .md file.

The following example converts a Markdown string containing product release notes to PDF.

using Spire.Additions.Markdown;

namespace ConvertMarkdownStringToPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            // Define the Markdown content
            string mdString = @"# Product Release Notes

## Version 2.5.0

This release introduces several new features and performance improvements.

### New Features

- Added support for exporting reports.
- Introduced advanced search filters.
- Improved dashboard navigation.

### Bug Fixes

- Fixed incorrect date formatting.
- Resolved issues with file uploads.

**Release Status:** Available";

            // Convert the Markdown string to PDF
            MarkdownToPdfConverter.ConvertToFileFromText(
                mdString, "ReleaseNotes.pdf");
        }
    }
}

Conversion Result:

PDF release notes generated from a Markdown string in C#

Customize Page Size and Margins When Converting Markdown to PDF

By default, Spire.PDF converts Markdown content to an A4 PDF document with one-inch margins on all sides. For documents containing wide tables, long code blocks, or content intended for printing, you may need to adjust the page size, orientation, or margins.

The MdLoadOptions class allows you to configure the PDF page layout before converting Markdown. It provides the following properties:

Property Description Default Value
Width Sets the page width in points. 595.276 pt
Height Sets the page height in points. 841.89 pt
Margin Sets the page margins through a MarginInfo object. 72 pt on each side

All measurements are specified in points (1 inch = 72 points). You can use the dimensions of a standard paper size or specify custom values.

Page Size Width (pt) Height (pt)
A4 Portrait 595.276 841.89
A4 Landscape 841.89 595.276
A5 Portrait 419.528 595.276
US Letter Portrait 612 792
US Letter Landscape 792 612
US Legal Portrait 612 1008

The following example converts a Markdown file to a US Letter PDF in landscape orientation with half-inch margins on all sides.

using Spire.Additions.Markdown;

namespace MarkdownToPdfWithCustomLayout
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create Markdown load options
            MdLoadOptions options = new MdLoadOptions();

            // Set the page size to US Letter landscape
            options.Width = 792f;
            options.Height = 612f;

            // Set half-inch margins (left, top, right, bottom)
            options.Margin = new MarginInfo(36f, 36f, 36f, 36f);

            // Convert Markdown to PDF with the custom page layout
            MarkdownToPdfConverter.ConvertToFile(
                "Sample.md", "CustomPageLayout.pdf", options);
        }
    }
}

The MarginInfo constructor accepts four values in the order of left, top, right, and bottom, allowing you to set each margin independently. Using landscape orientation and narrower margins provides more horizontal space for wide tables and other content.

The same MdLoadOptions settings can be applied when converting Markdown strings or byte arrays by passing the options object to the corresponding conversion method. For longer documents, check page breaks and table placement to ensure that content fits within the selected page dimensions.

Note: Creating a MarginInfo object with its parameterless constructor sets all margins to zero. Assigning null to MdLoadOptions.Margin restores the default one-inch margins.

Conversion Result:

Landscape Letter PDF with half-inch margins generated from Markdown

Modify the Generated PDF Before Saving

If you need to set document properties, add watermarks, or perform other PDF operations after converting Markdown, you can work directly with the generated PdfDocument object instead of saving and reopening an intermediate PDF file.

The MarkdownToPdfConverter class provides the following methods for obtaining a PdfDocument object:

  • Convert() – converts a Markdown file or byte array to a PDF document.
  • ConvertFromText() – converts a Markdown string to a PDF document.

The following example uses ConvertFromText() to convert Markdown content, set the PDF title, author, subject, and keywords, and save the modified document.

using Spire.Pdf;
using Spire.Additions.Markdown;

namespace ConvertMarkdownToPdfWithMetadata
{
    class Program
    {
        static void Main(string[] args)
        {
            // Define the Markdown content
            string mdString = @"# Monthly Sales Report

## Sales Summary

| Region | Revenue |
|---|---:|
| North America | $25,000 |
| Europe | $18,500 |
| Asia Pacific | $21,000 |

**Total Revenue:** $64,500

## Remarks

Sales performance remained stable throughout the reporting period.";

            // Convert Markdown to a PDF document object
            PdfDocument doc =
                MarkdownToPdfConverter.ConvertFromText(mdString);

            try
            {
                // Set PDF document properties
                doc.DocumentInformation.Title = "Monthly Sales Report";
                doc.DocumentInformation.Author = "Sales Department";
                doc.DocumentInformation.Subject = "Monthly Revenue Summary";
                doc.DocumentInformation.Keywords = "Sales, Revenue, Monthly Report";

                // Save the modified PDF
                doc.SaveToFile("MonthlySalesReport.pdf");
            }
            finally
            {
                // Release document resources
                doc.Dispose();
            }
        }
    }
}

The metadata set through the DocumentInformation property can be viewed in a PDF reader's document properties dialog. These properties are stored in the PDF document and do not change its visible page content.

If your source content is stored in a Markdown file, use Convert() instead:

PdfDocument doc =
    MarkdownToPdfConverter.Convert("Sample.md");

try
{
    doc.DocumentInformation.Title = "Project Status Report";
    doc.SaveToFile("ProjectStatusReport.pdf");
}
finally
{
    doc.Dispose();
}

You can extend the same workflow to perform other PDF operations, such as adding watermarks to a PDF in C#, before saving the document.

Markdown-to-PDF Conversion Considerations

Supported Markdown Elements

Spire.PDF supports rendering a range of commonly used Markdown elements, including:

  • Headings and paragraphs
  • Bold and italic text
  • Tables
  • Ordered and unordered lists
  • Fenced code blocks
  • Hyperlinks
  • Blockquotes

Markdown dialects, such as GitHub Flavored Markdown (GFM), differ in the syntax they support. If your source documents contain task lists, mathematical expressions, embedded HTML, or other elements not listed above, test their rendering before integrating the conversion into your application.

Images and External Resources

Markdown documents can reference images using relative paths, absolute paths, or URLs. For example:

![Application screenshot](images/dashboard.png)

Image rendering depends on how the referenced resources are resolved and whether they are accessible during conversion. When converting Markdown strings, pay particular attention to relative image paths, as the string itself does not retain the source file's directory.

For applications that convert user-uploaded or other untrusted Markdown content, restrict access to local files and remote resources according to your application's security requirements.

Text Encoding and Font Support

Use UTF-8 encoding for Markdown files to help preserve multilingual text and special characters. The appearance of these characters in the generated PDF also depends on font availability and glyph coverage.

When converting Markdown containing Chinese, Japanese, or other non-Latin scripts, ensure that appropriate fonts are available in the conversion environment and check the output for missing or incorrectly rendered characters.

Frequently Asked Questions

Can I convert Markdown stored in a byte array to PDF in C#?

Yes. The MarkdownToPdfConverter.Convert(byte[]) overload allows you to convert Markdown content stored as a byte array to a PdfDocument object. This is useful when working with file uploads, binary data retrieved from databases, or documents received from web services.

If the Markdown content is already available as a byte array named markdownBytes, you can convert and save it as follows:

PdfDocument doc =
    MarkdownToPdfConverter.Convert(markdownBytes);

try
{
    doc.SaveToFile("MarkdownToPDF.pdf");
}
finally
{
    doc.Dispose();
}

Can I convert Markdown to PDF without creating an intermediate Word document?

Yes. Spire.PDF for .NET provides a dedicated Markdown-to-PDF conversion API. You can convert Markdown files or strings directly to PDF without first converting them to DOCX or creating an intermediate Word document yourself.

Can I convert PDF back to Markdown in C#?

Yes. Spire.PDF for .NET also supports converting PDF to Markdown in C#.

However, Markdown and PDF represent document content differently. Converting a generated PDF back to Markdown may not reproduce the original Markdown syntax or document structure exactly.

Get a Free License

You can request a free 30-day temporary license to evaluate the Markdown-to-PDF conversion and other PDF processing features of Spire.PDF for .NET without evaluation limitations.

Convert Excel to XML in C#: workbook, custom schema, and DataTable output

Converting Excel to XML in C# can mean three different things, and the code you write depends on which one you need. You may want to save an entire workbook as an XML spreadsheet, export a few columns into a custom XML structure for another system, or serialize tabular data with .NET's built-in DataTable.WriteXml(). Each produces a different document, and they are not interchangeable.

This tutorial shows how to convert Excel to XML in C# using Spire.XLS for .NET, a standalone library that reads and writes Excel files without Microsoft Excel or Office Interop installed. You will learn to export a whole workbook as XML Spreadsheet 2003, build a custom XML schema from selected cells, and serialize a DataTable, then handle the data type details that matter in production.

Quick Navigation

  1. Which XML Format Does Excel to XML in C# Produce?
  2. Set Up a .NET Excel-to-XML Project
  3. Convert an Excel Workbook to XML in C#
  4. Export Excel to XML in C# with a Custom Schema
  5. Convert Excel Data to XML with DataTable.WriteXml()
  6. XLS, XLSX, and Data Handling
  7. Frequently Asked Questions
  8. Summary

Which XML Format Does Excel to XML in C# Produce?

Before writing code, decide which XML the receiving system expects. Three formats come up in Excel work, and mixing them up is the most common mistake in this task.

XML type What it is When to use it
XML Spreadsheet 2003 (SpreadsheetML) One XML file describing a workbook, with Workbook, Worksheet, Row, and Cell elements When a downstream tool accepts an Excel 2003 XML spreadsheet
Office Open XML (OOXML) The .xlsx format. It is a ZIP package containing separate XML parts for the workbook, worksheets, styles, and shared strings When you need to read or modify the internal parts of an XLSX file
Custom XML A document whose element names and hierarchy you define When an API, database import, or partner system requires a fixed schema

An XML file whose root is <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"> is XML Spreadsheet 2003. An XLSX file is a ZIP container holding several XML parts rather than one XML document. Because both are described as "XML" in Excel documentation, the two are easy to confuse.

If you are covering the OOXML package format instead, see convert Excel to Open XML in C#. That is a separate topic from this article. If you do not need code at all, the no-code options are covered in other ways to convert Excel to XML.


Set Up a .NET Excel-to-XML Project

Install Spire.XLS for .NET

dotnet add package Spire.XLS

Import the namespace

using Spire.Xls;

The examples below read SalesOrders.xlsx, which has an Orders sheet with columns OrderID, Customer, Region, Product, Quantity, UnitPrice, Amount, OrderDate, and Status, plus a Summary sheet. Both .xls and .xlsx files load through the same LoadFromFile() call.

The sample workbook used in the examples:

Sales order workbook with OrderID, Customer, Region, Product, Quantity, UnitPrice, Amount, OrderDate, and Status columns


Convert an Excel Workbook to XML in C#

To save a whole workbook as an XML spreadsheet, load the file and call Workbook.SaveAsXml().

using Spire.Xls;

using (Workbook workbook = new Workbook())
{
    // Load the Excel workbook.
    workbook.LoadFromFile("SalesOrders.xlsx");

    // Save the workbook as an XML spreadsheet.
    workbook.SaveAsXml("output.xml");
}

SaveToFile("output.xml", FileFormat.XML) produces the same file. In a test with Spire.XLS 16.10.3, the two calls returned documents of identical size and identical MD5 hash, so use whichever reads better in your code.

The output is XML Spreadsheet 2003. An OOXML package is a separate format. A real XML Spreadsheet file starts like this:

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
          xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
          xmlns:x="urn:schemas-microsoft-com:office:excel">
  <ss:Styles>...</ss:Styles>
  <ss:Worksheet ss:Name="Orders">
    <ss:Table ss:DefaultColumnWidth="48.75">
      <Row ss:Index="1">
        <Cell ss:Index="1"><Data ss:Type="String">OrderID</Data></Cell>
        <Cell ss:Index="2"><Data ss:Type="String">Customer</Data></Cell>
        <Cell ss:Index="3"><Data ss:Type="String">Region</Data></Cell>
        <Cell ss:Index="4"><Data ss:Type="String">Product</Data></Cell>
      </Row>
      ...

The exported orders-spreadsheet.xml opened in a text editor:

SpreadsheetML 2003 output with a Workbook root and ss:Worksheet, Row, Cell, and Data elements

To read the file back, use LoadFromXml(). LoadFromXml() reads XML Spreadsheet files, while LoadFromFile() handles XLS and XLSX workbooks.

using (Workbook workbook = new Workbook())
{
    // Load an XML Spreadsheet 2003 file.
    workbook.LoadFromXml("output.xml");
    // Workbook.Worksheets is now available.
}

The export includes the workbook's styles and cell formatting along with the cell data, so the XML document describes the full spreadsheet rather than a bare data table.


Export Excel to XML in C# with a Custom Schema

A workbook export is convenient, but most integrations need their own element names. Converting an Excel spreadsheet to XML with a custom schema usually starts with one range and a fixed set of element names. The sample workbook has these values in the Orders sheet:

OrderID Amount OrderDate
SO-1001 3897.00 2026-10-01
SO-1002 1645.00 2026-10-02
SO-1003 2598.00 2026-10-03

and the target system expects this structure:

<?xml version="1.0" encoding="utf-8"?>
<orders>
  <order>
    <id>SO-1001</id>
    <amount>3897.00</amount>
    <orderDate>2026-10-01</orderDate>
  </order>
  <order>
    <id>SO-1002</id>
    <amount>1645.00</amount>
    <orderDate>2026-10-02</orderDate>
  </order>
  <order>
    <id>SO-1003</id>
    <amount>2598.00</amount>
    <orderDate>2026-10-03</orderDate>
  </order>
</orders>

Export the range to a DataTable, then write the XML yourself with XmlWriter.

using System;
using System.Data;
using System.Globalization;
using System.Text;
using System.Xml;
using Spire.Xls;

using (Workbook workbook = new Workbook())
{
    workbook.LoadFromFile("SalesOrders.xlsx");
    Worksheet sheet = workbook.Worksheets["Orders"];

    var options = new ExportTableOptions
    {
        ExportColumnNames = true,
        KeepDataType = true,
        KeepDataFormat = false,
        ComputedFormulaValue = true
    };

    // AllocatedRange covers only the cells actually used.
    DataTable table = sheet.ExportDataTable(sheet.AllocatedRange, options);

    var settings = new XmlWriterSettings
    {
        Indent = true,
        Encoding = new UTF8Encoding(false)
    };

    using (XmlWriter writer = XmlWriter.Create("orders-custom.xml", settings))
    {
        writer.WriteStartDocument();
        writer.WriteStartElement("orders");

        foreach (DataRow row in table.Rows)
        {
            writer.WriteStartElement("order");

            writer.WriteElementString("id",
                Convert.ToString(row["OrderID"], CultureInfo.InvariantCulture));

            string amount = row.IsNull("Amount")
                ? string.Empty
                : Convert.ToDecimal(row["Amount"], CultureInfo.InvariantCulture)
                         .ToString("F2", CultureInfo.InvariantCulture);
            writer.WriteElementString("amount", amount);

            string orderDate = row.IsNull("OrderDate")
                ? string.Empty
                : Convert.ToDateTime(row["OrderDate"], CultureInfo.InvariantCulture)
                         .ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            writer.WriteElementString("orderDate", orderDate);

            writer.WriteEndElement();
        }

        writer.WriteEndElement();
        writer.WriteEndDocument();
    }
}

AllocatedRange covers only the cells in use, so the exported records match the actual data. A fixed range such as sheet.Range["A1:C100"] also includes the empty rows below the data; if you use a fixed range, skip rows where every value is null or empty.

Two options control the output. KeepDataType = true with KeepDataFormat = false keeps Amount as a decimal and OrderDate as a DateTime. With KeepDataFormat = true, the export uses the displayed text instead, such as 2026/10/29. XmlWriter also escapes &, <, and > in cell values, so the output stays well-formed.

If the source columns are numbers stored as text, or dates stored as plain strings, convert them explicitly before writing. Under invariant culture, Convert.ToDecimal expects 1250.50 rather than 1,250.50.

This approach writes the selected data only. When you also need merged cells, column widths, and fonts, use the workbook export in the previous section.

The custom output written to orders-custom.xml:

Custom XML with orders and order elements generated by XmlWriter


Convert Excel Data to XML with DataTable.WriteXml()

When the target accepts a standard table-shaped XML document, DataTable.WriteXml() removes the manual element writing.

using System.Data;
using Spire.Xls;

using (Workbook workbook = new Workbook())
{
    workbook.LoadFromFile("SalesOrders.xlsx");
    Worksheet sheet = workbook.Worksheets[0];

    var options = new ExportTableOptions
    {
        ExportColumnNames = true,
        KeepDataType = true,
        KeepDataFormat = false
    };

    DataTable table = sheet.ExportDataTable(sheet.AllocatedRange, options);
    table.TableName = "Orders";

    table.WriteXml("orders.xml", XmlWriteMode.IgnoreSchema);
}

The output root is <DocumentElement>, with one <Orders> element per row:

<?xml version="1.0" standalone="yes"?>
<DocumentElement>
  <Orders>
    <OrderID>SO-1001</OrderID>
    <Customer>Acme Corp</Customer>
    <Region>North</Region>
    ...
    <Amount>3897</Amount>
    <OrderDate>2026-10-01T00:00:00+08:00</OrderDate>
    <Status>Shipped</Status>
  </Orders>
</DocumentElement>

The DataTable output, with one <Orders> element per row:

DataTable XML output with a DocumentElement root and typed OrderDate values

Date values are written with the local offset, so the same workbook produces a different string on a server in another time zone. Normalize the values first if the consumer expects UTC.

If the receiving system requires a different root, wrap the table in a DataSet. Rename the table first, or you get <Orders><Orders> instead of one element per row:

table.TableName = "Order";

var dataSet = new DataSet("Orders");
dataSet.Tables.Add(table);
dataSet.WriteXml("orders-dataset.xml", XmlWriteMode.IgnoreSchema);

The output now uses the root and record names you chose:

<?xml version="1.0" standalone="yes"?>
<Orders>
  <Order>
    <OrderID>SO-1001</OrderID>
    ...

XmlWriteMode.WriteSchema adds an XSD schema block to the document. Use it when the consumer reads the schema.

For more on the export side, see converting Excel data to a DataTable in C#.


XLS, XLSX, and Data Handling

XLS vs XLSX input

Both formats load with LoadFromFile(), and the output format is independent of the input extension. An .xlsx file exported with SaveAsXml() becomes one XML spreadsheet document; the package parts inside the original file are a separate format. Decide the output format first, then pick the method.

Dates and numbers

Excel stores dates as numbers and displays them through a format. When you export through a DataTable, choose between the typed value and the displayed text. For cross-system exchange, keep the typed value and format it at write time, as the earlier yyyy-MM-dd example does.

Formulas

ComputedFormulaValue = true writes the calculated result. Set it to false when the consumer needs the formula expression itself.

Headers and empty cells

ExportColumnNames = true turns the first row into column names. Keep titles, notes, and blank rows out of the selected range. Decide up front whether a missing value becomes an omitted element, an empty element, or an explicit null marker, and choose the form your consumer expects.

Multiple worksheets

A workbook export writes every worksheet. A range export writes one sheet. To produce custom XML from several sheets, loop over the collection and write each sheet into its own parent element. The snippet reuses the settings and options objects defined earlier.

using (XmlWriter writer = XmlWriter.Create("workbook-custom.xml", settings))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("workbook");

    foreach (Worksheet sheet in workbook.Worksheets)
    {
        DataTable table = sheet.ExportDataTable(sheet.AllocatedRange, options);

        writer.WriteStartElement("sheet");
        writer.WriteAttributeString("name", sheet.Name);

        foreach (DataRow row in table.Rows)
        {
            writer.WriteStartElement("row");
            foreach (DataColumn column in table.Columns)
            {
                writer.WriteStartElement("field");
                writer.WriteAttributeString("name", column.ColumnName);
                writer.WriteString(Convert.ToString(row[column], CultureInfo.InvariantCulture));
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
        }

        writer.WriteEndElement();
    }

    writer.WriteEndElement();
    writer.WriteEndDocument();
}

The column name goes into an attribute rather than an element name on purpose. XML element names cannot contain spaces or start with a digit, so headers such as Order ID or 2026 Total need a safe name; the attribute form accepts any header as written.

To include only populated sheets, check table.Rows.Count before writing the <sheet> element.

The multi-sheet output, with each sheet and column name kept:

Multi-sheet XML with workbook, sheet, row, and named field elements

Large files

For very large sheets, read rows in chunks, or write directly with XmlWriter while iterating cells.

If you need the reverse direction, see convert XML to Excel and PDF in C#. For CSV input instead of Excel, see convert CSV to XML in C#.


Frequently Asked Questions

How do I convert XLSX to XML in C#?

Load the file with Workbook.LoadFromFile() and call SaveAsXml() to produce an XML Spreadsheet 2003 document. If you need custom element names instead, export the range to a DataTable and write it with XmlWriter or DataTable.WriteXml().

Does SaveAsXml() produce Office Open XML?

SaveAsXml() produces XML Spreadsheet 2003. In the Spire.XLS 16.10.3 test, the output used the urn:schemas-microsoft-com:office:spreadsheet namespace and a Workbook root, which identifies XML Spreadsheet 2003. Office Open XML is the .xlsx package format and is handled as a separate format.

How can I export only one worksheet to XML?

Export the range from that worksheet with Worksheet.ExportDataTable(), then serialize it. A workbook-level SaveAsXml() call always covers the whole workbook.

Can I control the element names?

Yes, with XmlWriter. You define the root, the record element, field names, nesting, and value formatting. DataTable.WriteXml() is faster to write but fixes the structure to the table.

Can I export XLS files the same way?

Yes. .xls and .xlsx both load with LoadFromFile(), and the export steps are the same for an XLS to XML conversion as for an XLSX to XML conversion.


Summary

Converting Excel to XML in C# means choosing which XML the receiving system needs before choosing the API. With Spire.XLS for .NET, SaveAsXml() produces an XML Spreadsheet 2003 document for the whole workbook, XmlWriter produces whatever schema your integration requires, and DataTable.WriteXml() produces a standard table-shaped document with one element per row.

The differences between the three outputs are practical, not cosmetic. XML Spreadsheet 2003 keeps workbook structure and formatting, custom XML keeps only the fields you write, and the DataTable route keeps the table shape but fixes the root and record names. SpreadsheetML and the XML parts inside an XLSX package are different formats, so confirm which one the consumer expects.

Keep data types intact by setting KeepDataType = true and KeepDataFormat = false, select the range with AllocatedRange instead of a fixed block, and decide how missing values should appear before the first file reaches the consumer.

If you need to test Spire.XLS for .NET in a real business environment, you can apply for a temporary license.

Explore 2 ways to transpose rows and columns via C#

Transposing data in Excel (i.e., swapping rows and columns) is a common requirement in data processing, reporting, and ETL workflows. Within desktop Microsoft Excel, you can copy a range and use the Transpose paste option. For .NET‑based applications, you may need to perform this transpose task programmatically without opening Microsoft Excel.

This tutorial walks you through two practical ways to transpose rows and columns in C# using Spire.XLS for .NET , from the built-in copy with transpose option to the native TRANSPOSE array formula.


Prerequisites

  1. A .NET project (.NET Framework / .NET Core / .NET 5+)
  2. Install Spire.XLS for .NET via NuGet Package Manager
Install-Package Spire.XLS

Note: Spire.XLS works on Windows, macOS, and Linux environments for cross-platform Excel processing.


Method 1: Transpose Data via Static Copy

Starting with Spire.XLS 16.1.4, the library introduced native support for transposing rows and columns when copying a cell range. It creates a disconnected snapshot of transposed data, preserving cell formatting.

using Spire.Xls;
class Program
{
    static void Main()
    {
        // 1. Create a new workbook
        Workbook workbook = new Workbook();

        // 2. Load an existing Excel file
        workbook.LoadFromFile(@"F:\SalesData.xlsx");

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

        // 4. Define the source range (e.g., A1:D5)
        CellRange sourceRange = sheet.Range["A1:D5"];

        // 5. Define the destination cell (top-left corner)
        CellRange destCell = sheet.Range["F7"];

        // 6. Set transposition options
        CopyRangeOptions options = CopyRangeOptions.Transpose | CopyRangeOptions.All;

        // 7. Copy the range with transposition
        sourceRange.Copy(destCell, options);

        // 8. Save the result
        workbook.SaveToFile(@"Transposed.xlsx", ExcelVersion.Version2016);
        workbook.Dispose();
    }
}

How It Works

  • CopyRangeOptions.Transpose: Inverts rows and columns for the copied cell range.
  • CopyRangeOptions.All: Copies cell values, formulas, fill styles, borders and font settings. You can combine multiple flags with the bitwise OR (|) operator.
  • You only specify the top‑left destination cell, and Spire.XLS will automatically calculate the full output range dimensions.

Result Preview:

The source range A1:D5 is transposed to F7:J10. The original rows become columns and the original columns become rows.

Transpose rows and columns and preserve cell formatting in C#

Copying Without Styles

If you only need the raw data and want to avoid copying cell formatting, omit CopyRangeOptions.All:

CopyRangeOptions options = CopyRangeOptions.Transpose;

Copying to a Different Worksheet

You can also transpose data into another worksheet:

Worksheet sourceSheet = workbook.Worksheets[0];
Worksheet destSheet = workbook.Worksheets.Add("TransposedData");

CellRange sourceRange = sourceSheet.Range["A1:D5"];
CellRange destCell = destSheet.Range["A1"];

CopyRangeOptions options = CopyRangeOptions.Transpose | CopyRangeOptions.All;
sourceRange.Copy(destCell, options);

Method 2: Transpose via the Dynamic TRANSPOSE Array Formula

Spire.XLS 16.9.2 added support for the Excel TRANSPOSE function. This method is useful when you want the transposed output to remain dynamically linked to the source range—if the source data changes, the transposed data updates automatically (depending on Excel's calculation settings).

using Spire.Xls;
class Program
{
    static void Main()
    {
        // Load an existing Excel file
        Workbook workbook = new Workbook();
        workbook.LoadFromFile(@"F:\SalesData.xlsx");

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

        // Source range: A1:D5 (5 rows × 4 columns)
        // Transposed output: F7:J10 (4 rows × 5 columns)
        sheet.Range["F7:J10"].FormulaArray = "=TRANSPOSE(A1:D5)";

        // Save the result
        workbook.SaveToFile("TransposedFormula.xlsx", ExcelVersion.Version2016);
        workbook.Dispose();
    }
}

Important Notes

  • The output range must be sized correctly: if the source is m rows × n columns, the destination must be n rows × m columns. In the example above, A1:D5 is 5×4, so F7:J10 is 4×5.
  • The formula is entered as an array formula using FormulaArray, not the regular Formula property.
  • This approach preserves the dynamic link only if the recipient opens the file in Excel with automatic calculation enabled.
  • Source‑sheet cell formatting is not copied to formula‑driven output cells.

Result Preview:

Transpose data with the TRANSPOSE array formula in C#


Excel Transpose Data Method Comparison

Feature Method 1: Static Copy with Transpose Method 2: TRANSPOSE Array Formula
Data type Static copy (values, formats) Dynamic array formula
Auto-update No Yes (when source changes)
Preserves formatting Yes Formula only
Output cells Plain cell values Embedded formula
Best for One-time transposition, formatting preservation Editable templates, dynamic dashboards

Conclusion: Choosing the Right Method

Converting rows to columns or columns to rows in C# is a common requirement that Spire.XLS for .NET handles elegantly. The best method depends on whether you need a static snapshot or a dynamic, formula-driven result.

Pick Method 1 if:

  • You need a snapshot of transposed data
  • You want to retain cell styles, borders, fills, and formatting
  • End users only view the result and won’t edit the source
  • You don’t want formulas in the final Excel file

Pick Method 2 if:

  • You’re building editable Excel templates for users
  • The transposed block needs to refresh when source data changes
  • You prefer minimal code and don’t need to copy formatting

Always validate exported Excel outputs against real‑world test data before production deployment. These reusable patterns help streamline row‑and‑column transformation within your .NET applications.


Frequently Asked Questions

Q: Can I transpose a single row or column?

A: Yes. Set the source range to a single row, such as A1:J1, or a single column, such as A1:A10. The output becomes a column or row, respectively.

Q: Does CopyRangeOptions.Transpose work with merged cells?

A: Merged cells can behave unpredictably when transposed. The CopyRangeOptions.Transpose method may preserve them in some cases, but it is safer to unmerge cells before transposing or test the result. 

Q: After static transpose, can I still modify the transposed cells independently?

A: Yes. The static transpose output creates independent cell copies. These cells hold plain values and formatting and have no link to the original source cells. Any edits to the transposed region will not affect the source data, and vice versa.

Q: Can I transpose multiple ranges at once?

A: Not in a single built-in call. You can transpose each range separately and place the outputs in different destination areas, or combine the data into one range before transposing.

Flatten a PDF in C# with Spire.PDF — form fields, annotations and layers become fixed page content

Flattening a PDF converts interactive objects into fixed page content. A filled-in form field loses its input control and keeps its value as text, a reviewer's comment becomes part of the page appearance, and optional-content layers are removed by rebuilding each page from its currently visible content. This makes the document less dependent on the interactive features of individual PDF viewers, although the page content itself can still be edited in a PDF editor.

This guide flattens a PDF in C# with Spire.PDF for .NET: the whole form at once, selected fields only, every annotation on every page, and layers by rebuilding each page through SVG. It closes with a verification step, because a flattened file looks very much like the original — the difference is structural, not visual.

Quick Navigation

  1. Install Spire.PDF for .NET
  2. What Flattening a PDF Does
  3. Flatten the Entire PDF Form
  4. Flatten Selected PDF Form Fields
  5. Flatten PDF Annotations and Comments
  6. Flatten PDF Layers Through SVG
  7. Flatten a PDF Before Printing
  8. Verify the Flattened PDF
  9. Putting It Together
  10. FAQ
  11. Conclusion

Install Spire.PDF for .NET

Spire.PDF for .NET is available as a NuGet package. Install it using the .NET CLI:

dotnet add package Spire.PDF

These examples were built with Spire.PDF for .NET 12.9.18.

You can also download Spire.PDF for .NET and add it to your project manually.

Three namespaces matter for flattening:

Namespace What lives there
Spire.Pdf PdfDocument, PdfPageBase, FileFormat
Spire.Pdf.Widget, Spire.Pdf.Fields PdfFormWidget and PdfField — the form side
Spire.Pdf.Interactive.Annotations PdfAnnotation, PdfAnnotationCollection — the annotation side, including Flatten()

What Flattening a PDF Does

Flattening presses the appearance of an interactive object into the page content and removes the object. The goal is to preserve the visible appearance while removing the interactivity — which is why this guide counts the objects left in the saved file instead of comparing screenshots.

Each object type needs its own call:

Object Flattened with
Form fields (text boxes, check boxes, list boxes, combo boxes) PdfForm.IsFlatten for the whole form, PdfField.Flatten for one field
Annotations (comments, highlights, stamps, free text) PdfAnnotation.Flatten() on each annotation
Layers (optional content groups) PDF → SVG → PDF conversion, which rebuilds every page from what is visible

Flatten the Entire PDF Form

Set Form.IsFlatten to true and every field in the document is converted in one pass:

using Spire.Pdf;

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("FillableForm.pdf");

// Every field and its current value becomes page content.
pdf.Form.IsFlatten = true;

pdf.SaveToFile("FlattenedForm.pdf");
pdf.Close();

On the registration form used here — five fields, three of them filled — the field count drops from 5 to 0. The values stay on the page as selectable text.

The registration form before and after flattening — the page looks the same, the five interactive fields are gone

Flatten Selected PDF Form Fields

Locking only the fields that are already final is the more common requirement: a completed section becomes read-only while the rest of the form stays fillable. Fields are reached through the FieldsWidget collection of a PdfFormWidget, and Flatten is a boolean property on each one:

using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Widget;

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("FillableForm.pdf");

PdfFormWidget formWidget = pdf.Form as PdfFormWidget;

foreach (PdfField field in formWidget.FieldsWidget)
{
    // Flatten the fields that are final, leave the rest fillable.
    if (field.Name == "full_name" || field.Name == "email" || field.Name == "department")
    {
        field.Flatten = true;
    }
}

pdf.SaveToFile("PartiallyFlattenedForm.pdf");
pdf.Close();

On the sample form this flattens three fields and leaves start_date and manager editable — the count goes from 5 to 2. Filter on the field names your form defines — read them from FieldsWidget so the comparison matches exactly.

The partially flattened form — three fields are page text, start_date and manager are still fillable

Flattening a field vs. removing a field. Flattening keeps a field's visible appearance — including the value typed into it — and removes only the interactivity. Deleting a form field removes the object and its appearance together. If deletion is the actual goal, see Remove/Delete Form Fields from PDF in C# instead.

Flatten PDF Annotations and Comments

Annotations are the objects reviewers leave on top of a page: text comments, highlights, stamps and free text boxes. In Spire.PDF for .NET they are flattened through the interactive annotation model: create a PdfAnnotationCollection for each page and call Flatten() on each annotation.

using Spire.Pdf;
using Spire.Pdf.Interactive.Annotations;

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("ReviewedDocument.pdf");

foreach (PdfPageBase page in pdf.Pages)
{
    if (page.Annotations.Count == 0) continue;

    PdfAnnotationCollection annotations = PdfAnnotationCollection.Create(page);

    // Flatten() removes the annotation from the collection, so walk it backwards.
    for (int i = annotations.Count - 1; i >= 0; i--)
    {
        annotations[i].Flatten();
    }
}

pdf.SaveToFile("FlattenedAnnotations.pdf");
pdf.Close();

The reviewed contract page in this guide carries three annotations — a free text note, a rubber stamp and a yellow highlight over a clause. After the loop the annotation count goes from 3 to 0, and all three marks are still drawn on the page: the note keeps its box and colour, the stamp keeps its border, the highlight stays behind the text. Only the interactive objects are gone. The highlight survives because its quad points are read from the saved page rather than from a page still in memory.

The reviewed contract before and after flattening — the stamp, the note and the highlight are still on the page, the annotation objects are gone

Two details in that loop are worth noting. Walk the collection backwards: Flatten() removes each annotation as it is flattened, so a back-to-front loop processes every item exactly once. Flatten() is declared on Spire.Pdf.Interactive.Annotations.PdfAnnotation, the model the annotation collection is created from.

Flatten PDF Layers Through SVG

Optional-content layers are removed by rebuilding each page from its currently visible content: convert each page to SVG and build the PDF back from it. The round trip redraws every page, which drops the layer structure while keeping text as text and graphics as vectors — so the result still selects, searches and scales, unlike a page rendered to an image.

A document with layers converts one page at a time:

using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Spire.Pdf;

// Work in a fresh temp folder for each run.
string workDir = Path.Combine(Path.GetTempPath(),
    "flatten_svg_" + Guid.NewGuid().ToString("N").Substring(0, 8));
Directory.CreateDirectory(workDir);

try
{
    // Step 1 - save every page as its own SVG file. A multi-page document gives
    // page_1.svg, page_2.svg, ...; a single-page document gives page.svg.
    PdfDocument source = new PdfDocument();
    source.LoadFromFile("LayeredDocument.pdf");
    int pageCount = source.Pages.Count;
    source.SaveToFile(Path.Combine(workDir, "page.svg"), FileFormat.SVG);
    source.Close();

    // Sort the files by page number; a single-page document produces page.svg.
    string[] svgFiles = Directory.GetFiles(workDir, "*.svg")
        .OrderBy(f =>
        {
            Match m = Regex.Match(Path.GetFileNameWithoutExtension(f), @"\d+$");
            return m.Success ? int.Parse(m.Value) : 0;
        })
        .ToArray();

    // One SVG per page — the merge below uses that count.
    if (svgFiles.Length != pageCount)
    {
        throw new IOException(
            $"SVG conversion produced {svgFiles.Length} files for {pageCount} pages.");
    }

    // Step 2 - load each SVG back and save it as a one-page PDF.
    string[] pageFiles = new string[svgFiles.Length];
    for (int i = 0; i < svgFiles.Length; i++)
    {
        PdfDocument page = new PdfDocument();
        page.LoadFromSvg(svgFiles[i]);
        pageFiles[i] = Path.Combine(workDir, "page_" + (i + 1) + ".pdf");
        page.SaveToFile(pageFiles[i], FileFormat.PDF);
        page.Close();
    }

    // Step 3 - join the one-page PDFs into a single document, in page order.
    PdfDocument.MergeFiles(pageFiles, "FlattenedLayers.pdf");
}
finally
{
    Directory.Delete(workDir, true);
}

The file names depend on the page count. A two-page layered document saved to page.svg produces page_1.svg and page_2.svg, while a one-page document produces a single page.svg with no number. On the sample document the round trip keeps both pages in order at the original page size, keeps the text that was drawn on each layer, and the layer count goes from 4 to 0. The same workflow on a single-page document returns one page.

The layered document rebuilt through SVG — the same two pages and the same content, with no layer structure left

Text and vector graphics survive the round trip, so the rebuilt pages still select, search and scale like the original, and the content that was drawn on each layer stays on the page.

For the two conversion steps on their own, see Convert PDF to SVG in C#, VB.NET and Convert SVG to PDF in C#, VB.NET.

Flatten a PDF Before Printing

Flatten a PDF for printing when the file is going to a printer, a print shop or a viewer you do not control. Once the fields, annotations and layers are ordinary page content, what gets printed is decided by the file rather than by the reader's interactive features.

No separate code is needed. Use the form calls from the form sections when the document has fields, the annotation loop when it has comments, and the SVG workflow when layer visibility could change what lands on paper — then run the output through the checks below before you send it.

Verify the Flattened PDF

A flattened file looks like the original, so confirm the result by counting objects in the saved file rather than by looking at a render:

using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Widget;

PdfDocument result = new PdfDocument();
result.LoadFromFile("FlattenedForm.pdf");

int fields = 0;
PdfFormWidget form = result.Form as PdfFormWidget;
if (form != null)
{
    foreach (PdfField field in form.FieldsWidget) fields++;
}

int annotations = 0;
foreach (PdfPageBase page in result.Pages)
{
    annotations += page.Annotations.Count;
}

Console.WriteLine($"pages={result.Pages.Count} fields={fields} "
                + $"annotations={annotations} layers={result.Layers.Count}");
result.Close();

Count fields through PdfFormWidget.FieldsWidget. On the sample files this reports:

File Pages Fields Annotations Layers
FillableForm.pdf (input) 1 5 0 0
FlattenedForm.pdf 1 0 0 0
PartiallyFlattenedForm.pdf 1 2 0 0
ReviewedDocument.pdf (input) 1 0 3 0
FlattenedAnnotations.pdf 1 0 0 0
LayeredDocument.pdf (input) 2 0 0 4
FlattenedLayers.pdf 2 0 0 0

Then check the visual result: open the file in a reader and confirm nothing can be clicked or toggled, compare page count and page size with the original, and select or extract text to confirm it is still real text.

Putting It Together

The snippets above solve one concern each. Here they are as a single method that flattens the form fields and the annotations of any document in one pass:

using Spire.Pdf;
using Spire.Pdf.Interactive.Annotations;

/// <summary>
/// Flatten the form fields and annotations of a PDF in one pass.
/// </summary>
public static void FlattenDocument(string inputFile, string outputFile)
{
    PdfDocument pdf = new PdfDocument();
    pdf.LoadFromFile(inputFile);

    // 1. Form fields: one flag covers every field in the document.
    if (pdf.Form != null)
    {
        pdf.Form.IsFlatten = true;
    }

    // 2. Annotations: Flatten() removes each one, so walk backwards. Skip pages
    //    that carry no annotations.
    foreach (PdfPageBase page in pdf.Pages)
    {
        if (page.Annotations.Count == 0) continue;

        PdfAnnotationCollection annotations = PdfAnnotationCollection.Create(page);
        for (int i = annotations.Count - 1; i >= 0; i--)
        {
            annotations[i].Flatten();
        }
    }

    pdf.SaveToFile(outputFile);
    pdf.Close();
}

The guard keeps the loop on pages that carry annotations, so the same method also works for documents that only have form fields. With it, the method takes the five-field form to 0 fields and the reviewed contract from 3 annotations to 0. Layered documents go through the SVG workflow from the previous section instead.

FAQ

What is the difference between flattening and removing form fields?

Flattening keeps the field's visible appearance, including any entered value, and removes only the interactivity. Removing a form field deletes the field object and its appearance together.

Can I flatten only some form fields?

Yes. Cast pdf.Form to PdfFormWidget, walk FieldsWidget, and set Flatten = true on the fields you name. The rest stay fillable.

Does flattening keep the text selectable and searchable?

Yes. A flattened text field keeps its value in the page's text layer, and the SVG round trip keeps the text it redraws, so the values stay selectable, copyable and searchable.

Is flattening reversible?

Flattening writes the fields and annotations into the page, so keep the source PDF if you may need to edit them later.

Do I need to flatten before printing?

Not always, but it removes the dependency on the reader. Flattening can make the output more consistent across PDF viewers, because the visible content no longer depends on interactive fields, annotations or layer visibility settings.

Conclusion

Flattening a PDF in C# is one call per object type:

  • pdf.Form.IsFlatten = true flattens every field in the document; PdfField.Flatten flattens the ones you name.
  • PdfAnnotationCollection.Create(page) plus Flatten() on each item, walked backwards, flattens every comment, highlight and stamp on the page.
  • Layers are flattened by saving each page as SVG, loading it back and merging the pages with PdfDocument.MergeFiles.

The page keeps its appearance either way, so verify by counting the objects left in the saved file — not by comparing screenshots.

If you need to test Spire.PDF for .NET in a real business environment, you can apply for a temporary license.

Convert PDF to JSON in C# — extract text, tables, and form fields to structured JSON

Your application receives a PDF invoice. You need the invoice number, vendor name, and line items — not as text on a page, but as structured JSON your API can consume. That is the real problem behind PDF to JSON conversion.

Unlike CSV or XML, a PDF file has no inherent data structure — no fields, no rows, no schema. Extracting usable JSON requires different approaches depending on what the document actually contains: plain text with key-value patterns, tables with rows and columns, fillable form fields, or scanned images that need OCR.

This article covers all four scenarios with runnable C# code using Spire.PDF for .NET. We build a real invoice-to-JSON converter, handle common table extraction problems like merged cells and missing headers, and package everything into a reusable PdfToJsonConverter class you can drop into any .NET project.

Quick Navigation

  1. What "PDF to JSON" Actually Means
  2. Install Spire.PDF for .NET
  3. Convert PDF Text to JSON in C#
  4. Convert PDF Tables to JSON in C#
  5. Convert PDF Form Fields to JSON
  6. Invoice PDF to JSON: A Real-World Example
  7. Convert Multiple PDFs to JSON in Batch
  8. Build a PDF to JSON Converter in C#
  9. Convert OCR Output to JSON in C#
  10. Performance Considerations
  11. FAQ

1. What "PDF to JSON" Actually Means

There is no built-in "PDF to JSON" conversion in the way you might convert a CSV to JSON. A PDF has no JSON structure. What developers actually need is: extract content from a PDF, then shape that content into a JSON format that matches their use case.

Depending on the PDF type and business requirement, the target JSON falls into one of three categories.

Raw Text JSON

Pull all text from each page and wrap it in a JSON envelope. Works for search indexing, RAG pipelines, and document archival.

{
  "sourceFile": "Contract.pdf",
  "pages": [
    { "pageNumber": 1, "text": "SERVICE AGREEMENT\nBetween Contoso Ltd and..." }
  ]
}

Key-Value JSON

Many PDFs follow a Label: Value pattern — employee records, registration forms, simple invoices. The goal here is to parse those pairs into a flat JSON object:

{
  "name": "John Smith",
  "email": "[email protected]",
  "department": "Engineering",
  "employeeId": "EMP-2026-0142"
}

Structured Business JSON

Real business documents have nested data: an invoice has a header, line items, tax breakdowns, and payment terms. The JSON output needs to mirror that structure:

{
  "invoiceNumber": "INV-2026-0042",
  "vendor": "Contoso Ltd",
  "date": "2026-06-15",
  "lineItems": [
    { "description": "Widget A", "quantity": 150, "unitPrice": 24.50, "total": 3675.00 }
  ],
  "subtotal": 3675.00,
  "tax": 294.00,
  "total": 3969.00
}

This distinction matters. When you search for "convert PDF to JSON," you need to decide which output format your application requires. The rest of this article shows how to build each one using Spire.PDF in C#.


2. Install Spire.PDF for .NET

Install via NuGet Package Manager Console:

Install-Package Spire.PDF

Or add to your .csproj:

<PackageReference Include="Spire.PDF" Version="*" />

Include these namespaces in your project:

using Spire.Pdf;
using Spire.Pdf.Texts;
using Spire.Pdf.Utilities;
using Spire.Pdf.Fields;
using Spire.Pdf.Widget;
using System.Text.Json;
using System.Text.Json.Serialization;

Spire.PDF supports .NET Framework, .NET Core, and .NET 6/7/8/9+.


3. Convert PDF Text to JSON in C#

The most common starting point: extract text from a PDF and produce JSON output.

Extract Text from PDF

using Spire.Pdf;
using Spire.Pdf.Texts;
using System.Collections.Generic;

using (PdfDocument pdf = new PdfDocument())
{
    pdf.LoadFromFile("EmployeeRecord.pdf");

    var pages = new List<Dictionary<string, string>>();

    for (int i = 0; i < pdf.Pages.Count; i++)
    {
        PdfPageBase page = pdf.Pages[i];

        PdfTextExtractOptions options = new PdfTextExtractOptions();
        options.IsExtractAllText = true;

        PdfTextExtractor extractor = new PdfTextExtractor(page);
        string pageText = extractor.ExtractText(options);

        pages.Add(new Dictionary<string, string>
        {
            { "pageNumber", (i + 1).ToString() },
            { "text", pageText.Trim() }
        });
    }
}

Parse Key-Value Pairs into JSON

If your PDF follows a Label: Value pattern, parse the extracted text into structured fields:

using System.Text.Json;

var parsedFields = new Dictionary<string, string>();

foreach (var page in pages)
{
    string[] lines = page["text"].Split('\n');
    foreach (string line in lines)
    {
        int colonIndex = line.IndexOf(':');
        if (colonIndex > 0)
        {
            string key = line.Substring(0, colonIndex).Trim();
            string value = line.Substring(colonIndex + 1).Trim();
            parsedFields[key] = value;
        }
    }
}

var jsonOptions = new JsonSerializerOptions
{
    WriteIndented = true,
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};

string jsonOutput = JsonSerializer.Serialize(parsedFields, jsonOptions);
File.WriteAllText("EmployeeRecord.json", jsonOutput);

Key API Calls

  • PdfDocument.LoadFromFile() — opens the PDF file
  • PdfTextExtractor.ExtractText() — extracts text content from a page
  • PdfTextExtractOptions.IsExtractAllText — preserves whitespace and formatting

Output

The following example shows the structured JSON generated from the extracted employee record.

{
  "name": "John Smith",
  "email": "[email protected]",
  "department": "Engineering",
  "employeeId": "EMP-2026-0142",
  "startDate": "2024-03-15"
}

The following screenshot shows the actual JSON file generated after running the example.

Convert PDF Text to JSON in C#

This approach works well for forms, records, and documents with consistent key-value layouts. For unstructured text, skip the parsing step and serialize the raw pages directly.

If you need a deeper look at PDF text extraction, see our dedicated guide on extracting text from PDFs in C# using Spire.PDF for .NET.


4. Convert PDF Tables to JSON in C#

The previous section focused on extracting plain text from PDFs. While that works well for paragraphs and simple records, many business documents organize their most valuable information in tables, such as invoice line items, sales reports, and financial statements. To preserve rows, columns, and relationships between cells, table data must be extracted differently before it can be converted into structured JSON.

Why Table Extraction Is Different from Text Extraction

Text extraction returns a flat stream of characters in reading order. Although a table may appear perfectly organized on the page, the extracted text often loses its row-and-column structure, making it difficult to identify which values belong together.

To preserve the table layout, you need a dedicated table extraction engine. PdfTableExtractor analyzes the page layout, detects table boundaries, and returns PdfTable objects that you can iterate row by row and cell by cell. Instead of producing a flat string such as:

Widget A 150 $24.50 $3,675.00

it enables you to generate structured JSON like:

{
  "Product": "Widget A",
  "Quantity": "150",
  "Unit Price": "$24.50",
  "Total": "$3,675.00"
}

The following example demonstrates how to extract tables from a PDF and serialize them into JSON.

Extract Tables from PDF

using Spire.Pdf;
using Spire.Pdf.Utilities;
using System.Collections.Generic;

using (PdfDocument pdf = new PdfDocument())
{
    pdf.LoadFromFile("SalesReport.pdf");

    PdfTableExtractor tableExtractor = new PdfTableExtractor(pdf);
    var allTables = new List<List<List<string>>>();

    for (int pageIndex = 0; pageIndex < pdf.Pages.Count; pageIndex++)
    {
        PdfTable[] tables = tableExtractor.ExtractTable(pageIndex);

        if (tables != null && tables.Length > 0)
        {
            foreach (PdfTable table in tables)
            {
                int rowCount = table.GetRowCount();
                int colCount = table.GetColumnCount();
                var tableData = new List<List<string>>();

                for (int row = 0; row < rowCount; row++)
                {
                    var rowData = new List<string>();
                    for (int col = 0; col < colCount; col++)
                    {
                        rowData.Add(table.GetText(row, col).Trim());
                    }
                    tableData.Add(rowData);
                }

                allTables.Add(tableData);
            }
        }
    }
}

Serialize Table Data to JSON

var jsonTables = new List<object>();

foreach (var tableData in allTables)
{
    if (tableData.Count < 2) continue;

    var headers = tableData[0];
    var rows = new List<Dictionary<string, string>>();

    for (int i = 1; i < tableData.Count; i++)
    {
        var rowObj = new Dictionary<string, string>();
        for (int j = 0; j < headers.Count && j < tableData[i].Count; j++)
        {
            rowObj[headers[j]] = tableData[i][j];
        }
        rows.Add(rowObj);
    }

    jsonTables.Add(new
    {
        tableIndex = allTables.IndexOf(tableData) + 1,
        headers = headers,
        data = rows
    });
}

string tableJson = JsonSerializer.Serialize(new
{
    sourceFile = "SalesReport.pdf",
    tables = jsonTables
}, new JsonSerializerOptions { WriteIndented = true });

File.WriteAllText("SalesReport_Tables.json", tableJson);

Key API Calls

  • PdfTableExtractor(PdfDocument) — initializes the table extraction engine
  • PdfTableExtractor.ExtractTable(pageIndex) — detects and extracts tables from a page
  • PdfTable.GetRowCount() / GetColumnCount() — returns table dimensions
  • PdfTable.GetText(row, col) — reads cell content

Sample JSON Output

The resulting JSON preserves the original table structure by organizing each row into key-value pairs based on the detected column headers.

{
  "sourceFile": "SalesReport.pdf",
  "tables": [
    {
      "tableIndex": 1,
      "headers": ["Product", "Quantity", "Unit Price", "Total"],
      "data": [
        { "Product": "Widget A", "Quantity": "150", "Unit Price": "$24.50", "Total": "$3,675.00" },
        { "Product": "Widget B", "Quantity": "80", "Unit Price": "$39.90", "Total": "$3,192.00" }
      ]
    }
  ]
}

The following screenshot shows the actual JSON file generated after running the example.

Convert PDF Tables to JSON in C#

This approach works well for invoices, reports, and other PDFs with well-defined table structures. For documents containing merged cells, missing headers, or multi-page tables, additional post-processing may be required.

If you need a deeper look at PDF table extraction, see our dedicated guide on extracting tables from PDFs in C# using Spire.PDF for .NET.

Common Table Extraction Problems

Real-world PDF tables are messy. Here are the three problems you will hit most often, and how to handle them.

Problem 1: Missing Headers

Many invoices and reports have tables without explicit header rows. The data starts immediately:

Apple      10    $2.99    $29.90
Orange     5     $1.50    $7.50

When the first row is data rather than headers, assign column names manually based on your known schema:

// Define headers when the PDF table has no header row
string[] defaultHeaders = { "Product", "Quantity", "UnitPrice", "Total" };

var rows = new List<Dictionary<string, string>>();
for (int i = 0; i < tableData.Count; i++)  // Start from 0, not 1
{
    var rowObj = new Dictionary<string, string>();
    for (int j = 0; j < defaultHeaders.Length && j < tableData[i].Count; j++)
    {
        rowObj[defaultHeaders[j]] = tableData[i][j];
    }
    rows.Add(rowObj);
}

Problem 2: Merged Cells

Tables in financial reports often have merged cells for grouping:

Quarter    Revenue     Expenses
Q1         $120,000    $95,000
           $115,000    $88,000
Q2         $140,000    $102,000

The extractor returns empty strings for merged cells. Fill them forward from the last non-empty value:

// Fill merged cells with the previous row's value
for (int col = 0; col < headers.Count; col++)
{
    string lastValue = "";
    for (int row = 1; row < tableData.Count; row++)
    {
        if (col < tableData[row].Count && !string.IsNullOrWhiteSpace(tableData[row][col]))
        {
            lastValue = tableData[row][col];
        }
        else if (col < tableData[row].Count)
        {
            tableData[row][col] = lastValue;
        }
    }
}

Problem 3: Multi-Page Tables

Enterprise reports often have a single table spanning multiple pages, with the header row repeated on each page. Handle this by deduplicating headers during serialization:

var combinedRows = new List<Dictionary<string, string>>();
string[] expectedHeaders = null;

for (int pageIndex = 0; pageIndex < pdf.Pages.Count; pageIndex++)
{
    PdfTable[] tables = tableExtractor.ExtractTable(pageIndex);
    if (tables == null) continue;

    foreach (PdfTable table in tables)
    {
        for (int r = 0; r < table.GetRowCount(); r++)
        {
            var cells = new List<string>();
            for (int c = 0; c < table.GetColumnCount(); c++)
            {
                cells.Add(table.GetText(r, c).Trim());
            }

            // First row of first page becomes the headers
            if (expectedHeaders == null && r == 0)
            {
                expectedHeaders = cells.ToArray();
                continue;
            }

            // Skip repeated header rows on subsequent pages
            if (r == 0 && cells.SequenceEqual(expectedHeaders))
                continue;

            var rowDict = new Dictionary<string, string>();
            for (int c = 0; c < expectedHeaders.Length && c < cells.Count; c++)
            {
                rowDict[expectedHeaders[c]] = cells[c];
            }
            combinedRows.Add(rowDict);
        }
    }
}

5. Convert PDF Form Fields to JSON

Unlike plain text or tables, fillable PDF forms already store data as named fields. Applications, surveys, and registration forms contain field names and values that can be mapped directly to JSON key-value pairs, making form data one of the easiest types of PDF content to serialize.

Read and Export Form Fields

using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Widget;
using System.Collections.Generic;

using (PdfDocument pdf = new PdfDocument())
{
    pdf.LoadFromFile("RegistrationForm.pdf");

    PdfFormWidget formWidget = pdf.Form as PdfFormWidget;
    var formData = new Dictionary<string, object>();

    if (formWidget != null)
    {
        for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++)
        {
            PdfField field = formWidget.FieldsWidget.List[i] as PdfField;

            if (field is PdfTextBoxFieldWidget textBox)
                formData[textBox.Name] = textBox.Text;
            else if (field is PdfCheckBoxWidgetFieldWidget checkBox)
                formData[checkBox.Name] = checkBox.Checked;
            else if (field is PdfRadioButtonListFieldWidget radioButton)
                formData[radioButton.Name] = radioButton.Value;
            else if (field is PdfComboBoxWidgetFieldWidget comboBox)
                formData[comboBox.Name] = comboBox.SelectedValue;
            else if (field is PdfListBoxWidgetFieldWidget listBox)
            {
                var selectedItems = new List<string>();
                foreach (PdfListWidgetItem item in listBox.Values)
                    selectedItems.Add(item.Value);
                formData[listBox.Name] = selectedItems;
            }
        }
    }

    var formOutput = new
    {
        sourceFile = "RegistrationForm.pdf",
        fieldCount = formData.Count,
        fields = formData
    };

    string json = JsonSerializer.Serialize(formOutput, new JsonSerializerOptions
    {
        WriteIndented = true
    });

    File.WriteAllText("RegistrationForm_Data.json", json);
}

Key API Calls

  • PdfFormWidget — provides access to the document's interactive form
  • PdfTextBoxFieldWidget.Text — reads text input values
  • PdfCheckBoxWidgetFieldWidget.Checked — reads checkbox state
  • PdfRadioButtonListFieldWidget.Value — reads selected radio button
  • PdfComboBoxWidgetFieldWidget.SelectedValue — reads combo box selection

Output

The following example shows how the extracted form fields are represented as structured JSON.

{
  "sourceFile": "RegistrationForm.pdf",
  "fieldCount": 6,
  "fields": {
    "FullName": "John Smith",
    "Email": "[email protected]",
    "Department": "Sales",
    "AgreeTerms": true,
    "SubscriptionPlan": "Enterprise",
    "Skills": ["C#", "SQL", "Azure"]
  }
}

The following screenshot shows the actual JSON file generated after exporting the form data.

Convert PDF Form Fields to JSON in C#

This approach works well for interactive PDF forms that contain structured fields such as text boxes, check boxes, radio buttons, and drop-down lists. Because each field already has a unique name, the extracted data can be serialized directly into JSON without additional parsing.

If you need a deeper look at importing and exporting PDF form field data in C#, see our dedicated guide on working with PDF form fields using Spire.PDF for .NET.


6. Invoice PDF to JSON: A Real-World Example

Invoice processing is one of the most common business use cases for PDF to JSON conversion. Instead of presenting a full parser implementation, this section demonstrates how the extraction techniques from Sections 3 and 4 come together to solve a real problem.

Target JSON Structure

Before writing any extraction code, define your target schema. For a typical invoice, the JSON output might look like this:

{
  "invoiceNumber": "INV-2026-0042",
  "date": "2026-06-15",
  "vendor": "Contoso Ltd",
  "paymentTerms": "Net 30",
  "lineItems": [
    { "description": "Widget A", "quantity": 150, "unitPrice": 24.50, "total": 3675.00 },
    { "description": "Widget B", "quantity": 80, "unitPrice": 39.90, "total": 3192.00 }
  ],
  "subtotal": 8367.00,
  "tax": 669.36,
  "total": 9036.36
}

Extraction Pattern

Use text extraction (Section 3) to parse header fields via regex, and table extraction (Section 4) to pull line items:

// Parse header fields from extracted text using regex
invoice["invoiceNumber"] = Regex.Match(fullText, @"Invoice Number:\s*(\S+)").Groups[1].Value;
invoice["date"] = Regex.Match(fullText, @"Date:\s*(\S+)").Groups[1].Value;
invoice["vendor"] = Regex.Match(fullText, @"Vendor:\s*(.+)").Groups[1].Value;

// Extract line items from table data (Section 4 pattern)
for (int r = 1; r < table.GetRowCount(); r++)
{
    lineItems.Add(new
    {
        description = table.GetText(r, 0).Trim(),
        quantity = int.Parse(table.GetText(r, 1).Trim()),
        unitPrice = ParseCurrency(table.GetText(r, 2)),
        total = ParseCurrency(table.GetText(r, 3))
    });
}

The implementation combines the text extraction introduced in Section 3 with the table extraction introduced in Section 4. Regex is used only for simple field matching — the core PDF processing relies entirely on Spire.PDF APIs.

Handling Different Invoice Layouts

In production, you rarely deal with a single invoice format:

  • Fixed template + regex — works when you control the source or process invoices from a known vendor
  • Template matching — maintain a set of regex patterns, one per vendor
  • AI-assisted extraction — for unknown or highly variable layouts, combine OCR output with an LLM

Regex-based parsing is fast and reliable for known formats. For a production-ready implementation, extend the PdfToJsonConverter class from Section 8 to build a dedicated invoice parser that reuses the same extraction patterns.


7. Convert Multiple PDFs to JSON in Batch

Production workflows process hundreds or thousands of PDFs at once. This batch processor handles errors gracefully and logs results:

using Spire.Pdf;
using Spire.Pdf.Texts;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;

string inputDir = @"C:\PDFs\Invoices";
string outputDir = @"C:\Output\JSON";
Directory.CreateDirectory(outputDir);

string[] pdfFiles = Directory.GetFiles(inputDir, "*.pdf");
var results = new List<object>();

foreach (string pdfPath in pdfFiles)
{
    string fileName = Path.GetFileNameWithoutExtension(pdfPath);
    string outputPath = Path.Combine(outputDir, $"{fileName}.json");

    try
    {
        using (PdfDocument pdf = new PdfDocument())
        {
            pdf.LoadFromFile(pdfPath);
            var pageTexts = new List<string>();

            for (int i = 0; i < pdf.Pages.Count; i++)
            {
                var extractor = new PdfTextExtractor(pdf.Pages[i]);
                var options = new PdfTextExtractOptions { IsExtractAllText = true };
                pageTexts.Add(extractor.ExtractText(options).Trim());
            }

            var doc = new
            {
                sourceFile = Path.GetFileName(pdfPath),
                pageCount = pdf.Pages.Count,
                processedAt = DateTime.UtcNow,
                content = pageTexts
            };

            File.WriteAllText(outputPath, JsonSerializer.Serialize(doc,
                new JsonSerializerOptions { WriteIndented = true }));

            results.Add(new { file = fileName, status = "success" });
        }
    }
    catch (Exception ex)
    {
        results.Add(new { file = fileName, status = "error", error = ex.Message });
    }
}

File.WriteAllText(Path.Combine(outputDir, "_log.json"),
    JsonSerializer.Serialize(results, new JsonSerializerOptions { WriteIndented = true }));

Swap the text-only extraction with the invoice JSON extraction pattern from Section 6 if your batch consists of invoices, or with the PdfToJsonConverter class from Section 8 for general-purpose conversion.


8. Build a PDF to JSON Converter in C#

For production applications, encapsulate all extraction logic into a single class. The PdfToJsonConverter below combines text, table, and form field extraction into one reusable PDF to JSON converter:

using Spire.Pdf;
using Spire.Pdf.Texts;
using Spire.Pdf.Utilities;
using Spire.Pdf.Fields;
using Spire.Pdf.Widget;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;

public class PdfToJsonConverter
{
    private readonly JsonSerializerOptions _jsonOptions = new()
    {
        WriteIndented = true,
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
    };

    public string ConvertToJson(string pdfPath)
    {
        using (PdfDocument pdf = new PdfDocument())
        {
            pdf.LoadFromFile(pdfPath);

            var result = new
            {
                sourceFile = Path.GetFileName(pdfPath),
                processedAt = DateTime.UtcNow,
                text = ExtractText(pdf),
                tables = ExtractTables(pdf),
                formFields = ExtractFormFields(pdf)
            };

            return JsonSerializer.Serialize(result, _jsonOptions);
        }
    }

    public void ConvertAndSave(string pdfPath, string outputPath)
    {
        File.WriteAllText(outputPath, ConvertToJson(pdfPath));
    }

    // Reuses the text extraction technique from Section 3 (PdfTextExtractor + PdfTextExtractOptions)
    private List<PageText> ExtractText(PdfDocument pdf) { return new List<PageText>(); }

    // Reuses the table extraction technique from Section 4 (PdfTableExtractor + ExtractTable)
    private List<TableData> ExtractTables(PdfDocument pdf) { return new List<TableData>(); }

    // Reuses the form field extraction technique from Section 5 (PdfFormWidget + field type checking)
    private Dictionary<string, object> ExtractFormFields(PdfDocument pdf) { return new Dictionary<string, object>(); }
}

public class PageText
{
    public int PageNumber { get; set; }
    public string Text { get; set; }
}

public class TableData
{
    public int PageNumber { get; set; }
    public int RowCount { get; set; }
    public List<List<string>> Rows { get; set; }
}

Usage

var converter = new PdfToJsonConverter();

// Single file
converter.ConvertAndSave("InvoiceReport.pdf", "InvoiceReport.json");

// Use inside an ASP.NET controller
[HttpPost("api/pdf-to-json")]
public IActionResult ConvertPdf(IFormFile file)
{
    var tempPath = Path.GetTempFileName();
    file.CopyTo(new FileStream(tempPath, FileMode.Create));
    var converter = new PdfToJsonConverter();
    string json = converter.ConvertToJson(tempPath);
    return Content(json, "application/json");
}

The helper methods (ExtractText, ExtractTables, ExtractFormFields) reuse the extraction techniques introduced in Sections 3–5. Refer to those sections for the full implementations.

Best Practices for Production Pipelines

When building PDF to JSON conversion into a production system:

  • Define your JSON schema first. Map each PDF element to a target field before writing extraction code.
  • Validate extracted data. Currency strings, dates, and IDs should be parsed and verified before serialization.
  • Handle missing values. Use JsonIgnoreCondition.WhenWritingNull to omit null fields from output.
  • Include metadata. Always record source file name, page numbers, and extraction timestamp for auditing.
  • Clean text artifacts. Trim whitespace, normalize line breaks, and handle encoding issues in extracted strings.

9. Convert OCR Output to JSON in C#

Scanned PDFs contain images rather than selectable text, so they must be processed with an OCR engine before they can be converted to JSON. Spire.PDF handles PDF rendering and page processing, while text recognition should be performed by an OCR solution such as Tesseract or Azure AI Vision.

For a complete walkthrough, see How to Extract Text from Scanned PDFs in C#.

Once OCR returns the recognized text, you can parse it using the same techniques shown earlier in this article.

Parse OCR Text into JSON

string recognizedText = ocrEngine.Recognize(imagePath);

// Parse recognized text using the same helper methods demonstrated in previous examples.
var parsedData = ParseRecognizedText(recognizedText);

string json = JsonSerializer.Serialize(parsedData, new JsonSerializerOptions
{
    WriteIndented = true
});

Best Practices

  • Scan documents at 300 DPI or higher for better OCR accuracy.
  • Validate important fields such as invoice numbers, dates, and currency values before serialization.
  • Reuse the parsing patterns introduced earlier in this article to build consistent JSON structures.

10. Performance Considerations

PDF to JSON conversion works fine for a single 5-page document. In production, you are processing hundreds of files with hundreds of pages each. These are the issues you will actually hit.

Large PDFs (100+ Pages)

Avoid loading all page text into a List<string> before serialization. Process and write each page incrementally:

using (var stream = File.Create("output.json"))
using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))
{
    writer.WriteStartObject();
    writer.WriteString("sourceFile", Path.GetFileName(pdfPath));
    writer.WriteStartArray("pages");

    for (int i = 0; i < pdf.Pages.Count; i++)
    {
        var extractor = new PdfTextExtractor(pdf.Pages[i]);
        var options = new PdfTextExtractOptions { IsExtractAllText = true };
        string text = extractor.ExtractText(options).Trim();

        writer.WriteStartObject();
        writer.WriteNumber("pageNumber", i + 1);
        writer.WriteString("text", text);
        writer.WriteEndObject();
    }

    writer.WriteEndArray();
    writer.WriteEndObject();
}

Utf8JsonWriter writes directly to the stream instead of building a string in memory. For a 500-page document, this can cut peak memory usage by 60-70% compared to JsonSerializer.Serialize().

Memory Usage

PdfDocument holds parsed page trees, fonts, and image references in memory. Two rules:

  1. Always wrap PdfDocument in using — it releases unmanaged resources on dispose
  2. Process one document at a time — do not keep multiple PdfDocument instances open simultaneously unless you have the RAM for it

For batch jobs processing 1000+ files, the using pattern inside the loop ensures each document is fully released before the next one loads.

Parallel Processing

Batch conversion is CPU-bound and parallelizes well:

var pdfFiles = Directory.GetFiles(inputDir, "*.pdf");

Parallel.ForEach(pdfFiles,
    new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
    pdfPath =>
{
    string outputPath = Path.Combine(outputDir,
        Path.GetFileNameWithoutExtension(pdfPath) + ".json");
    var converter = new PdfToJsonConverter();
    converter.ConvertAndSave(pdfPath, outputPath);
});

Each thread creates its own PdfToJsonConverter and PdfDocument instance. PdfDocument is not thread-safe — never share a single instance across threads.

When to Use Streaming JSON

Use Utf8JsonWriter over JsonSerializer.Serialize() when:

  • Output JSON exceeds 50 MB
  • You are processing PDFs with 200+ pages
  • Running in a memory-constrained environment (container with 512 MB limit)

For smaller documents, JsonSerializer is simpler and the memory difference is negligible.


11. FAQ

Can I convert PDF to JSON in C# for free?

Spire.PDF for .NET offers a free evaluation version with a page limit. For production use, you can apply for a 30-day free license or purchase a commercial license. The System.Text.Json serializer is built into .NET and free.

Can scanned PDFs be converted to JSON?

Yes, but you need an external OCR engine. Spire.PDF renders PDF pages as images via SaveAsImage(), which you then pass to Tesseract, Azure Computer Vision, or Amazon Textract for text recognition. The recognized text is then parsed and serialized to JSON. See Section 9 for the integration pattern.

Can I convert PDF tables to JSON automatically?

Yes. PdfTableExtractor automatically detects table structures on each page without manual configuration. It handles both properly structured tables (created in Word or Excel) and visual tables (text aligned to look like rows and columns). For multi-page tables or tables without headers, see the handling patterns in Section 4.

Can I batch convert multiple PDFs to JSON?

Yes. Iterate through a directory using Directory.GetFiles(), process each PDF with Spire.PDF extraction APIs, and save individual JSON files. Include error handling so one failed file does not stop the batch. See Section 7 for a complete example.

How can I convert large PDF files to JSON in C#?

Process the PDF page-by-page rather than loading all content into memory at once. For very large files (100+ pages), use Utf8JsonWriter to write JSON incrementally to a stream instead of building the entire output in memory. See Section 10 for the streaming JSON pattern and parallel processing approach.

Can I convert PDF to JSON using an API?

Yes. You can wrap the PdfToJsonConverter class from this article in an ASP.NET Web API endpoint. Accept a PDF upload, run the extraction, and return the JSON response. Spire.PDF works in any .NET hosting environment — ASP.NET Core, Azure Functions, AWS Lambda, or a self-hosted console app. See the ASP.NET controller example in Section 8.


Conclusion

PDF to JSON is not a single operation. Depending on your document, you are solving one of three different problems: wrapping raw text in a JSON envelope, parsing key-value patterns into flat objects, or building structured business JSON from text and table extraction.

This article covered all three, plus the complications that break naive implementations: tables without headers, merged cells, multi-page tables, fillable form fields, varying invoice layouts, batch processing, memory management for large documents, and OCR integration boundaries.

The PdfToJsonConverter class is a starting point you can adapt to your document types. The invoice extraction pattern shown in Section 6 demonstrates how to combine these techniques for real business documents. Both use Spire.PDF for .NET, which handles all PDF reading locally without external dependencies.

To get started:

Format Excel Programmatically in C#

Formatting plays an important role in making Excel spreadsheets easier to read, analyze, and present. Whether you are generating reports, invoices, financial statements, or dashboards, raw data often needs proper styling before it can be shared with end users.

In C#, Excel formatting tasks may include changing fonts, applying colors, aligning content, formatting numbers and dates, adding borders, creating tables, and configuring page layouts. Performing these tasks manually can be time-consuming, especially when dealing with large volumes of spreadsheets.

Spire.XLS for .NET provides a comprehensive set of APIs for creating, editing, formatting, and converting Excel documents without requiring Microsoft Excel to be installed. In this article, you will learn how to apply various types of formatting to Excel files in C# using Spire.XLS for .NET.

Table of Contents:

Prepare Your C# Project for Excel Formatting

Spire.XLS for .NET is a powerful Excel library that enables developers to work with XLS, XLSX, XLSM, CSV, and other spreadsheet formats programmatically. Besides formatting operations, it also supports formula calculation, chart creation, pivot tables, worksheet management, printing, and file conversion.

To install Spire.XLS for .NET, run the following NuGet command:

Install-Package Spire.XLS

Before applying formatting, load an existing Excel workbook (or create a new one) and access the worksheet you want to modify. Once all formatting operations are complete, save the result to a new Excel file using the SaveToFile() method.

using Spire.Xls;
using System.Drawing;

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

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

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

// Apply formatting
...

// Save the result
workbook.SaveToFile("output.xlsx", ExcelVersion.Version2016);

Note: The following examples assume that the workbook has already been loaded and the worksheet object has been obtained.

Part 1. Format Cell Appearance

Cell appearance settings control how data looks inside a worksheet. Proper formatting can significantly improve readability and help users quickly identify important information.

Format Cell Fonts

Font formatting allows you to customize the visual style of cell content. Common options include font family, font size, bold, italic, underline, and font color. These settings are frequently used for report titles, section headers, and highlighted values.

CellStyle style = workbook.Styles.Add("FontStyle");

style.Font.FontName = "Calibri";
style.Font.Size = 14;
style.Font.IsBold = true;
style.Font.IsItalic = true;
style.Font.Underline = FontUnderlineType.Single;
style.Font.Color = Color.Blue;

sheet.Range["A1"].Text = "Formatted Text";
sheet.Range["A1"].Style = style;

Set Cell Background Colors

Background colors help distinguish different sections of a worksheet and draw attention to key cells. For example, you may use a colored header row or highlight summary data with a contrasting fill color.

sheet.Range["A2"].Text = "Background Color";
sheet.Range["A2"].Style.Color = Color.LightSkyBlue;

Align Cell Content

Excel provides horizontal alignment, vertical alignment, indentation, and text rotation options. Proper alignment improves the overall layout of a worksheet and makes tabular data easier to scan.

sheet.Range["B2"].Text = "Centered Text";
CellStyle style = sheet.Range["B2"].Style;

style.HorizontalAlignment = HorizontalAlignType.Center;
style.VerticalAlignment = VerticalAlignType.Center;
style.Rotation = 45;

sheet.SetRowHeight(2, 40);
sheet.SetColumnWidth(2, 20);

Add Cell Borders

Borders are useful for separating rows and columns and defining table structures. Depending on the scenario, you can apply borders to individual cells or entire ranges and customize their styles and colors.

CellRange range = sheet.Range["A4:D6"];
range.Text = "Border";

range.Style.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin;
range.Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
range.Style.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
range.Style.Borders[BordersLineType.EdgeRight].LineStyle = LineStyleType.Thin;
range.Style.Borders[BordersLineType.EdgeTop].Color = Color.Black;

Wrap Text

When cell content exceeds the available column width, wrapping text allows multiple lines to be displayed within the same cell, preventing important information from being truncated.

sheet.Range["A8"].Text = "This is a very long sentence that will automatically wrap within the cell.";

sheet.Range["A8"].Style.WrapText = true;

sheet.SetColumnWidth(1, 20);
sheet.SetRowHeight(8, 60);

Part 2. Format Cell Values

Value formatting changes how data is displayed without modifying the underlying values. This is particularly important for business and financial spreadsheets.

Format Numbers

Numeric formats can control decimal places, thousands separators, scientific notation, and other display rules. Choosing the right format improves accuracy and readability.

sheet.Range["A10"].NumberValue = 1234567.891;
sheet.Range["A10"].NumberFormat = "#,##0.00";

Format Currency

Currency formatting automatically displays monetary symbols and decimal precision according to your requirements. This is commonly used in invoices, budgets, and financial reports.

sheet.Range["A11"].NumberValue = 5999.95;
sheet.Range["A11"].NumberFormat = "$#,##0.00";

Format Dates

Date formatting allows the same date value to be displayed in different styles, such as short dates, long dates, or custom patterns. Consistent date formats make reports easier to interpret.

sheet.Range["A12"].DateTimeValue = DateTime.Now;
sheet.Range["A12"].NumberFormat = "yyyy-MM-dd";

Part 3. Format Ranges and Layout

Instead of formatting cells one by one, you can apply styles to larger worksheet areas to improve efficiency and maintain consistency.

Format Ranges

A range may contain multiple rows and columns. Applying formatting to a range ensures that all cells share the same appearance and reduces repetitive code.

CellRange range = sheet.Range["A14:D18"];

range.Style.Color = Color.LightYellow;
range.Style.Font.IsBold = true;
range.Style.HorizontalAlignment = HorizontalAlignType.Center;

Merge Cells

Merged cells are often used for report titles and section headers. After merging, the content can be centered and styled to create a more professional appearance.

sheet.Range["A20:D20"].Merge();

sheet.Range["A20"].Text = "Monthly Sales Report";
sheet.Range["A20"].Style.Font.Size = 18;
sheet.Range["A20"].Style.Font.IsBold = true;
sheet.Range["A20"].Style.HorizontalAlignment = HorizontalAlignType.Center;

Format Rows and Columns

Formatting entire rows or columns is useful when all cells in a specific area should follow the same style, such as a header row or a currency column.

sheet.Rows[21].Style.Font.IsBold = true;
sheet.Rows[21].Style.Color = Color.LightGray;

sheet.Columns[1].Style.NumberFormat = "$#,##0.00";

AutoFit Rows and Columns

AutoFit automatically adjusts row heights and column widths based on cell content. This helps prevent clipped text and improves the presentation of generated spreadsheets.

sheet.AllocatedRange.AutoFitColumns();
sheet.AllocatedRange.AutoFitRows();

Part 4. Apply Advanced Formatting

Conditional formatting enables Excel to apply styles automatically based on cell values. Instead of manually highlighting data, rules can be configured to identify trends, exceptions, or important values.

For example, you can highlight numbers above a threshold, display data bars, apply color scales, or use icon sets to visualize performance indicators. These features make large datasets easier to analyze and understand.

sheet.Range["A25"].NumberValue = 1200;
sheet.Range["A26"].NumberValue = 800;
sheet.Range["A27"].NumberValue = 1500;

XlsConditionalFormats formats = sheet.ConditionalFormats.Add();
formats.AddRange(sheet.Range["A25:A27"]);
IConditionalFormat format = formats.AddCondition();
format.FormatType = ConditionalFormatType.CellValue;
format.FirstFormula = "1000";
format.Operator = ComparisonOperatorType.Greater;
format.BackColor = Color.LightGreen;

Part 5. Format Excel Tables and Worksheets

Formatting can also be applied at the worksheet level to improve the overall structure and appearance of a workbook.

Format Excel Tables

Excel tables provide built-in styling options such as header formatting, alternating row colors, and predefined themes. Converting a data range into a table can instantly enhance readability and organization.

sheet.Range["A30"].Text = "Product";
sheet.Range["B30"].Text = "Sales";
sheet.Range["A31"].Text = "Laptop";
sheet.Range["B31"].NumberValue = 5000;
sheet.Range["A32"].Text = "Monitor";
sheet.Range["B32"].NumberValue = 2000;

IListObject table = sheet.ListObjects.Create("SalesTable", sheet.Range["A30:B32"]);
table.BuiltInTableStyle = TableBuiltInStyles.TableStyleMedium2;

Configure Page Layout

Page layout settings determine how worksheets appear when printed or exported. Common options include page orientation, margins, print areas, scaling, and repeating header rows.

Proper page setup ensures that reports look professional both on screen and on paper.

sheet.PageSetup.Orientation = PageOrientationType.Landscape;
sheet.PageSetup.LeftMargin = 0.5;
sheet.PageSetup.RightMargin = 0.5;
sheet.PageSetup.TopMargin = 0.75;
sheet.PageSetup.BottomMargin = 0.75;
sheet.PageSetup.FitToPagesWide = 1;
sheet.PageSetup.FitToPagesTall = 1;

Part 6. Create a Professional Report Example

In real-world scenarios, multiple formatting techniques are often used together. A typical report may include a merged title, custom fonts, colored headers, borders, number formats, conditional formatting, and optimized page settings.

By combining these features, you can generate polished Excel documents that are ready for distribution without requiring manual editing.

using Spire.Xls;
using Spire.Xls.Core.Spreadsheet.Collections;
using Spire.Xls.Core;
using System.Drawing;

class Program
{
    static void Main()
    {
        // Create a new workbook
        Workbook workbook = new Workbook();
        Worksheet sheet = workbook.Worksheets[0];

        sheet.Name = "Sales Summary Report";

        // Title Row
        CellRange title = sheet.Range["A1:E1"];
        title.Merge();
        title.Text = "Sales Summary Report";

        title.Style.Font.FontName = "Arial";
        title.Style.Font.Size = 16;
        title.Style.Font.Color = Color.White;
        title.Style.Color = Color.DarkBlue;

        title.Style.HorizontalAlignment = HorizontalAlignType.Center;
        title.Style.VerticalAlignment = VerticalAlignType.Center;

        sheet.Rows[0].RowHeight = 30;

        // Headers
        string[] headers = { "Order ID", "Product", "Region", "Order Date", "Sales Amount" };

        for (int i = 0; i < headers.Length; i++)
        {
            CellRange cell = sheet.Range[2, i + 1];

            cell.Text = headers[i];
            cell.Style.Font.IsBold = true;
            cell.Style.Color = Color.LightGray;

            cell.Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Medium;
            cell.Style.Borders[BordersLineType.EdgeBottom].Color = Color.DarkBlue;
        }

        // Data
        object[][] data =
        {
            new object[] { 1001, "Laptop", "North", "2024-01-15", 15000 },
            new object[] { 1002, "Monitor", "West", "2024-02-10", 12000 },
            new object[] { 1003, "Keyboard", "East", "2024-03-05", 13500 },
            new object[] { 1004, "Mouse", "South", "2024-04-12", 16000 }
        };

        for (int r = 0; r < data.Length; r++)
        {
            for (int c = 0; c < data[r].Length; c++)
            {
                CellRange cell = sheet.Range[r + 3, c + 1];
                var value = data[r][c];

                if (c == 3) // Order Date
                {
                    cell.DateTimeValue = DateTime.Parse(value.ToString());
                    cell.NumberFormat = "yyyy-MM-dd";
                }
                else if (c == 4) // Sales Amount
                {
                    cell.NumberValue = Convert.ToDouble(value);
                    cell.NumberFormat = "$#,##0.00";
                }
                else
                {
                    cell.Text = value.ToString();
                }

                // Alternate row colors
                cell.Style.Color = (r % 2 == 0)
                    ? Color.LightYellow
                    : Color.LightCyan;
            }
        }

        // Borders
        CellRange range = sheet.Range["A2:E6"];

        range.BorderAround(LineStyleType.Medium, Color.Black);
        range.BorderInside(LineStyleType.Thin, Color.Gray);

        // Auto Fit Columns
        for (int i = 1; i <= 5; i++)
        {
            sheet.AutoFitColumn(i);
        }

        // Conditional Formatting
        XlsConditionalFormats formats = sheet.ConditionalFormats.Add();
        formats.AddRange(sheet.Range["E3:E6"]);

        IConditionalFormat condition = formats.AddCondition();
        condition.FormatType = ConditionalFormatType.CellValue;
        condition.Operator = ComparisonOperatorType.Greater;
        condition.FirstFormula = "14000";

        condition.FontColor = Color.Red;
        condition.IsBold = true;

        // Align + Layout Formatting
        CellRange all = sheet.AllocatedRange;

        for (int r = 1; r < all.RowCount; r++)
        {
            all.Rows[r].HorizontalAlignment = HorizontalAlignType.Center;
           // all.Rows[r].VerticalAlignment = VerticalAlignType.Center;
            all.Rows[r].RowHeight = 20;
        }

        for (int c = 0; c < all.ColumnCount; c++)
        {
            all.Columns[c].ColumnWidth = (c == 1) ? 19 : 14;
        }

        // Save
        workbook.SaveToFile("SalesSummaryReport.xlsx", ExcelVersion.Version2016);
        workbook.Dispose();
    }
}

Output:

Create Excel and Apply Formatting

Conclusion

Formatting is an essential step in creating professional Excel documents. With Spire.XLS for .NET, you can efficiently customize cell appearance, control number and date formats, manage worksheet layouts, apply conditional formatting, and build visually appealing reports entirely in C#.

By using the techniques covered in this guide, you can automate Excel formatting tasks and generate polished spreadsheets suitable for business, reporting, and data analysis scenarios.

FAQs

Can I format Excel files without Microsoft Excel installed?

Yes. Spire.XLS for .NET works independently of Microsoft Excel and can create, edit, and format spreadsheets directly through code.

Does formatting change the actual cell values?

No. Most formatting operations only affect how data is displayed. The underlying values remain unchanged unless explicitly modified.

Can I apply the same style to multiple cells at once?

Yes. Styles can be applied to ranges, rows, columns, or entire worksheets, making it easy to maintain consistent formatting.

Does Spire.XLS support conditional formatting?

Yes. The library supports common conditional formatting features, including highlighting rules, data bars, color scales, and icon sets.

Which Excel formats are supported?

Spire.XLS supports XLS, XLSX, XLSM, CSV, and several other spreadsheet formats for both reading and writing.

Visual Guide Showing How to Convert HTML to Markdown in C#

HTML is widely used for web pages, online articles, and rich text content, while Markdown (.md) is often preferred for documentation, technical writing, and text-based publishing. If you need to reuse HTML content in a Markdown-based workflow, converting it manually can be time-consuming and error-prone.

In this tutorial, we’ll show you how to convert HTML to Markdown in C# step-by-step using Spire.Doc for .NET. You’ll learn how to convert HTML files, HTML strings, streams, and multiple HTML files in batch.

Table of Contents

When Do You Need to Convert HTML to Markdown?

Converting HTML to Markdown is useful when you want to reuse web-based or rich-text content in a cleaner, text-friendly format. Common scenarios include:

  • Moving HTML articles or CMS content into Markdown-based documentation systems.
  • Preparing content for GitHub, static site generators, or developer portals.
  • Converting rich text editor output into editable Markdown files.
  • Simplifying HTML pages for version control, review, or long-term maintenance.
  • Exporting help center articles, product descriptions, or blog content as .md files.

Install C# HTML to Markdown Library

To convert HTML to Markdown programmatically, you need to add Spire.Doc for .NET to your project. This standalone document processing library allows you to parse HTML and export it to clean Markdown without requiring Microsoft Word or Microsoft Office interop assemblies on your server.

Method 1: Install via NuGet Package Manager

Run this command in your NuGet Package Manager Console:

Install-Package Spire.Doc

Method 2: Download and Reference DLLs Manually

If your development environment is offline or you prefer not to use NuGet, you can manually download and reference the library:

  1. Download & Unzip: Get the Spire.Doc for .NET package from the official download page and extract it.
  2. Add Reference: In the Solution Explorer of Visual Studio, right-click Dependencies (or References) > Add Project Reference (or Add Reference) > Browse and select the Spire.Doc.dll that matches your target .NET Framework or .NET Core version.

Note: Markdown support is available in Spire.Doc for .NET version 12.3.12 or later.

Convert an HTML File to Markdown in C#

If your HTML content is stored as a local .html or .htm file, you can convert it directly using the Document object. This approach is ideal for processing static web pages, documentation exports, or offline help articles.

C# Code Example

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

namespace ConvertHtmlFileToMarkdown
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize a Document instance within a using statement
            using (Document document = new Document())
            {
                // Load the local HTML file
                document.LoadFromFile("input.html", FileFormat.Html, XHTMLValidationType.None);

                // Export the HTML file to a Markdown file
                document.SaveToFile("output.md", FileFormat.Markdown);
            }
        }
    }
}

How the Code Works:

  • using (Document document = new Document()): Ensures the Document object is properly disposed of after conversion.
  • LoadFromFile("input.html", FileFormat.Html, XHTMLValidationType.None): Reads the source HTML file without strict XHTML validation, allowing the library to parse the HTML even if it doesn’t fully comply with XHTML rules.
  • SaveToFile("output.md", FileFormat.Markdown): Maps the supported HTML elements such as headings, bold text, lists, images, and links into Markdown syntax, and generate the .md file.

Output:

Markdown output generated from HTML in C#

Convert HTML Strings to Markdown in C#

When dealing with dynamic web data—such as content fetched from a database, API responses, or CMS rich-text inputs—you can convert raw HTML strings directly to Markdown without saving them as physical files first.

C# Code Example

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

namespace ConvertHtmlStringToMarkdown
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize a Document instance
            using (Document document = new Document())
            {
                // Add a section and paragraph to host the dynamic html content
                Section section = document.AddSection();
                Paragraph paragraph = section.AddParagraph();

                // Define the source HTML string
                string htmlString = @"
                    <h1>HTML to Markdown Conversion</h1>
                    <p>This is a sample paragraph with a <a href='https://www.example.com'>link</a>.</p>
                    <ul>
                        <li>First item</li>
                        <li>Second item</li>
                        <li>Third item</li>
                    </ul>";

                // Parse and append the HTML string directly into the text paragraph
                paragraph.AppendHTML(htmlString);

                // Save the fully compiled document model as Markdown
                document.SaveToFile("html-string-output.md", FileFormat.Markdown);
            }
        }
    }
}

Key Methods Explanation:

  • document.AddSection() & section.AddParagraph(): An empty Document object does not contain structural layouts. You must explicitly create a parent section and a text paragraph to serve as the container before injecting raw HTML string content.
  • paragraph.AppendHTML(htmlString): Parses the HTML string and inserts supported HTML elements into the document structure.

Output:

Markdown output generated from HTML String in C#

Convert HTML Stream to Markdown in C#

In cloud-ready or backend enterprise applications, HTML content is often processed in memory as a stream rather than being read from a fixed physical path. Using LoadFromStream() and SaveToStream(), you can convert in-memory HTML content directly to a Markdown stream.

This approach is useful for web services, ASP.NET applications, background processing tasks, or conversion APIs where files are uploaded, converted, and returned without permanent disk storage.

C# Code Example

using System.IO;
using System.Text;
using Spire.Doc;
using Spire.Doc.Documents;

namespace ConvertHtmlStreamToMarkdown
{
    class Program
    {
        static void Main(string[] args)
        {
            // Define a sample HTML string to simulate an in-memory input source
            string htmlContent = "<h1>HTML Stream to Markdown Stream</h1><p>This process happens entirely in memory.</p>";
            byte[] htmlBytes = Encoding.UTF8.GetBytes(htmlContent);

            // Create an input stream from the HTML bytes
            using (MemoryStream inputStream = new MemoryStream(htmlBytes))
            {
                // Create an empty memory stream to receive the converted Markdown data
                using (MemoryStream outputStream = new MemoryStream())
                {
                    // Initialize the Document instance
                    using (Document document = new Document())
                    {
                        // Load the HTML content directly from the input stream
                        document.LoadFromStream(inputStream, FileFormat.Html, XHTMLValidationType.None);

                        // Save the converted content directly into the output stream as Markdown
                        document.SaveToStream(outputStream, FileFormat.Markdown);
                    }

                    // Crucial: Reset the output stream position to the beginning before reading it
                    outputStream.Position = 0;

                    // Optional: Convert the output stream back to a string to verify the result (you can also save it as a .md file)
                    using (StreamReader reader = new StreamReader(outputStream, Encoding.UTF8))
                    {
                        string markdownResult = reader.ReadToEnd();
                        System.Console.WriteLine(markdownResult);
                    }
                }
            }
        }
    }
}

Batch Convert Multiple HTML Files

For large-scale publishing workflows, you can automate the conversion of multiple HTML files to Markdown using a loop.

C# Code Example

The following example converts all .html files in a source folder to .md files in an output folder.

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

namespace BatchConvertHtmlToMarkdown
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string inputFolder = @"C:\HtmlFiles";
            string outputFolder = @"C:\MarkdownFiles";

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

            // Get all HTML files
            string[] htmlFiles = Directory.GetFiles(inputFolder, "*.html");

            foreach (string htmlFile in htmlFiles)
            {
                try
                {
                    string fileName = Path.GetFileNameWithoutExtension(htmlFile);
                    string outputPath = Path.Combine(outputFolder, fileName + ".md");

                    using (Document document = new Document())
                    {
                        document.LoadFromFile(htmlFile, FileFormat.Html, XHTMLValidationType.None);
                        document.SaveToFile(outputPath, FileFormat.Markdown);
                    }

                    Console.WriteLine($"Converted: {Path.GetFileName(htmlFile)}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Failed to convert {Path.GetFileName(htmlFile)}");
                    Console.WriteLine($"Error: {ex.Message}");
                }
            }

            Console.WriteLine("HTML to Markdown batch conversion completed.");
        }
    }
}

What HTML Elements Can Be Converted to Markdown?

HTML has many elements, but Markdown supports only a smaller set of document structures. During conversion, content-focused elements are usually easier to preserve than layout-focused or style-heavy elements. For instance, standard Markdown tables only support basic rows and columns. If your source contains complex tables, you might want to convert HTML to Excel in C# instead.

The following table summarizes common HTML elements and how they may appear in Markdown.

HTML Element Markdown Syntax
<h1> to <h6> # to ###### (Headings)
<p> Plain paragraph
<strong>, <b> **bold**
<em>, <i> *italic*
<ul>, <ol>, <li> Bulleted or numbered lists
<a> [Link Text](URL)
<img> ![Alt Text](Image URL/Path)
<table> Markdown table
<code> Inline code
<pre> Code block
<br> Line break
<div>, <section> Usually simplified
CSS styles Limited or removed
JavaScript Not supported

Tip: Actual output may vary depending on the source HTML structure and the Markdown features supported by the target editor or platform.

Troubleshooting Common HTML to Markdown Issues

  • Images not showing: Verify that all image paths are still valid after conversion; relative paths may need adjustment.
  • Tables look different: Markdown supports only basic tables. For complex tables with merged cells, nested layouts, or custom styling, simplify the HTML table before conversion or manually adjust the generated Markdown table afterward.
  • Special characters appear incorrectly: This is usually an encoding issue. Make sure the source HTML file uses UTF-8 encoding and open the generated Markdown file in an editor that supports UTF-8.
  • Extra blank lines: Remove unnecessary empty tags, nested div elements, or redundant br tags from the source HTML before conversion. You can also clean the generated Markdown file afterward by opening it in a text editor like Notepad++ and then performing a find & replace.

Conclusion

With Spire.Doc for .NET, converting HTML to Markdown in C# can be implemented in just a few lines of code. This guide covered the core approaches needed for various development scenarios:

  • Converting local HTML files and streams to Markdown.
  • Inserting and converting dynamic HTML strings.
  • Batch converting multiple HTML files simultaneously.

If your workflow also requires the reverse process, see this tutorial on how to convert Markdown to HTML in C#.

Frequently Asked Questions

Q1: Will images be preserved during HTML to Markdown conversion?

A1: Yes. Standard HTML <img> tags can be converted into Markdown image syntax (![Alt Text](Image URL/Path)). Just ensure your source HTML links use valid URLs or correct file paths so the images can load.

Q2: Can I convert an HTML string or stream to Markdown without saving files?

A2: Yes. You can load an HTML string using AppendHTML() or a stream via LoadFromStream(), then export it entirely in memory using SaveToStream() without hitting the local disk.

Q3: Can I convert multiple HTML files to Markdown at once in C#?

A3: Yes. You can use a foreach loop in C# to scan a folder for *.html files, process each file through the converter, and output them to a destination folder in bulk.

Q4: Is Microsoft Word required for HTML to Markdown conversion?

A4: No. Spire.Doc for .NET is a standalone library, so Microsoft Word does not need to be installed.

Spire.XLS guide to convert CSV to XML in C#

CSV (Comma-Separated Values) and XML (Extensible Markup Language) are two mainstream data exchange formats in modern software development. CSV excels at lightweight storage and transmission of tabular data, while XML is widely used for cross-system data interaction due to its hierarchical structure and strict validation rules. Converting CSV to XML is a common demand in scenarios such as configuration file generation, database record export, and third-party API integration.

Manual CSV parsing and XML generation are error-prone, inefficient, and difficult to maintain for large datasets. For C# developers, Spire.XLS for .NET provides a lightweight, high-performance solution for CSV-to-XML conversion.

This article will guide you through two core methods to convert CSV to XML in C# using Spire.XLS, covering basic conversion and customized XML output with complete code examples.


Prerequisites

Install Spire.XLS via NuGet

The quickest way to add Spire.XLS to your project is through the NuGet Package Manager. In Visual Studio, run the following command in the Package Manager Console:

Install-Package Spire.XLS

Alternatively, search for “Spire.XLS” in the NuGet UI and install the latest version.

Prepare a Sample CSV Data (For Testing)

Create a Products.csv file in your project’s output folder with this sample tabular data (includes headers and rows):

ID,ProductName,Category,Price,StockQuantity,ReleaseDate
1,Laptop,Electronics,999.99,50,2023-01-15
2,Wireless Mouse,Electronics,25.50,200,2023-02-20
3,Cotton T-Shirt,Apparel,19.99,150,2022-11-05
4,Coffee Mug,Home Goods,12.99,300,2022-09-10
5,Desk Chair,Furniture,150.00,75,2023-03-01

Understanding the Two XML Output Types

When converting CSV file to XML using Spire.XLS for .NET, you can produce two distinct types of XML output:

1. Excel XML (SpreadsheetML)

A standardized XML format based on Microsoft's Open XML specification. It retains the original table layout, cell formatting and overall structure of the CSV file. This is an ideal choice if you need to open, edit or process the generated XML with Excel and other spreadsheet-compatible tools.

2. Custom XML Structure

A user-defined XML schema enables free mapping of CSV columns to custom element tags, nested hierarchies, and adjustable presentation rules. This is ideal for integrating with third-party APIs, legacy systems, and business platforms that require specific fixed XML node structures.

Both approaches are covered in detail with C# code examples in the following sections. For developers working in Python, refer to our separate guide: Convert CSV to XML in Python


Method 1: Convert CSV to Excel XML in C#

This is the simplest approach that requires only a few lines of code. The CSV is loaded into a Workbook, then saved directly as Excel XML (SpreadsheetML) format. Suitable for cases where the target system accepts Excel's native XML format.

CSV to XML C# Code Example:

using Spire.Xls;

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

            // Load CSV into the first worksheet
            workbook.LoadFromFile("Products.csv", ",", 1, 1);

            // Save as Excel SpreadsheetML format
            workbook.SaveAsXml("output.xml");

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

Core Methods:

  • LoadFromFile() – Spire.XLS automatically parses the CSV content into the first worksheet of the workbook.
  • SaveAsXml() – Export the loaded CSV data as an Excel XML file.

The core data parts looks like:

Convert CSV to SpreadsheetML using C# and Spire.XLS

Beyond converting CSV files, Spire.XLS for .NET also enables seamless conversion of Excel (XLS / XLSX) to XML using the same robust Workbook.SaveAsXml() method.


Method 2: Convert CSV to Custom XML in C#

When the target system expects a specific XML schema, you’ll need to build a custom XML document. Spire.XLS, together with the built-in .NET XmlWriter class, makes this straightforward: simply iterate over worksheet rows and columns, then generate well-structured XML efficiently.

Custom XML Code Example:

using Spire.Xls;
using System.Xml;

namespace CSVtoXMLConverter
{
    class program
    {
        static void Main(string[] args)
        {

            // Initialize workbook and load CSV
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Products.csv", ",", 1, 1);
            Worksheet worksheet = workbook.Worksheets[0];

            // Create custom XML settings (indentation for readability)
            XmlWriterSettings settings = new XmlWriterSettings
            {
                Indent = true,
                IndentChars = "\t",
                OmitXmlDeclaration = false,
                Encoding = System.Text.Encoding.UTF8
            };

            // Save CSV to XML with CUSTOM ROOT NODE and FORMATTING
            XmlWriter writer = XmlWriter.Create("Custom_Output.xml", settings);

            writer.WriteStartDocument();
            // Custom root element: <ProductInventory>
            writer.WriteStartElement("ProductInventory");


            // Loop through CSV rows (skip header row: start at 2)
            for (int row = 2; row <= worksheet.LastRow; row++)
            {
                // Custom data node: <Product>
                writer.WriteStartElement("Product");

                // Loop through CSV columns and write custom elements
                for (int col = 1; col <= worksheet.LastColumn; col++)
                {
                    string header = worksheet.Range[1, col].Text;
                    string value = worksheet.Range[row, col].Text;
                    writer.WriteElementString(header, value);
                }

                writer.WriteEndElement(); // Close <Product>
            }

            writer.WriteEndElement(); // Close <ProductInventory>
            writer.WriteEndDocument();

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

    }
}

How the code works:

  • Load the CSV file into a Workbook.
  • Access the worksheet – Retrieve the first worksheet containing the imported data.
  • Create an XmlWriter – Configure it with indentation, encoding, and other formatting preferences.
  • Write the XML document – Start the document, write the custom root element, then loop through rows (skipping the header row) and columns, writing an element per column using the header text as the tag name.
  • Close resources – Close the XmlWriter and dispose of the Workbook.

Output:

The generated XML uses <ProductInventory> as the root node and <Product> as the data node, with child nodes named after CSV headers, fully matching custom business requirements.

Convert CSV to custom XML structure using C# and Spire.XLS

Bonus Tip: For scenarios requiring formal document delivery, you can also use Spire.XLS for .NET to convert XML files to PDF in C# effortlessly.


Handling Real‑World CSV Scenarios

Real-world CSV files often have non-standard delimiters, empty values, redundant rows/columns, or missing headers. The following solutions solve these common problems:

Different Delimiters

CSV files may use tabs (\t), semicolons (;), or pipes (|). Spire.XLS supports specifying custom delimiters when loading CSV files:

// Tab-separated
workbook.LoadFromFile("data.tsv", "\t", 1, 1);

// Semicolon-separated (common in European locales)
workbook.LoadFromFile("data.csv", ";", 1, 1);

// Pipe-separated
workbook.LoadFromFile("data.psv", "|", 1, 1);

Skipping Rows and Columns

If the CSV contains metadata rows or empty columns, adjust your loop bounds:

// start from row 3
for (int row = 3; row <= worksheet.LastRow; row++)
//start from column 3
for (int col = 3; col <= worksheet.LastColumn; col++)

Handling Missing Values and Empty Cells

Empty cells in CSV files appear as empty strings. You can handle them by writing a default value or omitting the elements:

// Option 1: Fill empty values with "N/A"
string value = worksheet.Range[row, col].Text;
if (string.IsNullOrEmpty(value))
    value = "N/A";   
writer.WriteElementString(header, value);

// Option 2: Omit empty nodes
string value = worksheet.Range[row, col].Text;
if (!string.IsNullOrEmpty(value))
    writer.WriteElementString(header, value);

Missing Header Row

If your CSV has no header row, you can pass an array of custom names, or generate generic column names such as:

for (int col = 1; col <= worksheet.LastColumn; col++)
{
    string header = $"Column{col}";
    string value = worksheet.Range[row, col].Text;
    writer.WriteElementString(header, value);
}

Conclusion​

Converting CSV to XML in C# with Spire.XLS for .NET eliminates manual parsing and reduces code complexity. Whether you need a simple one-line conversion to Excel XML or a fully customized XML structure, the code examples in this guide let you seamlessly integrate CSV-to-XML conversion into your C# applications.

For more Excel or CSV-related tasks in .NET development, visit the online documentation.


FAQs About CSV to XML Conversion

Q1: Can I convert only a specific range of cells (e.g., A1:C10)?

Yes. Instead of looping to worksheet.LastRow and LastColumn, set custom bounds (e.g., loop rows 2 to 11 for A1:C10) or directly access a range via worksheet.Range.

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

No, it is an independent .NET component and does not rely on Microsoft Excel, Office interop, or any third-party Office software.

Q3: Can I batch convert multiple CSV files to XML at once?

Yes. You can loop through all CSV files in a folder, load each one with Spire.XLS, and export them to corresponding XML files in batches with the same logic in the tutorial.

Q4: Can I add custom attributes and namespaces to generated XML elements?

Absolutely. Use XmlWriter.WriteAttributeString() to add custom attributes to nodes, and WriteStartElement with namespace parameters to define XML namespaces for enterprise-standard XML schemas.

Page 1 of 96
page 1