Export DataSet or DataTable to Excel in C# .NET (Examples)
Export DataSet to Excel xlsx file in C# .NET

To export a DataSet or DataTable to an Excel (.xlsx) file in C#, you can use either ClosedXML (shortest code, one call per table) or the free Open XML SDK from Microsoft (official docs) (no third-party dependency). Neither needs Microsoft Office installed on the machine. Each DataTable becomes its own worksheet.

The code below was built and run on .NET 10 with DocumentFormat.OpenXml 3.5.1 and ClosedXML 0.105.1, and works the same on .NET 8 and .NET 9.

It’s 4:45 PM and your manager asks, “Can you send me that report as an Excel file?” The data is sitting in SQL Server, your app already loads it into a DataSet, and all you need is a clean .xlsx with one sheet per table. No Excel installation, no copy and paste.

You can do that in about 15 lines of C#. Here is the whole idea in one picture, and the working code follows.

Animation showing SQL Server tables filled into a DataSet and exported as separate sheets of an Excel xlsx file in C#
Each DataTable in your DataSet becomes its own worksheet.

Which approach should you choose?

  • ClosedXML: easiest, built-in header row, column auto-fit and cell formatting. Best for most apps and reports.
  • Open XML SDK: official Microsoft library, no extra dependency and full control, but you write more code. Best when you must stay on Microsoft packages or process very large files.
  • Prefer EPPlus or NPOI? See Read/Write Excel using EPPlus (EPPlus has a commercial license for business use).

Prerequisites

  • A .NET 8, 9 or 10 project (a console app is enough).
  • Install one of the packages below.
dotnet add package ClosedXML
dotnet add package DocumentFormat.OpenXml

Step 1: Load data into a DataSet from SQL Server

Fill a DataSet with SqlDataAdapter. Table mappings give each worksheet a readable name. Install Microsoft.Data.SqlClient first. The older System.Data.SqlClient is deprecated.

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

public static DataSet LoadDataSet(string connectionString)
{
    var dataSet = new DataSet();
    using var connection = new SqlConnection(connectionString);
    using var adapter = new SqlDataAdapter(
        "SELECT Id, Name, Salary FROM Employees; SELECT Code, Title FROM Departments;", connection);
    adapter.TableMappings.Add("Table", "Employees");
    adapter.TableMappings.Add("Table1", "Departments");
    adapter.Fill(dataSet);
    return dataSet;
}

New to database access in .NET? See Connect SQL Server with ADO.NET or Getting started with EF Core.

Step 2, option A: Export DataSet to Excel using ClosedXML

Worksheets.Add(DataTable, name) writes the header row and all data in one call:

using ClosedXML.Excel;
using System.Data;

public static void ExportWithClosedXml(DataSet dataSet, string filePath)
{
    using var workbook = new XLWorkbook();
    foreach (DataTable table in dataSet.Tables)
    {
        var sheet = workbook.Worksheets.Add(table, table.TableName);
        sheet.Columns().AdjustToContents();
    }
    workbook.SaveAs(filePath);
}

Call it with ExportWithClosedXml(dataSet, "report.xlsx");. Numbers stay numeric and dates stay real Excel dates.

Step 2, option B: Export DataSet to Excel using the Open XML SDK

This version writes each table to its own sheet, keeps numbers numeric and applies a date format, so dates don’t appear as serial numbers such as 44634.

using System.Data;
using System.Globalization;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

public static void ExportWithOpenXml(DataSet dataSet, string filePath)
{
    using var document = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook);
    var workbookPart = document.AddWorkbookPart();
    workbookPart.Workbook = new Workbook();
    var sheets = workbookPart.Workbook.AppendChild(new Sheets());

    AddDateStyle(workbookPart);   // style index 1 = date format
    uint sheetId = 1;             // declared OUTSIDE the loop: every sheet needs a unique id

    foreach (DataTable table in dataSet.Tables)
    {
        var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
        var sheetData = new SheetData();
        worksheetPart.Worksheet = new Worksheet(sheetData);
        sheets.Append(new Sheet
        {
            Id = workbookPart.GetIdOfPart(worksheetPart),
            SheetId = sheetId++,
            Name = table.TableName
        });

        var header = new Row();
        foreach (DataColumn column in table.Columns)
            header.Append(new Cell { DataType = CellValues.String, CellValue = new CellValue(column.ColumnName) });
        sheetData.Append(header);

        foreach (DataRow dataRow in table.Rows)
        {
            var row = new Row();
            foreach (DataColumn column in table.Columns)
                row.Append(ToCell(dataRow[column]));
            sheetData.Append(row);
        }
    }
    workbookPart.Workbook.Save();
}

static Cell ToCell(object? value) => value switch
{
    null or DBNull => new Cell { DataType = CellValues.String, CellValue = new CellValue("") },
    int or long or short or decimal or double or float => new Cell
    {
        DataType = CellValues.Number,
        CellValue = new CellValue(Convert.ToString(value, CultureInfo.InvariantCulture)!)
    },
    DateTime dt => new Cell
    {
        DataType = CellValues.Number,
        StyleIndex = 1,
        CellValue = new CellValue(dt.ToOADate().ToString(CultureInfo.InvariantCulture))
    },
    bool b => new Cell { DataType = CellValues.Boolean, CellValue = new CellValue(b ? "1" : "0") },
    _ => new Cell { DataType = CellValues.String, CellValue = new CellValue(value.ToString() ?? "") }
};

static void AddDateStyle(WorkbookPart workbookPart)
{
    var stylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
    stylesPart.Stylesheet = new Stylesheet(
        new Fonts(new Font()),
        new Fills(new Fill(new PatternFill { PatternType = PatternValues.None }),
                  new Fill(new PatternFill { PatternType = PatternValues.Gray125 })),
        new Borders(new Border()),
        new CellStyleFormats(new CellFormat()),
        new CellFormats(
            new CellFormat(),                                                   // 0 = default
            new CellFormat { NumberFormatId = 14, ApplyNumberFormat = true }));  // 1 = short date
    stylesPart.Stylesheet.Save();
}

What the Excel file looks like

Open report.xlsx and you will find two sheets, Employees and Departments. The header row comes from the column names, numbers stay numeric (so formulas and sorting work), and dates show as real dates. I checked this by reading the generated files back and validating the Open XML output (0 errors).

Excel workbook report.xlsx with Employees and Departments sheet tabs and a header row with Id, Name, Salary and Joined columns
The exported workbook: one sheet per DataTable, numbers and dates preserved.

Common problems and fixes

  • Excel says the file is corrupt or needs repair: with the Open XML SDK each Sheet needs a unique SheetId, and sheet names must be unique, 31 characters or fewer, and free of : \ / ? * [ ]. Many older examples reset the sheet counter inside the loop, which gives every sheet the same id.
  • Dates appear as numbers like 44634: Excel stores dates as serial numbers. Apply a date style as shown above, or use ClosedXML, which does it for you.
  • Very large exports use a lot of memory: the DOM approach used here holds the whole sheet in memory. For hundreds of thousands of rows, use the Open XML SDK’s OpenXmlWriter (SAX-style) or export to CSV.
  • Empty database values: DBNull is written as an empty cell, as handled in ToCell.

Frequently asked questions

Do I need Microsoft Office installed to create an Excel file in C#?

No. ClosedXML and the Open XML SDK write the .xlsx file directly. Server and Docker environments need no Excel installation.

How do I export a DataTable to Excel instead of a DataSet?

Pass a single table: with ClosedXML call workbook.Worksheets.Add(table, "Sheet1"). For the Open XML code, wrap it in a DataSet with new DataSet().Tables.Add(table).

Can I read the Excel file back?

Yes. See Read Excel files in C# .NET and Read Excel as JSON using the Open XML SDK.

Summary

To export a DataSet to Excel in C#, load your tables into a DataSet, then use ClosedXML for the shortest code or the Open XML SDK when you want no third-party dependency. Give each sheet a unique id and name, and apply a date format so values display correctly in Excel.

Found this useful?

Bookmark this page and share it with your team. Get new .NET, cloud and database tutorials in your inbox.

Leave a Reply

Your email address will not be published. Required fields are marked *