IC Improve Code Recipes

Recipe 11.3 · C#

Excel Export with ClosedXML

Problem

Users want a real spreadsheet: numbers that sum, dates that sort, a header row that stays in place. The legacy answers are an HTML table renamed to .xls, which triggers Excel's "format and extension don't match" warning, or Excel automation through COM on the server, which Microsoft explicitly does not support and which leaves EXCEL.EXE processes running until someone reboots.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition",
    "attachment; filename=report.xls");
var sw = new StringWriter();
var hw = new HtmlTextWriter(sw);
gridView.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();

Every value is text, so the balance column cannot be summed, leading zeros vanish from account numbers, and the user sees a security-sounding warning on every open.

The improved recipe

ClosedXML writes genuine .xlsx files with no Excel installation. The exporter reuses the ExportColumn<T> definitions from Recipe 11.1, writes typed cell values, applies number formats per column, formats the range as an Excel table with filters, freezes the header and sizes the columns.

NuGet package: ClosedXML.

C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ClosedXML.Excel;

namespace ImproveCode.Export;

public static class ExcelExporter
{
    private const int MaxSheetNameLength = 31;

    public static void Export<T>(
        Stream destination,
        string sheetName,
        IEnumerable<T> records,
        IReadOnlyList<ExportColumn<T>> columns)
    {
        ArgumentNullException.ThrowIfNull(destination);
        ArgumentNullException.ThrowIfNull(records);
        ArgumentNullException.ThrowIfNull(columns);

        using var workbook = new XLWorkbook();
        var sheet = workbook.Worksheets.Add(SafeSheetName(sheetName));

        for (int c = 0; c < columns.Count; c++)
        {
            sheet.Cell(1, c + 1).Value = columns[c].Header;
        }

        int row = 1;
        foreach (T record in records)
        {
            row++;
            for (int c = 0; c < columns.Count; c++)
            {
                sheet.Cell(row, c + 1).Value =
                    ToCellValue(columns[c].Value(record));
            }
        }

        for (int c = 0; c < columns.Count; c++)
        {
            if (columns[c].Format is { } format)
            {
                sheet.Column(c + 1).Style.NumberFormat.Format = format;
            }
        }

        var table = sheet.Range(1, 1, Math.Max(row, 2), columns.Count)
                         .CreateTable();
        table.Theme = XLTableTheme.TableStyleLight9;
        sheet.SheetView.FreezeRows(1);
        sheet.Columns(1, columns.Count)
             .AdjustToContents(1, Math.Min(row, 500), 8, 60);

        workbook.SaveAs(destination);
    }

    public static XLCellValue ToCellValue(object? value) => value switch
    {
        null => Blank.Value,
        string s => s,
        bool b => b,
        DateTime d => d,
        DateOnly d => d.ToDateTime(TimeOnly.MinValue),
        DateTimeOffset d => d.DateTime,
        TimeSpan t => t,
        decimal m => m,
        double n => n,
        float n => n,
        int n => n,
        long n => n,
        short n => n,
        Enum e => e.ToString(),
        _ => value.ToString() ?? ""
    };

    private static string SafeSheetName(string name)
    {
        char[] invalid = [':', '\\', '/', '?', '*', '[', ']'];
        string cleaned = new string(name
            .Select(ch => invalid.Contains(ch) ? '_' : ch).ToArray())
            .Trim('\'').Trim();
        if (cleaned.Length == 0)
        {
            cleaned = "Sheet1";
        }
        return cleaned.Length > MaxSheetNameLength
            ? cleaned[..MaxSheetNameLength]
            : cleaned;
    }
}

A usage snippet for an ASP.NET Core minimal API endpoint:

C#
app.MapGet("/customers/export", async (CustomerRepository repo,
    CancellationToken ct) =>
{
    var customers = await repo.ListAsync(ct);
    var stream = new MemoryStream();
    ExcelExporter.Export(stream, "Customers", customers, columns);
    stream.Position = 0;
    return Results.File(stream,
        "application/vnd.openxmlformats-officedocument" +
        ".spreadsheetml.sheet", "customers.xlsx");
});

How it works

ToCellValue maps .NET types to Excel's own: numbers stay numbers, dates become real Excel dates, booleans become TRUE and FALSE. That is what makes sums, sorting and filters work. Strings stay strings, so an account number such as 00123 keeps its leading zeros as long as you pass it as a string. A string that starts with = is stored as text, not a formula; ClosedXML only creates formulas through the FormulaA1 property, so the CSV injection problem from Recipe 11.1 does not apply here.

Number formats are set on whole columns, not on each cell, which keeps the file small and the export fast. Use Excel's format codes: #,##0.00 for money, yyyy-mm-dd for dates, 0% for percentages. Column formats apply to cells written in that column, while the header cells keep their text.

CreateTable turns the range into an Excel table, which gives users filter buttons, banded rows and a name they can refer to in formulas. The range always includes at least one data row, because Excel cannot open a file whose table has a header and no body. FreezeRows(1) keeps the header visible while scrolling.

AdjustToContents measures text to size columns. It is the slowest call in the method, so it looks at the first 500 rows only, and widths are clamped between 8 and 60 characters so one long comment field does not make a column three screens wide.

Sheet names have rules: no more than 31 characters and none of : \ / ? * [ ]. SafeSheetName enforces them, since report names often come from user input.

Variations and pitfalls

  • Memory. ClosedXML builds the whole workbook in memory. Up to a few hundred thousand cells it is fine. For millions of cells, write CSV, or use the lower-level DocumentFormat.OpenXml SDK with its streaming OpenXmlWriter.
  • Excel's row limit. A worksheet holds 1,048,576 rows. Check the count before exporting, and offer CSV above it.
  • DataTable sources. sheet.Cell(1, 1).InsertTable(dataTable) exports a DataTable in one line. Typed records with explicit columns give you control over headers and formats, which is why I prefer them for new code.
  • Don't automate Excel on a server. COM automation of Office in services or web applications is unsupported by Microsoft, slow, and leaks processes. No exceptions.