Export to Excel in C#: DataTable, SQL, List, DataSet & More

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 | dispatch@nordicfreight.example | 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.