HotXLS Docs

Compiled reporting API

Small Business edition: The compiled report engine (lxReport) ships with HotXLS Small Business (HotXLS-SME / HotXLS-DCU-SME) and Enterprise (HotXLS-ENT / HotXLS-DCU-ENT), in the HotXLSSB runtime package for RAD Studio and HotXLSLazSB.lpk for Lazarus (demo: Demo\Delphi\CompiledReports); the trial build includes it under the usual trial limits

The lxReport unit compiles placeholders and structural report bands once, then applies caller-owned data through bounded cursors without rescanning the workbook objects it generates

Table and cursor contracts

IXLSReportCursorMoveNext, RowIndex, and Values expose one forward-only row at a time
IXLSReportTableName, ColumnCount, ColumnNames, and CreateCursor define a reusable tabular source
IXLSReportRandomAccessTableRowCount and two-dimensional Values add indexed access used by joins and relation indexes
IXLSReportTableProviderTryGetTable resolves a named table lazily
TXLSReportMemoryTableAddRow, ColumnIndexOf, CreateCursor, ColumnCount, ColumnNames, and RowCount provide an owned in-memory implementation
TXLSReportDataContextRegisterTable, AddProvider, TryGetTable, RequireTable, ClearLoadedTables, and LoadedTableCount coordinate eager and lazy sources; RegisterResolver, HasResolver, RemoveResolver, ClearResolvers, ResolverCount , and BeginRun coordinate eager and lazy sources

Controlled query providers

IXLSReportQueryExecutor.ExecuteReadOnly keeps query execution host-owned and takes only definitions registered by application code

TXLSReportQueryParameter, TXLSReportQueryParameters, and TXLSReportQueryDefinition expose Name, CommandText, TimeoutMS, ParameterCount, Parameters, SetParameter, and ClearParameters

TXLSReportQueryProvider uses RegisterQuery, RemoveQuery, Clear, and TryGetTable, with Count, Definitions, and MaximumTimeoutMS exposing the whitelist and timeout ceiling

Per-run data sessions

IXLSReportDataSession is the isolated lazy cache behind one report run: DeclareRequest registers a TXLSReportDataRequest (kind TXLSReportDataRequestKind: xrdrkNamed or xrdrkUser) whose TXLSReportDataSource (kind TXLSReportDataSourceKind: unspecified, cell, range band, table band, or expression) and TXLSReportDataParameter list describe the source and its values, and whose RunControl is the host's IXLSReportRunControl cancellation handle; HasResolver tests a provider key, TryGetTable and RequireTable read cached aliases, TryResolveTable and RequireResolvedTable resolve on demand into a TXLSReportDataResolveResult (status TXLSReportDataResolveStatus: xrdrsUnhandled, xrdrsResolved, xrdrsNotFound, or xrdrsDataError), and TryGetState reports a TXLSReportDataSessionState of loading, resolved, not found, or data error, whilst CachedAliasCount and ResolvedAliasCount expose session size

IXLSReportDataView.TryGetValue looks up one named value without raising, complementing the indexed Count, Names, and Values accessors

Relations and lazy table combinators

TXLSReportRowIndexes and TXLSReportRelationIndex retain child row numbers in compound-key buckets; use FindChildRows or CreateChildCursor and inspect BucketCount or IndexedRowCount

Sum and Average sum the numeric cells in a column and skip text, blanks and logicals, just as the spreadsheet SUM and AVERAGE do; Sum answers 0 when the column holds no number and Average answers null. Min and Max look at the kind of value held by the column’s first non-blank cell and ignore values of the other kind, so a stray label never becomes the maximum of a numeric column; First and Last take the first and last non-blank value of any kind

TXLSReportAggregateKind, TXLSReportAggregate, and TXLSReportJoinKind configure TXLSReportTableFactory, whose row filters compare through TXLSReportFilterOperator (xrfoEqual, xrfoNotEqual, xrfoGreater, xrfoGreaterEqual, xrfoLess, xrfoLessEqual, xrfoContains, xrfoStartsWith, xrfoEndsWith)

Aggregate definitionsCountAggregate, MinAggregate, MaxAggregate, SumAggregate, AverageAggregate, FirstAggregate, LastAggregate, and Aggregate
Projection and reductionTop, Columns, NRows, and the one-column reducers Min, Max, Sum, Average, First, and Last
CompositionUnion, Join, and Split return lazy views without copying complete intermediate row payloads

Named and explicit range bands

TXLSReportBandKind selects row, column, or cross-tab expansion, and TXLSReportBandState reports ready, running, completed, completed-with-errors, cancelled, or failed lifecycle state

TXLSCompiledReportBand accepts an exact-scope defined name or CreateForRange, then expands through the Run overloads; DefinedName, ScopeSheetIndex, Kind, Sheet, SheetIndex, FirstRow, FirstCol, LastRow, LastCol, TargetCount, and State expose the compiled plan

EmptyBandPolicy (type TXLSEmptyBandPolicy) controls what the band does with its template rows once the data set is empty — xreKeepTemplate leaves the rows untouched, xreClearTemplate clears the band cells including placeholders, and xreDeleteTemplate deletes the template rows — and DeleteLastRow removes the final BandHeight rows of the expanded block after its copies land, so trailing X-range separator rows close up

FixedBand makes row bands overwrite the rows below the template rather than inserting new ones, which keeps surrounding content at a fixed position

The reserved placeholders {{$enumrowstart}}, {{$enumrowend}}, {{$enumcolstart}}, and {{$enumcolend}} resolve to the first and last row or column of the copy being written, so =SUM(B{{$enumrowstart}}:B{{$enumrowend}}) in a band cell becomes a live formula over that copy’s own rows once the copy has been cloned, in a row, column, cross-tab, or fixed band. They are not looked up in the data set — a band whose data has no column of that name still runs — and a target outside any band resolves them to its own cell

Row and column range bands clone threaded-comment conversations when every root and reply belongs to the template range; text and display-name placeholders are evaluated for each record, copied comments receive new identifiers and remapped parent identifiers, and existing workbook person records get reused

Compilation rejects conversations split across the template boundary, missing parents, duplicate identifiers, and invalid cell anchors before expansion; anchor overflow is checked before worksheet mutation, and a failed or cancelled run takes away generated conversations whilst restoring the template state

TXLSReportDataContext.AddRelationship(master, detail, masterKeys, detailKeys) declares a master/detail pair once by table name, with ClearRelationships, RelationshipCount and HasRelationship to manage the registry; names are compared without regard to case, and registering an identical pair again replaces the earlier entry

TXLSCompiledReportBand.RunRelated(master, detail) then expands the pair using the registered key columns, an expansion identical to the one RunBidirectional carries out with its key lists written out on each call; the band resolves the tables through its DataContext and refuses a missing context, an unknown table or an undeclared pair by name

TXLSCompiledTableReportBand.Run expands one Excel table data-template row whilst preserving table metadata; inspect TableName, Sheet, SheetIndex, ExcelTable, TemplateRow, and State, and configure the same V2 image properties exposed by range bands

Range and Excel-table bands share ErrorMode, StrictDataAccess, RuntimeLimits, and immutable LastResult snapshots; xremWriteAndContinue writes only explicit recoverable cell failures as literal diagnostics, logs the source BandInputRow and actual output coordinates, and continues later targets and rows, whilst structural, cancellation, resource-limit, callback, and rollback failures remain fatal

TXLSCompiledSheetReportBand.Run creates per-record sheets using NameColumn, NamePrefix, and DeleteTemplateAfterRun; TXLSCompiledOverflowReportBand.Run creates continuation sheets using NamePrefix and DeleteTemplateAfterRun

Whole-workbook templates

TXLSReportTemplateTarget and TXLSReportTemplateTargets select cells, comments, hyperlinks, shapes, headers and footers, sheet names, defined names, and workbook document properties

TXLSCompiledReportTemplate.Compile captures targets and expressions, Analyze returns addressed TXLSReportIssues, the Run overloads apply values, and WriteDiagnostics writes issues to a worksheet; TargetAreas, TargetCount, and UserTableCount describe the compiled surface and registered user tables

ProcessStructuralDirectives (default True) makes a template Run execute the structural {{#delete}}, {{#format}} and {{#merge}} directives after value targets are applied, where {{#merge B2:C2}} joins the named rectangle and clears the directive cell. {{#if expression}}, {{#elseif expression}}, {{#else}} and {{#endif}} make a conditional block within one column: the first branch whose condition is true retains its rows, all other branches are removed along with their directive rows, and the surviving rows keep their cell formatting. Blocks may not nest, and a block missing its {{#endif}} is refused by name. TXLSReportDirectiveProcessor.Execute takes the run values so a condition can read them; a template Run passes them automatically, and {{#swapseries Title}} finds the chart by its title and switches it from columns to rows — one series per data row, the header row as the categories and each row’s category label as its series name — refusing a multi-column value range, series with different row spans or a missing header row by name; {{#hyperlink}} links the directive cell when it names only a URL and an optional label ({{#hyperlink https://example.com/a Click}}), or a named cell when the first token is a cell reference ({{#hyperlink B4 https://example.com/b}}), in which case the directive cell is emptied and the target cell’s own text supplies the display unless one is provided; TXLSCompiledReportTemplate.ApplyStructuralDirectives exposes the same pass for a host that applies targets itself — the compiled report runner calls it after its targets and before autofit and serialisation, so a conditional block, a merge or a row deletion shapes the workbook the output actually writes — the TXLSReportDirectiveProcessor behind it parses the ranges, applies them and reports the number handled through AppliedCount — and CreateEncrypted opens an encrypted template with its password and compiles it whilst keeping the workbook reachable through the Workbook property

TXLSReportIssueKind, TXLSReportIssue, and TXLSReportIssues identify malformed, missing, invalid, unknown, or cyclic placeholder content with target plus cell coordinates

TXLSReportObjectValues flattens an object graph into the name/value strings consumed by a template: each published property gets its own name, while a nested object contributes its properties beneath a dotted path (Customer.Name), and dates are written in ISO form rather than the machine’s locale. Add takes a prefix so a graph can be nested under a name, Count and Values expose the result, DepthLimit bounds a cyclic graph, and a TStrings, TCollection or TComponent property is left to the table side instead of being flattened

TXLSReportObjectTables.ChildrenOf(master [, collection]) converts the items of a master object’s collection property into a report table: a row for every item, with the item’s published properties as columns. A TCollection yields its columns even when empty because its element class is known; a TList needs one item to reveal its element type. The table feeds a detail band whilst TXLSReportObjectValues feeds the same run’s values

TXLSCompiledReportTemplate.Run takes either a TStrings or an object: the object overload flattens the graph with TXLSReportObjectValues and renders, letting a report bind to a document object without the caller copying properties by hand

Placeholder expressions

A cell written as {{=expression}} is evaluated once for every target; the result preserves its type, so a number remains numeric and a string beginning with = becomes a live formula. The vocabulary is if(condition, then, else), ifs(c1, v1, c2, v2, ..., [default]) and switch(value, match, result, match, result, ..., [default]) for branching, and, or, not, eq, ne, gt, ge, lt, le for comparisons, add, sub, mul, div for arithmetic, and lookup, dbvalue, dbcount, concat, upper, lower, trim, tonumber, formula, regexmatch, regexreplace, ref, row, column, sheet and cellref for the rest

ifs answers the first value whose condition is true and switch the first result whose match equals its first argument, compared the same way as every report comparison; either form treats an odd trailing argument as the default and yields an empty string when nothing matches and no default was supplied

Includes, images, and formatting

IXLSReportIncludeResolver.Resolve supplies named fragments and its Immutable flag permits safe reuse; TXLSReportIncludeLibrary provides Add, Remove, Clear, Freeze, Resolve, Count, and Immutable

IXLSReportImageProvider.TryGetImage returns a TXLSReportImageValue configured by TXLSReportImageFit; TXLSReportMissingImagePolicy controls missing resources, whilst TXLSReportImageBinder.Apply, ApplyTarget, MissingPolicy, and ClearDirectiveCell update exact image directives

TXLSReportImageBinder.ApplyTargetV2 binds one directive cell through the V2 provider contract and forwards a TXLSReportTransformImageEvent that can rewrite the resolved payload before it lands; the resolved placeholder is a TXLSReportEvaluatedTarget whose TXLSReportEvaluatedTargetKind distinguishes xretNone, xretText, xretValue, and xretFormula; IXLSReportImageCancellation.IsCancellationRequested lets long-running providers observe a cooperative cancel

IXLSReportImageDataProviderV2.GetImage receives TXLSReportImageRequest with stable worksheet identity, compiled target, band and table names, logical and cursor rows, a read-only current-row view, directive and anchor cells, target dimensions and offsets in EMU units, and IXLSReportImageCancellation

TXLSReportImageResult carries a TXLSReportImagePayload whose Kind (TXLSReportImagePayloadKind) selects xripMissing, bytes, or a stream, with the stream's lifetime declared by TXLSReportImageStreamOwnership: xrisoBorrowed streams remain caller-owned and restore their position when seekable, whilst xrisoTransferred streams are released exactly once; optional SourceWidth, SourceHeight, SourceDpiX, and SourceDpiY assert or override physical source geometry

xrifNatural uses the source physical size, xrifContain scales and centres within the target box, xrifCover fills the box with symmetric source cropping, and xrifStretch fills it without keeping the aspect ratio; PNG, JPEG, GIF, BMP, EMF, and WMF geometry is read from bounded headers without decoding pixels

OnTransformImage runs after provider data is snapshotted and before worksheet mutation; MaximumImageBytes defaults to 64 MiB and payload signatures, geometry headers, dimension and DPI pairs, raster side and pixel limits, anchors, and grid coordinates get validated before binding

TXLSXImage.OffsetXEMU and OffsetYEMU keep an image's position inside its cell or absolute anchor through XLSX and ODS round trips

TXLSReportDynamicFormat and TXLSReportFormatEvent let a runner apply number formats, row heights, and column widths per target

Reusable execution

TXLSReportRunPhase, TXLSReportRunState, TXLSReportRunProgress, and TXLSReportRunProgressEvent describe progress and cancellation boundaries

TXLSCompiledReportRunner exposes Run, RunToStream, RunToFile, RunToEncryptedFile, and Cancel, with ReportTemplate, State, Progress, OnProgress, and OnFormat controlling reusable execution; failed validation raises EXLSReportData before deterministic writes

ErrorMode (type TXLSReportErrorMode) defaults to xremStop; xremWriteAndContinue handles only explicit EXLSReportRecoverableData failures and resolver DataError results, records ordered immutable issues in LastResult (an IXLSReportRunResult exposing State, AppliedCount, IssueCount, indexed Issues, and the FailureClassName / FailureMessage of a fatal failure) whose TXLSReportRuntimeIssue snapshots expose their Category (a TXLSReportRuntimeIssueCategory: xrricDataAccess, xrricProvider, or xrricExpression) and report TargetIndex, SheetName, Col, and whether the issue was already WasWritten into the output, and finishes as xrrsCompletedWithErrors

TXLSReportRuntimeLimits.Defaults allows 100,000 retained issues, 512 characters per sanitised message, and 16 MiB of issue memory; assign a positive custom RuntimeLimits record before a run, and leave RuntimeDiagnosticsSheetName empty unless one structured diagnostics worksheet is required

Recoverable cell values and formulas become literal [Report error CODE] message text, safe non-cell targets retain their original value, and an optional diagnostics worksheet marks those structured issues as written; worksheet-name and defined-name-formula failures always halt because they can change workbook structure

Resolver-declared data errors, expression division by zero, and invalid regular expressions use stable provider or expression categories; thrown resolver exceptions and all callback, cancellation, resource-limit, rollback, serialisation, security, and structural failures remain fatal

RunToStream, RunToFile, and RunToEncryptedFile stage serialisation inside the same run and data-session lifetime, then publish once; any fatal, cancelled, serialisation, partial stream-write, or destination-replacement failure preserves the complete prior destination and releases temporary storage before returning

A nonempty output stream must be readable, writable, sizable, and seekable so rollback can restore its original bytes, size, and position; snapshots up to 8 MiB remain in memory and larger snapshots use managed temporary storage, whilst a successful commit leaves the stream positioned at zero

Unencrypted output uses the generated workbook's source format, so an ODS template produces an ODS stream or file carrying its required package metadata; encrypted output continues to use the encrypted Office container

ImageProvider preserves the original compatibility contract; ImageProviderV2, OnTransformImage, MaximumImageBytes, MissingImagePolicy, and ClearImageDirectiveCell let a runner, generator, range band, or Excel-table band consume precompiled {{#image Key}} targets directly; omitting both providers leaves those directive cells untouched

AutofitMode (type TXLSReportAutofitMode) selects a whole-sheet autofit (xramNone, xramRows, xramColumns, or xramBoth) applied once after all targets run, and AutofitAdjustment is an extra headroom factor (1.0 = none, 1.1 = 10% taller rows)

Generation lifecycle and template sources

TXLSReportLifecyclePhase identifies template-read, workbook-generation, and worksheet-generation boundaries, whilst TXLSReportLifecycleOutcome distinguishes entered, completed, cancelled, and failed callbacks

TXLSReportLifecycleContext supplies the active workbook and worksheet, stable worksheet identity, original and current coordinates, plus a read-only IXLSReportDataView, target count, and first-failure details; every entered before event receives a paired after event even when generation is cancelled or fails

All the lifecycle events share one handler type, TXLSReportLifecycleEvent (Sender, the TXLSReportLifecycleContext, and a var Cancel flag); setting Cancel within a before event stops the run, and the paired after event is still delivered

TXLSCompiledReportRunner.BeforeGenerateWorkbook, AfterGenerateWorkbook, BeforeGenerateSheet, and AfterGenerateSheet observe a frozen set of original worksheets; callback-driven structure changes trigger a compilation refresh without adding newly created sheets to the current run

TXLSReportGenerator accepts a workbook, file name, caller-owned stream, or encrypted file and adds BeforeReadTemplate plus AfterReadTemplate to the generation events; TXLSReportModificationMode picks compatible in-place mutation or isolated atomic-clone generation. Read-only SourceKind (type TXLSReportTemplateSourceKind: xrtsWorkbook, xrtsFile, xrtsStream, or xrtsEncryptedFile) and TemplateWorkbook report the configured template source, whilst ModificationMode and IncludeResolver are settable before a run

File and stream templates default to xrmAtomicClone; seekable input streams restore their original position, forward-only streams are consumed in bounded blocks, caller streams stay open, and output streams or files are replaced only after successful completion

Planning, checking, and migration

TXLSReportPaginationPlanner provides KeepTogether, SplitRows, MergeSimilar, and BalanceColumns plans for fixed-footers and balanced output

TXLSReportTemplateChecker provides Check, CheckBand, and CheckTableBand; TXLSReportTemplateMigrator provides MigrateText and MigrateWorkbook for supported legacy placeholder forms

Delphi example

Context := TXLSReportDataContext.Create;
Table := TXLSReportMemoryTable.Create('Orders', ['Customer', 'Amount']);
Table.AddRow(['A. Datum', 1200]);
Context.RegisterTable(Table);
Template := TXLSCompiledReportTemplate.Create(Workbook);
Template.DataContext := Context;
Runner := TXLSCompiledReportRunner.Create(Template);
try
  Runner.StrictDataAccess := True;
  Runner.ErrorMode := xremWriteAndContinue;
  Runner.RuntimeDiagnosticsSheetName := 'Report Diagnostics';
  Runner.RunToFile(Values, OutputFileName);
  RunResult := Runner.LastResult;
finally
  Runner.Free;
  Template.Free;
  Context.Free;
end;

C++Builder example

Lxreport::TXLSReportMemoryTable *tableObject =
  new Lxreport::TXLSReportMemoryTable(L"Orders", columns, 1);
Lxreport::_di_IXLSReportTable table;
tableObject->GetInterface(table);
tableObject->AddRow(row, 1);
context->RegisterTable(table);

Lxreport::TXLSCompiledReportTemplate *reportTemplate =
  new Lxreport::TXLSCompiledReportTemplate(workbook);
reportTemplate->DataContext = context;
Lxreport::TXLSCompiledReportRunner *runner =
  new Lxreport::TXLSCompiledReportRunner(reportTemplate);
runner->StrictDataAccess = true;
runner->ErrorMode = Lxreport::xremWriteAndContinue;
runner->RuntimeDiagnosticsSheetName = L"Report Diagnostics";
runner->RunToFile(values, outputFileName);
Lxreport::_di_IXLSReportRunResult runResult = runner->LastResult;

The Delphi FeatureShowcase and C++Builder XlsxFeatureGallery contain complete runnable versions that verify the completed-with-errors state and the issue count before releasing the runner

See also