Excel template reference
Introduction
Section titled “Introduction”XlsxTemplate fills an author-designed Excel workbook with report data while preserving its layout, styles, and number formats. It complements — and does not replace — the XlsxReport export builder: XlsxReport builds new workbooks from code; XlsxTemplate binds data into workbooks you design in Excel.
using var template = XlsxTemplate.New("Templates/chart-data.xlsx", options);var filled = template.Fill(data);filled.Save("Output/chart-data.xlsx");XlsxTemplate.New(path)/New(stream)load the workbook into memory.Fill(data)clones the workbook, applies bindings, and returns a newIXlsxTemplate. The source stays untouched and can be filled again with different data.Save(path)andOutputAsStream()behave like theirDocxTemplatecounterparts.XlsxTemplateOptionssupplies logging (LoggerFactory),CultureInfo, and the expression-interpreter factories.
Expressions use the same DynamicExpresso syntax as DocxTemplate; the root fill object is available as this.
Bindings Live in Cell Notes
Section titled “Bindings Live in Cell Notes”All bindings are written as legacy cell notes — in Excel: right-click a cell → New Note (⚠ not New Comment; modern threaded comments are not supported). The visible cell value is only an authoring placeholder; the note holds the expression.
Every note is removed from the filled workbook, including notes on skipped structures and notes that are not bindings at all. Do not use notes to carry information intended for the recipient.
Single-Value Bindings
Section titled “Single-Value Bindings”A note outside any repeating structure is evaluated once against the root object:
| Cell | Visible value | Note |
|---|---|---|
| B1 | Customer placeholder | this.CustomerName |
| B2 | 0 | this.TotalAmount |
On success the cell receives a native XLSX value — the cell’s style and number format are kept, so format date/currency cells in Excel and the filled value renders accordingly. On an evaluation error or a null result, the template value stays and a warning is logged. A note may sit on an empty cell; the cell is created on fill.
Supported value types: strings, bool, all numeric types, DateTime, and DateOnly (dates are written as serial values; give the cell a date number format). Anything else is written as text via ToString().
Row-Oriented Tables (ListObjects)
Section titled “Row-Oriented Tables (ListObjects)”An Excel table (Insert → Table) with one header row and exactly one data row is a tabular-data anchor:
- The note on the first header cell evaluates a collection against the root object.
- The single data row is the row template. Its notes evaluate per collection item, where
thisis the item. - The filler duplicates the template row once per item, preserving cell styles, row height, and formula text, then extends the table (and its auto-filter) to cover the generated rows.
- An empty collection removes the template row and keeps the header.
When the fill data is itself a collection, use this as the first header cell’s note. For example, a Person[] root value uses this on A1 and this.FirstName, this.LastName, and so on in its template data row.
| Cell | Visible value | Note |
|---|---|---|
| A1 | Name | this.Items |
| B1 | Price | |
| A2 | placeholder | this.Name |
| B2 | 0 | this.Price |
Keep the worksheet row below the table blank — it is required expansion room. Content further down within the table’s columns is shifted down, not overwritten; content in other columns stays in place (Excel’s own insert-table-row behavior), so tables can sit beside other content or other tables.
Not supported (the table is skipped with a warning): multiple template data rows, totals rows, and merged cells in the template row.
Horizontal Repeating Grids (@repeat-grid)
Section titled “Horizontal Repeating Grids (@repeat-grid)”A grid produces chart-shaped data: categories down the first column, one series per following column — the layout a Word default line chart expects.
The note on the grid’s top-left (anchor) cell declares two named iterators:
@repeat-grid columns <alias> in <expression>; rows <alias> in <expression>@repeat-grid rows <alias> in <expression>; columns <alias> in <expression>- The first clause is the outer iterator; the second clause’s expression may reference the outer alias. A trailing semicolon is tolerated.
- The cell right of the anchor is the series template column (expanded rightward, once per column item).
- The cell below the anchor is the row-label template, and the cell diagonal to the anchor is the data-cell template (both expanded downward, once per row item).
- The outer expression evaluates against the root object; the inner expression evaluates with the outer alias in scope. Cell notes may reference either alias or both.
- With
rowsfirst the grid is transposed: each outer item becomes a generated row (labels down the anchor column) and the inner items expand across the header row.
| Row | A | B |
|---|---|---|
| 1 | (blank)Note: @repeat-grid columns fruit in this; rows point in fruit.Values |
SeriesNote: fruit.Name |
| 2 | YearNote: point.Year |
0Note: point.Value |
Filled with three fruits of four yearly values each, this becomes a 5×4 range: years in column A (from the first fruit), one series column per fruit, with column B’s width and styles carried to the generated columns.
The axis is positional. The first outer item establishes the shared axis; before anything is written, every outer item is verified to produce the same count and ordered axis values. On a mismatch the whole grid is skipped with a warning — normalize your data (same years, same order, padded values) before filling. The engine never joins series to categories by axis value.
A grid may be wrapped in an Excel table for styling: a table whose range covers the grid template grows with the expansion, and its column definitions are rebuilt from the generated header cells.
Keep the worksheet column right of the series template column blank. Content further right on the grid’s two template rows is shifted right, and content below within the grid’s generated columns is shifted down — neither is overwritten. Everything outside those bands stays in place, so grids can sit side by side on the same rows.
Processing Rules and Limits
Section titled “Processing Rules and Limits”- Worksheets are processed in workbook order; single-value bindings first, then repeating structures top-to-bottom, left-to-right.
- At most 10 repeating structures per worksheet and 10,000 generated rows or columns per structure.
- Expansion shifts are bounded like Excel’s insert-cells: inserted rows move only the cells in the structure’s columns, inserted columns move only the cells on a grid’s two template rows. Row heights and column widths never travel with shifted content.
- Overlapping or nested structures are skipped with a warning, as is a structure whose bounded expansion would cut through or partially shift another structure.
- Merged cells and note-less table ranges fully inside a shifted band move or grow with it; ranges only partially covered by the band are left as authored, so keep them clear of expansion areas.
- Formula text is preserved verbatim when rows/columns are cloned — references are not adjusted the way Excel does on copy/paste. The filled workbook is marked to fully recalculate when opened; the engine never calculates formulas itself.
- Charts inside the template workbook are not rebound: a chart referencing
B1:B5will not pick up generated series columns.
Failure Semantics
Section titled “Failure Semantics”| Situation | Behavior |
|---|---|
Single-value binding: evaluation error or null |
Template value kept, warning logged |
Collection marker: error, null, or non-enumerable |
Structure skipped, warning logged |
| Grid row-axis mismatch across series | Grid skipped, warning logged |
| Data cell in a generated row/column: evaluation or conversion error | Empty cell (style kept), warning logged with the expression and zero-based item index |
Skipped structures keep their placeholder values but still lose their notes — inspect the warnings (via XlsxTemplateOptions.LoggerFactory) rather than the output to detect fill problems.
Report Schema
Section titled “Report Schema”A template can carry the schema of the data it binds to, so a template author can find out which fields are available instead of reading the calling application’s source.
The schema is stored twice on purpose:
- the identity (
ReportSchemaId,ReportSchemaVersion, and optionallyReportSchemaTitleandReportSchemaUri) goes into the custom document properties, visible under File -> Info -> Properties -> Advanced Properties -> Custom; - the JSON Schema document goes into a custom XML part, so the template stays self-describing when it is passed around without the application that produced it.
Attaching a schema
Section titled “Attaching a schema”Generate the schema from the declared type the application passes to Fill, and attach it once:
var schema = ReportSchema.FromType<SalesReport>( id: "iseag.sales-report", version: "2.1.0", title: "Sales Report");
using var template = XlsxTemplate.New("Templates/report.xlsx");template.AttachSchema(schema);template.Save("Templates/report.xlsx");Attaching replaces any schema already stored. A hand-written schema works too, via
ReportSchema.FromJson, FromStream or FromFile.
Generation targets declared types. An anonymous object produces unstable member names and is not a useful generation source, though anonymous data still validates fine against a schema generated from a real type.
Reading the schema back
Section titled “Reading the schema back”This is the authoring loop until dedicated tooling exists: extract the JSON Schema next to the template and write bindings against the fields it lists.
using var template = XlsxTemplate.New("Templates/report.xlsx");template.ReadSchema()?.SaveDocument("sales-report.schema.json");ReadSchema() returns null when the template carries no schema.
Validation
Section titled “Validation”Validation is opt-in by attachment: a template with no schema behaves exactly as before,
whatever the mode says. When a schema is attached, the data handed to Fill is validated against it
before anything is filled.
using var template = XlsxTemplate.New("Templates/report.xlsx", new XlsxTemplateOptions{ SchemaValidation = SchemaValidationMode.Warn // Off | Warn | Throw});
using var filled = template.Fill(data);
if (filled.SchemaValidation.HasErrors){ foreach (var error in filled.SchemaValidation.Errors) { Console.WriteLine($"{error.InstanceLocation}: {error.Message}"); }}| Mode | Behaviour |
|---|---|
Off |
Never validate, even with a schema attached |
Warn (default) |
Log a warning per mismatch and continue filling |
Throw |
Throw ReportSchemaValidationException, which carries the full result |
A warning names the schema id and version, the JSON Pointer to the offending value, and the reason:
Schema mismatch at /OrderCount: data does not match iseag.sales-report version 2.1.0: Value is "string" but should be "integer"What is checked is the data, against the schema. Binding tags are arbitrary expressions rather than paths, so they are not statically checked against the schema.
For validation, .NET enum values are serialized as their names, matching generated schemas. Data supplied as JSON keeps its existing representation.
Generated reports
Section titled “Generated reports”A filled report keeps the schema, which makes it traceable to the model it came from. Strip it before distributing a report outside your trust boundary, since a schema describes internal structure and field names:
using var filled = template.Fill(data);filled.RemoveSchema();filled.Save("Output/report.xlsx");Notes and limits
Section titled “Notes and limits”- The
ReportSchemaUriis metadata. The library never fetches it, and never resolves external or remote$refvalues; resolving a schema against a registry is the application’s job. - The version is stored and reported verbatim. The library never parses, compares or ranges it -
compare
ReadSchema()?.Versionyourself if you need drift detection. - An unreadable or oversized stored schema degrades to “no schema” with a warning rather than failing the fill.
- Word and Excel list custom XML parts in the XML Mapping pane, so the schema store is visible there alongside genuine data-bound stores.
- Validation serialises the fill data with
System.Text.Jsonreflection. An application that disables reflection-based serialization (trimming, AOT, orJsonSerializerIsReflectionEnabledByDefault=false) still fills normally, but every fill reports a single “could not be represented as JSON for validation” warning instead of real results; run such applications withSchemaValidationMode.Off.
Security
Section titled “Security”Templates are trusted application assets: notes contain expressions evaluated by DynamicExpresso, so never process untrusted workbooks. The engine introduces no macros, external links, or network access.