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 generated workbook objects

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, and ResolverCount manage typed resolvers, and BeginRun snapshots tables and providers into an isolated per-run session so separate runs never share provider results

Controlled query providers

IXLSReportQueryExecutor.ExecuteReadOnly keeps query execution host-owned and accepts 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, while 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 add the numeric cells of a column and ignore text, blanks and logicals, as the spreadsheet SUM and AVERAGE do; Sum answers 0 when the column holds no number and Average answers null. Min and Max compare the kind of value the column’s first non-blank cell holds and ignore the other kind, so a stray label does not become the maximum of a number 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, canceled, 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 when 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 collapse

FixedBand makes row bands overwrite the rows below the template instead of 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 are 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 canceled run removes generated conversations while 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 case-insensitively and registering the same pair again replaces it

TXLSCompiledReportBand.RunRelated(master, detail) then expands the pair through the registered key columns, which is the same expansion RunBidirectional performs with its key lists spelled out at each call; the band resolves the tables from 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 while 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, records the source BandInputRow and actual output coordinates, and continues later targets and rows, while 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 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}} form a conditional block in one column: the first branch whose condition holds keeps its rows, every other branch is deleted with the directive rows themselves, and the survivors keep their own cell formatting. Blocks cannot nest, and a block without 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 cleared and the target cell’s own text becomes the display unless one is given; 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 serialization, 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 how many it handled through AppliedCount — and CreateEncrypted opens an encrypted template with its password and compiles it while keeping the workbook reachable through the Workbook property

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

TXLSReportObjectValues flattens an object graph into the name/value strings a template takes: every published property becomes its own name, a nested object contributes its properties under 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]) turns the items of a master object’s collection property into a report table: one row per item, 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 while 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, so a report can be bound to a document object without the caller copying properties by hand

Placeholder expressions

A cell written as {{=expression}} is evaluated once per target; the result keeps its type, so a number stays numeric and a string starting 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, comparing the way every report comparison does; either answers an odd trailing argument as the default and an empty string when nothing matches and no default was given

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, while 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 itself 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, 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, while 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 preserving 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 are validated before binding

TXLSXImage.OffsetXEMU and OffsetYEMU retain 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 sanitized 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 stop 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, serialization, security, and structural failures remain fatal

RunToStream, RunToFile, and RunToEncryptedFile stage serialization inside the same run and data-session lifetime, then publish once; any fatal, canceled, serialization, 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, while 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 with 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 unchanged

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, while TXLSReportLifecycleOutcome distinguishes entered, completed, canceled, and failed callbacks

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

All lifecycle events share the handler type TXLSReportLifecycleEvent (Sender, the TXLSReportLifecycleContext, and a var Cancel flag); setting Cancel in 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 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 selects 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, while 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 remain 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 issue count before releasing the runner

See also