Excel export library
- gh: Xlsx Data Export Pitch
- [[pitch-xlsx-data-export]]
Purpose
Section titled “Purpose”Xlsx-Report is a small library for exporting tabular data to Microsoft Excel (XLSX). It is built around two concepts:
- ColumnDefinitions → describe how each column should look
- TableWriters → write rows of data into a worksheet
- create a new report
- add as many sheets as needed
using var report = XlsxReport.New(_options);var sheet = report.Sheets.Add("sheetname");- fill the sheet with data
sheet.FillData(data, columns)The Interface of a Sheet looks like this:
public interface IReportSheet{ public CellReference CursorCell { get; set; } FillOptions FillOptions { get; set; } IReportSheet FillData<T>(IEnumerable<T> data); IReportSheet FillData<T>(IEnumerable<T> data, params Expression<Func<T, object?>>[] columns); IReportSheet FillData<T>(IEnumerable<T> data, params ColumnDefinition<T>[]? columns); IReportSheet FillData(IEnumerable data, params DynamicColumnDefinition[] columns); IReportSheet FillData<T>(IEnumerable<T> data, params DynamicColumnDefinition[] columns); public FillDataResult FillResult { get; internal set; } ImmutableArray<ReportCell> GetCells(); string Name { get; }}- save the excel to a directory
report.Save(path);ColumnDefinitions
Section titled “ColumnDefinitions”A column defines:
- Name (the header shown in Excel)
- Expression (the value of the column for one row)
- Format (optional Excel number format code, e.g.
#,##0.00oryyyy-mm-dd) - Width (optional width in Excel character units)
Example:
var columns = new[]{ new ColumnDefinition<Order>("Order ID", o => o.Id), new ColumnDefinition<Order>("Customer", o => o.CustomerName), new ColumnDefinition<Order>("Date", o => o.OrderDate) { Format = "dd.MM.yyyy" }, new ColumnDefinition<Order>("Amount", o => o.Total) { Format = "#,##0.00", Width = 14 }};A format is registered in the workbook’s stylesheet once, however many columns or sheets use it.
Without a format, DateTime uses Excel’s built-in date-time format and DateOnly its date format.
Tables, frozen headers and column widths
Section titled “Tables, frozen headers and column widths”FillOptions decides how a fill is laid out. Set them per sheet before filling:
var sheet = report.Sheets.Add("Orders");sheet.FillOptions = sheet.FillOptions with{ TableName = "Orders", // write an Excel table (ListObject) with header row and auto-filter FreezeHeaderRow = true, // keep the header visible while scrolling AutoFitColumns = true // size columns without an explicit Width to their content};sheet.FillData(orders, columns);- A table name must be unique in the workbook, start with a letter or underscore, contain only
letters, digits, underscores and periods, and must not look like a cell reference (
A1,R1C1). Header names must be non-empty, unique within the table and at most 255 characters long. These constraints are checked before any row is written; a violation throwsInvalidOperationException. - Explicit column widths must be finite values from 0 to 255 inclusive, in Excel character units.
Invalid widths throw
InvalidOperationExceptionbefore any row is written. - Auto-fit measures only columns without explicit widths. It reuses converted text for custom objects, without invoking their formatter again.
- An empty result still makes a valid table: its range is the header plus one blank row.
TableStylepicks the built-in table style (defaultTableStyleMedium2).- Set
TableNameper fill, not inXlsxReportOptions.DefaultFillOptions, which every sheet shares.
TableWriters
Section titled “TableWriters”The writer takes data + column definitions and writes them into a sheet.
var writer = new TableWriter<Order>(columns);writer.Write(orders, worksheet);There are two modes:
- Generic (with Expressions) → type-safe, compile-time checked
- Dynamic (with strings or reflection) → useful for metadata-driven reports
Data Types & Formats
Section titled “Data Types & Formats”- DateTime → needs special treatment:
DateTime dt => new Cell { DataType = null, CellValue = new CellValue(dt.ToOADate()), CellReference = cellReference, StyleIndex = 1 }, DateOnly dateOnly => new Cell { DataType = null, CellValue = new CellValue(dateOnly.ToDateTime(TimeOnly.MinValue).ToOADate()), CellReference = cellReference, StyleIndex = 2 }- both need a Style, to be formatted correctly in Excel:
var stylesheet = new Stylesheet(new Fonts(new Font()),new Fills(new Fill()),new Borders(new Border()),new CellFormats( new CellFormat(), // Index 0 = Default new CellFormat { NumberFormatId = 22, ApplyNumberFormat = true }, // Index 1 new CellFormat { NumberFormatId = 14, ApplyNumberFormat = true } // Index 2));- Numeric → Cellvalues.Number, written culture-independently (
1234.5, whateverCultureInfothe report uses) - Boolean → written as 1 / 0
- Strings → written as-is, as inline strings; text that looks like a formula (
=1+1) stays text