Additional library API members
This page completes the reference for public types that support the primary workbook, worksheet, rendering, import, diagnostics, and viewer APIs but do not require a separate task-oriented guide
Filtering and conditional formatting
TXLSAutofilter | Add, AddAutofilterData, AssignFrom, Clear, and ParseAutofilterData edit or import the filter definition; SetRangeBounds(ARow1, ACol1, ARow2, ACol2) restores 1-based inclusive bounds without removing loaded criteria or dropdown shapes, and ignores nonpositive or reversed bounds and a column count that differs from the loaded fields; Defined, FirstRow, FirstCol, LastCol, LastRow, and FieldCount expose its active bounds and filtered-column count |
TXLSAutofilterItem | Shape exposes the filter-button drawing associated with the item, and the loaded filter criterion is available as a TXLSAutofilterDOPER operand record — DataType selects the operand form and grbitSgn carries the sign and flag bits — for inspection or round-trip editing |
TXLSDataBarSpec | AxisColor, AxisIsThemeColor, AxisThemeColorId, AxisThemeColorTint, AxisPosition and ClearAxisThemeColor control the axis, with AxisPosition selecting automatic (0), middle (1) or no axis (2), defaulting to no axis; Direction, GradientFill, NegativeBarBorderColorSameAsPositive, NegativeBarColor, NegativeBarColorSameAsPositive, and NegativeBorderColor control bar appearance, BorderColor colours the positive-bar border when Border is set, and AutoMin plus AutoMax select automatic minimum and maximum endpoints; IsIndexedColor, IndexedColorIndex, and ClearIndexedColor manage the palette-index bar color |
TXLSIconSetSpec | ThresholdEqualsInclude selects inclusive or exclusive comparison for each icon threshold |
TXLSCfValue | IsIndexedColor and IndexedColorIndex report a threshold color stored as a legacy palette index, ClearIndexedColor removes that form again, and theme or literal colors remain available through the existing accessors |
TXLSCfValue, TXLSDataBarSpec, TXLSColorScaleSpec, TXLSIconSetSpec, and TXLSDxfStyle accept AttachWriteGuardOwner, linking the rule object to its owning workbook so edits acquire a write guard automatically; the owner implements TXLSCondFormatWriteGuardOwner, whose single AcquireWriteGuard method hands the rule the workbook's write guard. TXLSDxfStyle adds FontColorIndex with FontColorIsIndexed plus the FillFgColorIndex / FillFgColorIsIndexed and FillBgColorIndex / FillBgColorIsIndexed pairs for palette-index rule colors, and the differential-font overrides FontName, FontSize, and FontScheme (empty string, a point size, or a theme font slot such as major / minor) alongside the existing bold, italic, underline, and color members; each assignment acquires the write guard and marks the rule dirty for re-emission; differential fills can also carry an x14 gradient through FillGradientKind, FillGradientDegree, FillGradientLeft, FillGradientRight, FillGradientTop, FillGradientBottom, FillGradientStopCount and FillGradientStops, assigned with SetFillGradient and detached on request through CopyFillGradientStops
TXLSConnections, TXLSDataTables, and TXLSQueryTables expose OnAcquireWriteGuard (type TXLSConnectionAcquireWriteGuard, TXLSDataTableAcquireWriteGuard, and TXLSQueryTableAcquireWriteGuard), the hook their edit paths use to obtain the owning workbook's IXLSWorkbookWriteGuard before mutating and to advance the workbook generation afterwards; the guard records StartGeneration, and Complete marks the write finished so dependent caches can rebuild
Preserved data connections carry a typed description: TXLSConnectionKind (xlckUnknown, xlckOdbc, xlckDao, xlckFile, xlckWeb, xlckOleDb, xlckText, xlckAdo) classifies the connection, TXLSConnectionCredentials (xlccIntegrated, xlccNone, xlccStored, xlccPrompt) records its authentication mode, and each connection parameter value is tagged with TXLSConnectionParameterValueKind (xlcpvNone, xlcpvBoolean, xlcpvDouble, xlcpvInteger, xlcpvString, xlcpvCell). What-if data tables report their stored definition kind through TXLSDataTableKind
What-if data tables and pivot grouping
TXLSDataTable | Assign, ContainsCell, and IsRoot copy and inspect a table; Kind, FirstRow, FirstCol, LastCol, LastRow, AlwaysCalculate, ColumnInputCol, ColumnInputRow, ColumnInputDeleted, RowInputCol, RowInputRow, and RowInputDeleted expose the stored calculation definition |
TXLSDataTables | Add, AddExisting, Delete, Clear, Assign, AdjustForShift, and Offset maintain the collection; FindByCell and FindRoot locate the table containing or rooted at a given cell; Count, Items, and OnChange expose collection state |
TXLSPivotCacheField | GroupBaseField and GroupParentField expose the relationships between a grouped field and its source or parent field |
Icon-set thresholds can be rendered or validated programmatically: XLSCfIconSetCount reports how many icons a TXLSIconSetType defines, and XLSBuildCfIconGeometry fills a TXLSCfIconGeometry with the primitives (TXLSCfIconPrimitive, kind TXLSCfIconPrimitiveKind: cfipPolygon, cfipEllipse, cfipRect, cfipLine) and points (TXLSCfIconPoint) that draw one icon, so custom renderers match Excel's built-in icon shapes. TXLSCfIconGeometry reports PrimitiveCount and the Primitives array; each primitive reports Kind, HasFill, FillColor, HasStroke, StrokeColor, StrokeWidth, PointCount, the Points array, and the X1 / Y1 / X2 / Y2 bounds used by rectangle and ellipse/line primitives; each point reports X and Y. Coordinates are normalized to the icon box, and colors use the library's BGR LongWord convention
Diagnostics, formula tracing, and validation
TXLSDiagnostic | Code, NativeCode, Message, Severity, ExceptionClass, PartName, RecordId, SheetIndex, SheetName, and StreamOffset identify one parser, writer, or package diagnostic |
TXLSDiagnostics | Add appends a diagnostic, Clear resets the collection, and Count plus Items enumerate its entries |
TXLSDiagnosticSeverity and TXLSDiagnosticOperation | TXLSDiagnosticSeverity (xlsDiagnosticInfo, xlsDiagnosticWarning, xlsDiagnosticError, xlsDiagnosticFatal) classifies one diagnostic and TXLSDiagnosticOperation (xlsOperationNone, xlsOperationOpen, xlsOperationSave, xlsOperationCalculate, xlsOperationExport) names the phase that produced it; OnDiagnostic handlers read both from the delivered TXLSDiagnostic |
TXLSFormulaDebugSession | CurrentStep, DependencyCount, NodeCount, and StepCount expose the current debugger snapshot and its trace sizes |
TXLSFormulaTracer | StepCount reports the number of recorded evaluation steps |
TXLSImportCheck | AddRule, AddUniqueRule, and AddCrossColumnRule configure column predicates, composite uniqueness, and typed comparisons; Check returns structured violations from stored worksheet values and formula caches without recalculation or packed-cell materialization; HeaderRow, FirstRow, LastRow, OnVerifyCell, ViolationCount, and Violation expose bounds, callbacks, and results; Annotate and KeepOnlyViolations are explicit correction-workbook operations; see import validation schemas for types, bounds, date systems, tuple identity, and failure behavior |
Import validation schemas
Small Business edition: Import validation (lxImportCheck) ships with HotXLS Small Business and Enterprise (and their DCU editions), in the HotXLSSB runtime package for RAD Studio and HotXLSLazSB.lpk for Lazarus; the trial build includes it under the usual trial limits
TXLSImportCheck from lxImportCheck validates a TXLSXWorksheet against application-owned rules; it examines stored scalar values and stored formula results, with one-based worksheet coordinates and no implicit text-to-number, text-to-date, or text-to-Boolean conversion
Validator := TXLSImportCheck.Create;
try
Validator.HeaderRow := 1;
Rule := Validator.AddRule(2);
Rule.Name := 'quantity';
Rule.Flags := [irRequired, irValueType, irValueRange];
Rule.ValueKind := ivkInteger;
Rule.MinimumValue := 1;
Rule.MaximumValue := 1000;
Validator.AddUniqueRule([1, 3]).Name := 'account-and-region';
Validator.AddCrossColumnRule(4, 5, icLessOrEqual).Name := 'start-before-end';
FailureCount := Validator.Check(Sheet);
if FailureCount > 0 then
Validator.Annotate(Sheet, 'Import validator');
finally
Validator.Free;
end;
HeaderRow > 0 starts checking at the next row and takes precedence over FirstRow; otherwise FirstRow defaults to 1; LastRow = 0 uses the worksheet's last used row, while a positive LastRow can include absent cells without creating them; columns must be within 1 through 16,384 and active data-row bounds within 1 through 1,048,576
Column rules and explicit types
TlxImportColumnRule | Column, Flags, Name, Title, MinLength, MaxLength, Pattern, ValueKind, and DateSerialMode configure one column; MinimumValue, MaximumValue, HasMinimum, HasMaximum, MinimumInclusive, and MaximumInclusive configure bounds; Validate checks schema configuration and PreparePattern prepares the regex; the two Check overloads return a Boolean with an error message and optionally a TlxImportViolationKind |
TlxImportRuleFlags | irRequired, irTextLength, irPattern, irUnique, and irCallback retain their existing checks; irValueType enables ValueKind and irValueRange enables the configured bounds; a column with no flags is not checked |
TlxImportValueKind | ivkAny accepts supported finite scalar values, ivkNumber accepts finite numeric Variants, ivkInteger additionally requires an integral value, ivkDate accepts date Variants or explicitly enabled Excel serials, ivkBoolean requires a Boolean Variant, and ivkText requires a string Variant |
TlxImportDateSerialMode | idsNone is the default and keeps numeric values distinct from dates; idsExcel1900 and idsExcel1904 explicitly interpret numeric values for a column using irValueType with ValueKind = ivkDate |
AddRule(Column) replaces and frees any previous rule for that column; the per-value type, range, length, and pattern predicates skip missing values, nulls, and empty strings, while irRequired reports them; uniqueness retains the distinct policies described below; nonempty whitespace remains a value; a number does not qualify as a Boolean, a date does not qualify as an ordinary number, and a numeric-looking string remains text
Assigning MinimumValue or MaximumValue enables that bound; either HasMinimum or HasMaximum can disable it again; both inclusivity switches default to True; bounds must be finite typed numbers or dates, and two bounds must be comparable and describe a nonempty interval; reversed, missing, incompatible, or empty bounds raise before worksheet validation begins
Number bounds compare numeric values and date bounds compare dates; integer-to-integer comparisons preserve all Int64 and UInt64 bits; values of an incompatible category fail the range check; text length and regex predicates continue to inspect the scalar's text representation, and regex checks retain the existing IsMatch behavior, so use anchors such as ^...$ when the complete text must match; an invalid regex disables its pattern check for compatibility
Date-formatted Excel values
A cell imported from Excel can contain a numeric serial even when its number format displays a date; choose a serial mode explicitly when that is the accepted import schema; the mode affects validation only and never changes the stored cell value
Rule := Validator.AddRule(4); Rule.Flags := [irRequired, irValueType, irValueRange]; Rule.ValueKind := ivkDate; if Sheet.Workbook.Date1904 then Rule.DateSerialMode := idsExcel1904 else Rule.DateSerialMode := idsExcel1900; Rule.MinimumValue := VarFromDateTime(EncodeDate(2026, 1, 1)); Rule.MaximumValue := VarFromDateTime(EncodeDate(2026, 12, 31));
VarFromDateTime is declared in Variants and EncodeDate in SysUtils; numeric serials must be nonnegative and resolve before January 1, 10000; fractional serials retain their time-of-day; the 1900 system rejects every serial from 60 inclusive through 61 exclusive because that interval denotes the fictitious leap day; the 1904 system maps serial zero to January 1, 1904
Date bounds include time-of-day, so a maximum set to midnight on December 31 excludes later times on that day; use an exclusive upper bound at January 1 of the following year when the entire final day must be accepted; textual dates such as 10/08/2026 remain text regardless of the configured serial mode
Composite uniqueness and cross-column comparisons
AddUniqueRule(const AColumns: array of Integer): TlxImportUniqueRule | Adds an independent tuple constraint over an ordered, nonempty list of distinct columns; Name identifies the rule, Title prefixes its message, ColumnCount and zero-based Columns[Index] expose its members, and SkipIncompleteRows defaults to True |
AddCrossColumnRule(ALeftColumn, ARightColumn: Integer; AComparison: TlxImportComparison): TlxImportCrossColumnRule | Adds a same-row comparison with read-only LeftColumn and RightColumn, an editable Comparison, Name, Title, and SkipBlankValues, which defaults to True |
TlxImportComparison | icEqual, icNotEqual, icLess, icLessOrEqual, icGreater, and icGreaterOrEqual select the relation; numeric pairs and date pairs compare their values, Boolean pairs order False before True, and string pairs compare case-sensitive UTF-16 code units ordinally |
Composite keys retain each member's exact Variant type and text identity; Integer(1), Double(1), the string '1', a Boolean, and a date are distinct members; there is no case folding, Unicode normalization, locale parsing, or delimiter ambiguity; combinations such as ('ab', 'c') and ('a', 'bc') remain different; each validation pass starts a fresh tuple index
When SkipIncompleteRows = True, a missing, null, or empty-string member excludes that row from tuple uniqueness; setting it to False includes those members with their original Variant identities; a duplicate reports the first tuple column as its cell address and the first matching row through FirstDuplicateRow
The existing single-column irUnique retains its text-based, case-insensitive matching behavior and skips missing or null values; use AddUniqueRule([Column]) when strict typed identity is required for one column
Cross-column comparisons never coerce strings to numbers, numbers to Booleans, or ordinary numbers to dates; mixed incompatible categories fail even for icNotEqual; string comparisons distinguish composed and decomposed Unicode, preserve embedded null characters, and use shorter-prefix-first ordering; when SkipBlankValues = False, either blank operand produces a cross-column violation
Structured results and correction workbooks
TlxImportViolation | Row, Col, SheetName, and Address identify the cell, with Address in A1 notation; ValueText and ErrorText carry display information; RuleName and Kind identify the configured rule and failure category; RelatedColumn identifies the second operand for a cross-column failure and FirstDuplicateRow identifies the original row for uniqueness failures |
TlxImportViolationKind | ivRequired, ivTextLength, ivPattern, ivUnique, ivCallback, ivValueType, ivValueRange, ivCellError, ivFormulaCacheMissing, ivCompositeUnique, and ivCrossColumn distinguish supported failure categories |
Check(Sheet) returns the number of violations, and ViolationCount plus zero-based Violation(Index) enumerate the report; one column rule reports its first failing predicate, while independently configured tuple and comparison rules can add further violations for the same cell; assign meaningful Name values when callers need stable application rule identifiers
Formula cells are validated using their stored cached values; a formula without a stored cached result reports ivFormulaCacheMissing, and an error result reports ivCellError; explicitly recalculate before checking when fresh formula results are required; validation does not access external sources, alter formula definitions, or evaluate uncached formulas
OnVerifyCell retains the TlxImportVerifyCell callback signature and runs after successful applicable column predicates and uniqueness checks; it returns a Boolean and can set an application error message; callbacks must keep the workbook and validation schema unchanged, and workbook writes are rejected by the read lease; callback exceptions propagate and the lease is released for subsequent operations
Check never annotates, deletes rows, or materializes packed values; use Annotate after checking to apply red fonts and append error text to existing comments, or explicitly call KeepOnlyViolations to remove nonviolating rows and create a correction workbook; these methods modify the supplied worksheet, so call them on the intended workbook after reviewing the report
Validation borrows the worksheet and workbook for the synchronous call; it does not adopt the caller's object ownership or require an interface-owned workbook; a read lease protects relevant stored-cell snapshots and stored formula-cache access throughout the check
External link save policies
TXLSExternalLinkUpdateMode = (xluPromptUser, xluNever, xluAlways);
property IXLSWorkbook.SaveExternalLinkValues: Boolean;
property IXLSWorkbook.UpdateLinks: TXLSExternalLinkUpdateMode;
property TXLSXWorkbook.SaveExternalLinkValues: Boolean;
property TXLSXWorkbook.UpdateLinks: TXLSExternalLinkUpdateMode;
xluPromptUser; xluNever and xluAlways only change the update preference stored in the workbook and never authorize or initiate external file or network access
Calculation audit and workbook hints
function TXLSWorkbook.RecalcAndVerify(MaxIssues: Integer = 10000): TXLSCalculationAuditReport;
function TXLSXWorkbook.RecalcAndVerify(MaxIssues: Integer = 10000): TXLSCalculationAuditReport;
function TXLSWorkbook.RecalcAndVerifyEx(const Options: TXLSRecalcAuditOptions): TXLSCalculationAuditReport;
function TXLSXWorkbook.RecalcAndVerifyEx(const Options: TXLSRecalcAuditOptions): TXLSCalculationAuditReport;
function TXLSWorkbook.RunCalculationAudit(const Options: TXLSRecalcAuditOptions): TXLSCalculationAuditReport;
function TXLSWorkbook.FormulaIsVolatile(Formula: WideString): Boolean;
function TXLSWorkbook.AuditOverlayHash(SheetIndex, Row, Col: Integer): Integer;
function TXLSWorkbook.AuditOverlayRead(SheetIndex, Row, Col: Integer; var Value: Variant): Boolean;
procedure TXLSWorkbook.AuditOverlayWrite(SheetIndex, Row, Col: Integer; const Value: Variant);
procedure TXLSWorkbook.AuditOverlayClear;
TXLSCalculationAuditIssueKind = (xlcaiCacheMismatch, xlcaiParseFailure,
xlcaiMissingFunction, xlcaiMissingName, xlcaiUnsupportedArguments,
xlcaiCircularReference, xlcaiExternalReferenceDenied,
xlcaiExternalReferenceMissing, xlcaiDataTableSkipped, xlcaiCancelled,
xlcaiInternalFailure);
TXLSCalculationAuditIssue = record
Kind: TXLSCalculationAuditIssueKind;
SheetIndex: Integer;
SheetName: WideString;
Row: Integer;
Col: Integer;
Formula: WideString;
Symbol: WideString;
Expected: Variant;
Actual: Variant;
ResultCode: Integer;
Stack: WideString;
ExternalTarget: WideString;
end;
TXLSCalculationAuditIssues = array of TXLSCalculationAuditIssue;
TXLSRecalcAuditProgress = procedure(ASender: TObject;
ACurrent, ATotal: Integer; var ACancel: Boolean) of object;
property WorkbookCodeName: WideString;
property CalculationThreadMode: TXLSCalculationThreadMode;
property ForceFullCalculationState: TXLSOptionalBooleanState;
property RefreshAllOnLoadState: TXLSOptionalBooleanState;
RecalcAndVerify combines formula-symbol failures and cached-value mismatches into stable structured categories with worksheet coordinates, formulas, symbols, expected and actual values, and bounded truncation while leaving caches and workbook semantics unchanged. RecalcAndVerifyEx runs the deep audit: it evaluates every formula once through the dependency graph into an isolated result overlay so dependent cells read this pass instead of stale caches, classifies evaluation failures (unsupported arguments, circular references, denied or missing external references, data tables skipped, cancellation, internal failures) with result codes, records a bounded call stack per failure, honours an issue budget and a progress/cancel sink, and stays read-only unless ApplyResults commits the recomputed values atomically after a fully successful pass over an unchanged workbook structureAbsoluteTolerance and RelativeTolerance control mismatch reporting, not intermediate calculation values or explicit cache application
For numeric results, a mismatch requires an absolute difference above AbsoluteTolerance and, when relative tolerance is enabled, above RelativeTolerance * max(abs(Expected), abs(Actual))
Equality at either threshold is tolerated; changed values still enter the audit overlay so dependent formulas see the current calculation, and ApplyResults commits those values even when their differences are not reportable
A read-only audit never changes stored cachesTXLSCalculationAuditReport.Issues is a TXLSCalculationAuditIssue; Kind selects one of the xlcai* categories, Expected / Actual carry the compared values for cache mismatches, Stack is the bounded evaluation call chain rendered as Sheet!A1 > Sheet!B2 (outermost frame first), and ExternalTarget describes the external workbook for external-reference issues. TXLSRecalcAuditOptions.OnProgress is a TXLSRecalcAuditProgress sink that receives ACurrent / ATotal node progress and can set ACancel to stop the audit at the next node boundary with a single xlcaiCancelled issueRunCalculationAudit is the engine entry the workbook-level audit wrappers delegate to and accepts the same options record. FormulaIsVolatile reports whether a formula would force a recalculation on every pass (calls such as NOW, RAND, TODAY, OFFSET, INDIRECT, or an unresolvable reference)AuditOverlayWrite stores a replacement value for one cell (1-based sheet index, 0-based row and column matching the calculator convention), AuditOverlayRead and AuditOverlayHash query it, and AuditOverlayClear empties the layer. Overlaid values are returned by the normal cell-value getters, so recalculation and the deep audit observe them without mutating worksheet cells; clearing the overlay restores the stored valuesTable formula and IME state
property TXLSXTable.ColumnCalculatedFormulaArrayStates[Index: Integer]: TXLSTableFormulaArrayState;
property TXLSXTable.ColumnTotalsFormulaArrayStates[Index: Integer]: TXLSTableFormulaArrayState;
property TDataValidation.ImeMode: TXLSDataValidationImeMode;
property TXLSXDataValidation.ImeModeKind: TXLSDataValidationImeMode;
SaveExternalLinkValues to False omits Classic XCT and CRN records or the XLSX external-book sheetDataSet subtree, while retaining link targets, sheet names, external defined names, relationships, formula references, unknown XML, and the in-memory cache; restoring the property to True on the same workbook can serialize that retained cache again
Web Add-in task pane inspection and removal
function IXLSWorkbook.HasWebAddinTaskPanes: Boolean;
function IXLSWorkbook.WebAddinTaskPaneCount: Integer;
function IXLSWorkbook.RemoveWebAddinTaskPanes: Integer;
function TXLSXWorkbook.HasWebAddinTaskPanes: Boolean;
function TXLSXWorkbook.WebAddinTaskPaneCount: Integer;
function TXLSXWorkbook.RemoveWebAddinTaskPanes: Integer;
1303 and raise an exception before mutation, while Classic XLS and ODS return False, 0, and -1 without package scanning
Workbook object display policy
TXLSObjectDisplayMode = (xlsodmShowAll, xlsodmShowPlaceholders,
xlsodmHideAll);
property IXLSWorkbook.ObjectDisplayMode: TXLSObjectDisplayMode;
property TXLSWorkbook.ObjectDisplayMode: TXLSObjectDisplayMode;
property TXLSXWorkbook.ObjectDisplayMode: TXLSObjectDisplayMode;
property TXLSPaginationModel.ExportObjectPlaceholders: Boolean;
property TXLSPDFExport.ExportObjectPlaceholders: Boolean;
property TXLSSvgExport.ExportObjectPlaceholders: Boolean;
property TXLSPageImageExporter.ExportObjectPlaceholders: Boolean;
property TXLSPrintDocument.ExportObjectPlaceholders: Boolean;
property TXLSXHtmlExportOptions.ExportObjectPlaceholders: Boolean;
workbookPr.showObjects; missing values default to xlsodmShowAll, untouched reserved Classic payloads and unsupported XLSX tokens remain lossless, and explicit assignments emit only canonical values
ExportObjectPlaceholders requests the same low-cost policy without decoding image payloads or constructing chart scenes
xlsodmHideAll prevents drawing collection and object-driven range expansion before rendering begins; workbook conversion carries all three states, ODS writes complete drawings for placeholder mode and omits drawing and media output for hide-all mode, and worksheet backgrounds remain independent
Render calibration values and snapshots
TXLSRenderCalibration = record
WidthCorrection: Double;
HeightCorrection: Double;
LineSpacing: Double;
CellMarginFactor: Double;
ScreenScaling: Integer;
MeasurementDpi: Integer;
end;
function XLSDefaultRenderCalibration: TXLSRenderCalibration;
function XLSValidateRenderCalibration(const AValue: TXLSRenderCalibration;
out AInvalidField: TXLSRenderCalibrationField): Boolean;
1, 1, 1, 1, 100, and 96; width and height corrections must be greater than zero and less than two, line spacing is bounded to (0, 4], cell margins to [0, 4], screen scaling to [100, 500] percent, and measurement DPI to [36, 2400]
RenderCalibration, CaptureRenderCalibration, and ResetRenderCalibration members; whole-record assignment validates before mutation, and each capture returns an independent immutable-by-convention value snapshot for one rendering operation
Render geometry and font measurement
TXLSRenderGeometryBackend = (xlsrgbAutoFit, xlsrgbPagination, xlsrgbPdf,
xlsrgbSvg, xlsrgbBitmap, xlsrgbPrintPreview, xlsrgbViewer, xlsrgbHtml);
TXLSRenderFont = record
Name: WideString;
Size: Double;
Styles: TXLSRenderFontStyles;
Charset: Byte;
end;
function CreateXLSRenderGeometry(
const ACalibration: TXLSRenderCalibration;
AWorkbookGeneration: UInt64;
ABackend: TXLSRenderGeometryBackend;
ACacheCapacity: Integer = 4096): IXLSRenderGeometry;
property TXLSHTMLExport.RenderGeometry: IXLSRenderGeometry;
property TXLSXHtmlExportSession.RenderGeometry: IXLSRenderGeometry;
IXLSRenderGeometry owns one immutable calibration, workbook generation, backend identity, measurement service, and bounded operation-local metric cache; CreateXLSRenderGeometry uses GDI, while CreateXLSPortableCairoRenderGeometry in lxPortableCairo uses explicit font bytes with FreeType/HarfBuzz on native Linux or macOS; MeasureText returns pixel width, height, line height, ascent, descent, and line count while MaximumDigitWidthPixels, ColumnWidthToPixels, PixelsToColumnWidth, PointsToPixels, PixelsToPoints, and UsableCellWidthPixels provide the shared geometry conversions
MarkSheet measurement, while TXLSPaginationModel.Build captures one service for the selected RenderBackend; PDF, SVG, bitmap, print-preview, workbook-viewer, and HTML entry points select their own backend before output, changing workbook calibration cannot mutate an existing snapshot, and output does not write worksheet dimensions
xlsrgbHtml service, while an incremental TXLSXHtmlExportSession captures once in BeginExport and reuses that snapshot for all sheets; both exporters expose the retained service through RenderGeometry for calibration and cache diagnostics
IXLSRenderGeometry properties WorkbookGeneration, CacheCapacity, and CacheEntryCount report the bound generation and cache fill for diagnostics, and ImplicitWidthMaximumDigitWidthPixels returns the digit-width measurement behind implicit column-width emulation
MeasureText fills a TXLSRenderTextMetrics record (pixel width, height, line height, ascent, descent, and line count) from a TXLSRenderFont whose Styles member is a set of TXLSRenderFontStyle flags (bold, italic, underline, strikethrough)
Optional physical font metrics
Reserve calls with XLSCoveredSingleLineFontMetricBounds or XLSShapedSingleLineFontMetricBounds before using the matching optional capability
Use IXLSRenderCoveredFontMetricSource to check whether every Unicode scalar in a normalized single-line string has a nonzero nominal glyph in the selected physical font face and to obtain that face's font metrics
Use IXLSRenderShapedFontMetricSource when the text needs shaping or resolved fallback runs, with an explicit locale supplied by the caller
Query these optional interfaces from an IXLSRenderGeometry instance with Supports
The existing IXLSRenderGeometry and IXLSRenderFontMetricSource interfaces retain their method order and identifiers
These APIs report physical font metrics in one captured rendering context They do not return text width, glyph positions, ink bounds, or a line box for a target application They do not set worksheet dimensions or define Excel's row-height, font-fallback, locale-selection, or default-grid policy Keep the source font, displayed text, locale, and layout policy under their own owners when using the results in a larger layout operation
TXLSRenderFontMetrics = record
HeightPixels, AscentPixels, DescentPixels, EmHeightPixels: Integer;
ExternalLeadingPixels, AverageWidthPixels: Integer;
end;
IXLSRenderCoveredFontMetricSource = interface
['{A21CF465-8A72-4638-8442-833828710E6A}']
function TryMeasureCoveredSingleLineFont(
const AText: WideString; const AFont: TXLSRenderFont;
AMaximumBytes, AMaximumWork: Int64;
out AMetrics: TXLSRenderFontMetrics;
out AUsedBytes, AUsedWork: Int64): Boolean;
end;
IXLSRenderShapedFontMetricSource = interface
['{D41E1D02-56C9-47E6-B49A-C9F21D6ACF28}']
function TryMeasureShapedSingleLineFont(
const AText: WideString; const AFont: TXLSRenderFont;
const ALocaleName: WideString;
AMaximumBytes, AMaximumWork: Int64;
out AMetrics: TXLSRenderFontMetrics;
out AUsedBytes, AUsedWork: Int64): Boolean;
end;
procedure XLSCoveredSingleLineFontMetricBounds(
const AText: WideString; const AFont: TXLSRenderFont;
out AMaximumBytes, AMaximumWork: Int64);
procedure XLSShapedSingleLineFontMetricBounds(
const AText: WideString; const AFont: TXLSRenderFont;
const ALocaleName: WideString;
out AMaximumBytes, AMaximumWork: Int64);
Coverage and shaping
The covered method validates the entire UTF-16 string, selects and verifies the requested primary family, and checks nominal glyph coverage in that physical face
Successful nominal coverage does not prove shaping, mark positioning, ligature behavior, variation-selector interpretation, or an application's fallback choices
A missing nominal glyph returns False, including cases that a shaping engine could render with another face
The shaped method creates a no-wrap GDI-compatible DirectWrite layout using the explicit locale and the verified primary font It accepts only actual glyph runs that account for the entire source text without overlapping source ranges or unresolved glyph indices Each accepted run's physical face and size are mapped back to a GDI measurement context and verified by physical face and font-file identity The returned record contains a separate maximum for each field across the primary font contribution and all accepted run contributions Those independent maxima need not belong to one face and are not a measured text bounding rectangle or a complete application's line-height calculation
An empty string returns the validated primary font metrics when the guarded native capability is available
For nonempty text, an unavailable required run or an unsupported physical identity returns False
Neither method substitutes a nominal-only result after a failed shaped operation
Return values and failures
| Outcome | Meaning |
|---|---|
Supports returns False |
This geometry implementation does not expose the optional interface |
Covered method returns True |
Every scalar has nominal coverage in the selected physical face and AMetrics contains that face's metrics in this context |
Shaped method returns True |
The complete source string was accepted through verified physical runs and AMetrics contains the per-field maxima |
Either method returns False |
The native capability, nominal glyph coverage, complete shaped run ownership, or a supported finite representation is unavailable; every field of AMetrics is zero |
EArgumentException |
The font descriptor, locale, UTF-16 spelling, or single-line input is invalid |
EArgumentOutOfRangeException |
A quota is negative or exhausted, the shaped text exceeds 32767 UTF-16 units, or the geometry calibration or cache-capacity constructor argument is outside its supported domain |
EInvalidOperation |
The requested primary family was substituted or is unavailable, the selected font context changed, or an unexpected native measurement or callback failure occurred |
The Boolean result is not an exception suppression contract
In particular, an unavailable requested primary family raises an exception instead of silently measuring a substitute family
The used-budget outputs can contain charges on a refused or failed attempt and must not be interpreted as successful metric output
Use AMetrics only after a True result
Text must contain well-formed UTF-16 and must already be single-line text suitable for the caller's layout
C0 controls, including tab and line breaks, NEL (U+0085), line separator (U+2028), and paragraph separator (U+2029) raise an input exception
The complete spelling is validated before an early missing-glyph result can be returned
The shaped method additionally limits text to 32767 UTF-16 code units
The font family name must contain 1 through 255 UTF-16 units without C0 controls, and the point size must be finite and between 1/64 and 4096, inclusive
The descriptor also carries the existing bold, italic, underline, strikeout, and charset fields
The shaped locale name must contain 1 through 85 UTF-16 units without characters below U+0021, and the guarded Windows path checks that the locale name is available
Supply the locale from the caller's actual rendering contract rather than assuming that the Windows user locale identifies a workbook's language or an application's UI language
DPI, calibration, and budgets
The geometry object captures TXLSRenderCalibration, workbook generation, and backend at construction
MeasurementDpi determines the primary GDI pixel size selected from the point-size descriptor
Height correction applies to height, ascent, descent, and external leading; width correction applies to average character width
EmHeightPixels retains the physical em height without applying height correction
These single-line font metrics do not apply cell margins, multi-line spacing, or implicit-column screen-scaling emulation
Create a new operation context when the font environment or intended calibration changes
Call the matching Bounds helper before measurement to obtain conservative per-call byte and work reservations for the exact text, font, and locale The helpers inspect lengths only and do not open a native context, copy or scan the text, or validate its spelling and descriptor values The execution method still validates those inputs Use a caller-selected aggregate budget when invoking the methods repeatedly and account for each invocation's returned charges
AUsedBytes reports charged reservations, including the operation's native-context allowance, rather than a measured process-memory peak
AUsedWork reports the controlled validation, scan, glyph, range, and identity-comparison work charged by this operation
Neither limit guarantees the Windows font-cache peak or the internal allocation and work of the system shaping engine
Exhausted supplied quotas raise an exception; unsupported finite face or run representations return False
The general geometry cache capacity does not replace these per-call budgets
For the covered helper, let T be the number of UTF-16 units in the text and F the font family name length
MaximumBytes = (SizeOf(Cardinal) + SizeOf(Word)) * 128
+ 2 * SizeOf(TXLSRenderFontMetrics) + 4 * F + 4096
MaximumWork = F + 21 + 4 * T + ceil(T / 128)
For the shaped helper, let L be the locale length, P = min(T, 16), and R = min(T, 256)
MaximumBytes = 65536 + 64 * T + 4 * (F + L)
MaximumWork = F + L + 1024 + 64 * T + 2304 * (P + 1)
+ R * (R - 1) / 2
Use the helper calls in application code rather than duplicating these implementation formulas
Finite shaped representation
The shaped operation admits up to 256 nonempty, disjoint source ranges and 16 distinct physical face/size tuples in one call A run may contain at most 16 glyphs per source UTF-16 unit plus 16 additional glyphs Physical identity comparison admits up to eight font files per face and 256 reference-key bytes per file The accepted ranges must cover every source UTF-16 unit exactly once
Sideways runs, custom drawing effects, inline-object callbacks, and decoration callbacks are refused by this single-line capability
Neither API accepts variation-axis coordinates
The nonempty shaped-run metric path refuses font resources with an fvar table because file and face identity alone cannot identify their variation-axis coordinates
Nominal coverage does not establish an axis-specific variation instance either
The empty-string primary-metric shortcut does not prove nonempty variable-font support
Platform and build scope
The GDI factory is Windows-specific and retains its existing unsupported-platform behavior outside Windows
The native covered and shaped implementation is compiled only when LX_CLASSIC_DWRITE_ADVANCE is enabled by the unit's non-FPC CompilerVersion >= 37.0 guard
On a Windows build without that guard, the optional methods validate their input and quotas and return False without constructing the guarded native context
The optional interface can therefore be present even when the native measurement path is unavailable
DirectWrite must also be available at runtime
Portable render geometry implementations are not implied to expose these optional interfaces
The qualified evidence for this addition uses the Windows Win64 command-line compiler and its pinned Windows font environment It does not establish execution on older compilers, FPC, other architectures, or non-Windows platforms The public unit interface changes, so rebuild the affected compiled-unit dependency closure coherently instead of mixing old and new unit files
Bounds and method examples
The following helpers query the optional interfaces and reserve each call before measurement They let invalid input, exhausted quotas, and unexpected native failures propagate as exceptions The calibration and generation are provided by the calling operation
uses
SysUtils, lxWorkbookView, lxRenderGeometry;
function TryCoveredMetricExample(
const AText: WideString; const AFont: TXLSRenderFont;
const ACalibration: TXLSRenderCalibration; AGeneration: UInt64;
out AMetrics: TXLSRenderFontMetrics): Boolean;
var
Geometry: IXLSRenderGeometry;
Capability: IXLSRenderCoveredFontMetricSource;
MaximumBytes, MaximumWork, UsedBytes, UsedWork: Int64;
begin
FillChar(AMetrics, SizeOf(AMetrics), 0);
Result := False;
{$IFDEF MSWINDOWS}
Geometry := CreateXLSRenderGeometry(
ACalibration, AGeneration, xlsrgbBitmap, 0);
if not Supports(Geometry, IXLSRenderCoveredFontMetricSource,
Capability) then
Exit;
XLSCoveredSingleLineFontMetricBounds(
AText, AFont, MaximumBytes, MaximumWork);
Result := Capability.TryMeasureCoveredSingleLineFont(
AText, AFont, MaximumBytes, MaximumWork,
AMetrics, UsedBytes, UsedWork);
{$ENDIF}
end;
function TryShapedMetricExample(
const AText: WideString; const AFont: TXLSRenderFont;
const ALocaleName: WideString;
const ACalibration: TXLSRenderCalibration; AGeneration: UInt64;
out AMetrics: TXLSRenderFontMetrics): Boolean;
var
Geometry: IXLSRenderGeometry;
Capability: IXLSRenderShapedFontMetricSource;
MaximumBytes, MaximumWork, UsedBytes, UsedWork: Int64;
begin
FillChar(AMetrics, SizeOf(AMetrics), 0);
Result := False;
{$IFDEF MSWINDOWS}
Geometry := CreateXLSRenderGeometry(
ACalibration, AGeneration, xlsrgbBitmap, 0);
if not Supports(Geometry, IXLSRenderShapedFontMetricSource,
Capability) then
Exit;
XLSShapedSingleLineFontMetricBounds(
AText, AFont, ALocaleName, MaximumBytes, MaximumWork);
Result := Capability.TryMeasureShapedSingleLineFont(
AText, AFont, ALocaleName, MaximumBytes, MaximumWork,
AMetrics, UsedBytes, UsedWork);
{$ENDIF}
end;
For example, construct combining text with WideString('e') + WideChar($0301) and pass the locale selected by the caller to the shaped helper
A covered False result can be followed by a separately budgeted shaped attempt when that matches the caller's policy
Do not replace a shaped refusal with an unconditional nominal metric or a guessed row height
Optional source-owned single-line cell metrics
Version 2.384.529 adds IXLSRenderCellLineMetricSource for bounded single-line observations of at most 4096 UTF-16 units using the existing TXLSRenderFont, an explicit locale and the geometry's captured calibration
Query the capability from IXLSRenderGeometry with Supports and call XLSCellLineMetricBounds before measuring
The result contains source-owned em and descent components and separately named layout height and baseline observations The producer value identifies how those observations were obtained This capability does not set worksheet row heights or select a spreadsheet application's font, locale or grid policy
Version 2.384.530 improves source ownership when text is split among separate shaping runs
The method considers all boundary-aligned source occurrences and assigns a range only when a forced choice remains compatible with complete, disjoint source coverage
A fixed point with unresolved alternatives returns False with zero metrics, even when a more expensive search might establish a unique assignment
Source-range preparation and shaping retain cumulative work charges before controlled operations and preserve the existing byte and work limits
A quota failure does not supply partial metrics and the caller may retry with a suitable allowance
TXLSRenderCellLineProducer = (
xlsclpCurrentSSA, xlsclpDWriteAfterMissingGlyphs, xlsclpEmptyPrimary);
TXLSRenderCellLineMetrics = record
EmHeightPixels, DescentPixels: Integer;
LayoutHeightPixels, BaselinePixels: Double;
Producer: TXLSRenderCellLineProducer;
end;
IXLSRenderCellLineMetricSource = interface
['{8E5BE61F-F916-430B-A234-A7026FB51B94}']
function TryMeasureSingleLineCell(
const AText: WideString; const AFont: TXLSRenderFont;
const ALocaleName: WideString;
AMaximumBytes, AMaximumWork: Int64;
out AMetrics: TXLSRenderCellLineMetrics;
out AUsedBytes, AUsedWork: Int64): Boolean;
end;
procedure XLSCellLineMetricBounds(
const AText: WideString; const AFont: TXLSRenderFont;
const ALocaleName: WideString;
out AMaximumBytes, AMaximumWork: Int64);
Producer and baseline ownership
| Producer | Accepted source ownership | Height and baseline meaning |
|---|---|---|
xlsclpCurrentSSA | Current Uniscribe records have complete, unambiguous source ranges, cluster mapping, glyph indices and physical font ownership | The positioned physical font-cell box union and its common primary baseline relative to the union's top |
xlsclpDWriteAfterMissingGlyphs | The current SSA selected face has a proved missing source glyph and a complete Unicode DirectWrite line owns the replacement physical runs | The actual DirectWrite line height and line baseline, converted from DIPs to captured measurement pixels |
xlsclpEmptyPrimary | An empty source has independently verified primary physical font metrics and claims no source glyph | The primary GDI font-cell height and ascent |
EmHeightPixels and DescentPixels retain the explicit primary contribution and the accepted source-run contributions transported to their common producer-owned baseline
The line components, layout observation and glyph ink are distinct quantities
Neither the layout height nor a sum of components is an application row-height policy
Finite context prerequisites
The initial native implementation requires Windows with the unit's non-FPC CompilerVersion >= 37.0 guard, available DirectWrite and the supported Uniscribe path
Both WidthCorrection and HeightCorrection must equal one
The actual device context DPI must match the geometry's captured MeasurementDpi during creation and measurement
The caller owns a suitable, consistent DPI-awareness context; capturing a DPI value alone does not change the later measurement context
The explicit locale must match the current Windows user-default SSA locale
It gates that current SSA context and is passed to the DirectWrite format, but it does not change Windows settings, choose arbitrary SSA language behavior or identify an application's UI language
An optional interface may be present even when its guarded native capability returns False
Input must be normalized single-line, well-formed UTF-16 with at most 4096 code units The existing font descriptor rules apply The implementation refuses unproved physical identity, variation fonts, ambiguous source ranges, missing or unsupported run evidence and baseline transport that cannot be represented by the owned integer components The existing physical, nominal-covered and shaped interfaces remain available with their existing method contracts
Results and failure boundaries
A True result supplies the small observation record for this captured context
An unavailable finite capability returns False with zero result metrics
Malformed arguments and invalid limits raise argument exceptions, exhausted explicit allowances raise EArgumentOutOfRangeException, and changed source or physical context or unexpected native failures raise EInvalidOperation
Unavailable or substituted requested font families retain the existing invalid-operation behavior
Use the metrics only after a True result and retain charges from refused or failed attempts under the caller's budget owner
Per-call reservations and qualification
XLSCellLineMetricBounds is a pure reservation helper and rejects more than 4096 UTF-16 units before arithmetic
Reserve the returned byte and work allowances before a call
They cover explicit owned buffers and charged operations, not the operating-system font-cache or shaping peak
The reported charges can be lower than the conservative reservation and are not an aggregate before-work budget callback
A caller requiring a cumulative before-work budget must own sufficient allowance for each operation
The qualifying execution uses Win64 RAD Studio 37, actual 120 DPI, the pinned font environment, the zh-CN Windows user locale and identity corrections Other compilers, architectures and locales are not newly qualified by that execution Known regression examples are not a new blind holdout or native application acceptance Rebuild the affected compiled-unit dependency closure coherently when adopting the new public unit interface
Query and measurement example
The calling operation supplies a geometry object created under its captured, supported device context The example preserves Boolean unavailability and allows invalid input, quota exhaustion and unexpected native failures to propagate
uses SysUtils, lxRenderGeometry;
function TryCellLineMetricExample(
const AGeometry: IXLSRenderGeometry;
const AText: WideString; const AFont: TXLSRenderFont;
const ALocaleName: WideString;
out AMetrics: TXLSRenderCellLineMetrics): Boolean;
var
Capability: IXLSRenderCellLineMetricSource;
MaximumBytes, MaximumWork, UsedBytes, UsedWork: Int64;
begin
FillChar(AMetrics, SizeOf(AMetrics), 0);
Result := False;
if not Supports(AGeometry, IXLSRenderCellLineMetricSource, Capability) then
Exit;
XLSCellLineMetricBounds(AText, AFont, ALocaleName, MaximumBytes, MaximumWork);
Result := Capability.TryMeasureSingleLineCell(
AText, AFont, ALocaleName, MaximumBytes, MaximumWork,
AMetrics, UsedBytes, UsedWork);
end;
Import, code generation, comparison, and monitoring
TXLSHTMLImport | LoadFromHTML overloads import HTML table content from a stream or file into a worksheet, with optional start coordinates, table selection, and decimal separator; assigning OnCell (type TXlsHtmlImportCellEvent: one-based row and column, the value as a Variant that is Null for empty cells, a Double for clean numbers, and a string otherwise, plus the declared column and row spans) replaces the default sink — parsed cells are delivered to the callback and no worksheet is required |
TXLSCodeGen | Language (type TlxCodeGenLanguage: lcgDelphi or lcgCppBuilder) selects the source dialect of the generated statements, GenerateToList writes generated workbook code to a string list, and TlxCodeGenOptions widens the output with merges, column widths, or number formats (cgoMerges, cgoColumnWidths, cgoNumberFormats; sheets and cells are always emitted) |
TXLSXWorkbookCompare | Compare compares typed stored cells, formula text, sheet presence, and merges; Options adds formula caches, base cell styles, and row or column geometry, SetNumericTolerance configures numeric equality, and Count, Diff, and Report expose the ordered results; see workbook comparison |
TXLSFileMonitor | IntervalMs selects the polling interval and SynchronizeEvent selects synchronized callback delivery; an OnFileChanged handler may deactivate or destroy the monitor, or change FileName to start watching another file |
TXLSCSVLoader and TXLSCSVSaver | The loader parses delimited text into an in-memory grid of Variants — ParseFile and ParseStream fill the grid, CellValue, RowCount, and ColCount read it back — with auto-detected separator (ValueSeparator) and encoding (TXLSCsvEncoding: system ANSI, UTF-16, UTF-8) and optional type promotion controlled by DetectTypes and per-column ColumnTypes entries (TXLSCsvColumnType: auto, text, number, date, boolean, skip); SkipRows, AutoTrim, LocaleTolerantNumbers, and FieldWidths refine fixed-width and locale handling. TXLSCSVSaver.SaveAs writes the grid back with RFC 4180 quoting, and QuoteAllStrings forces quoting; TXLSTSVSaver derives from the saver for tab-separated output |
Workbook comparison
Small Business edition: Workbook comparison (lxCompare) ships with HotXLS Small Business and Enterprise (and their DCU editions), in the HotXLSSB runtime package for RAD Studio and HotXLSLazSB.lpk for Lazarus; the trial build includes it under the usual trial limits
TXLSXWorkbookCompare in lxCompare compares two TXLSXWorkbook instances without recalculating formulas or modifying either workbook; sheets are paired by case-insensitive name, and changing sheet order alone does not produce a difference
The default Options value is empty and both tolerances default to zero; default comparison reports added or removed sheets, added or removed stored cells, changed typed literal values, changed formula text, and added or removed merged ranges
Literal comparison distinguishes numbers, text, Boolean values, dates, errors, and blanks: the number 1 differs from the text '1', a Boolean differs from its text spelling, dates retain their own type, and errors compare by their stored error code; numeric storage types with equal values compare equally, while distinct Int64 values remain distinct during exact comparison
lcoFormulaCachedResults | For cells with matching formula text, compares the existing cached result and distinguishes a missing or invalidated cache from an available cache; loaded and calculated caches with the same typed value compare equally |
lcoCellStyles | Compares resolved base styles at matching stored-cell coordinates, including fonts, fills, gradients, borders, alignment, number formats, and cell protection; unrelated style-pool insertion order does not create differences, and theme colors resolve against each workbook's current theme |
lcoAxisGeometry | Compares effective row heights, column widths, hidden flags, outline levels, collapsed flags, and worksheet defaults; an explicit size equal to the effective default compares equally to an implicit size |
lcoDefinedNames | Compares workbook and worksheet scoped names, their formula definitions, visibility, comments, and macro flags; scope follows worksheet names, and insertion order does not create differences |
lcoDataValidations | Compares validation definitions in stored order, including normalized target ranges, formulas, operators, prompts, error messages, and control flags; changing the order of target ranges within one definition does not create a difference |
lcoConditionalFormats | Compares conditional-format definitions in stored order, including effective priority, stop-if-true behavior, target ranges, formulas, differential styles, and supported color-scale, data-bar, and icon-set settings; style-pool and indexed-palette identifiers resolve to their semantic values |
lcoTables | Pairs tables by name and compares ranges, headers, totals, style settings, comments, column names, labels, formulas, array flags, unique names, connection names, filter criteria, and sort conditions; table IDs, column IDs, and insertion order do not create differences, while color-filter and sort differential-style IDs resolve to appearance |
lcoDrawings | Compares typed drawing definitions in drawing order, retaining group-child order and chart plot-group order; supported canonical definitions cover images, text boxes, charts, groups, complete typed slicer views, and typed timeline views, with opaque or unsupported drawing nodes raising EXLSSemanticSnapshot |
lcoBlankStyleRegions | Compares resolved base styles across coordinates without a stored cell on either side, including worksheet defaults and virtual style overlays; equivalent rectangle subdivisions compare equally, and equal adjacent changes coalesce into rectangles without materializing cells |
lcoRichTextRuns | Compares effective run fonts and text at matching stored text cells, inherits the base font for omitted run properties, ignores empty runs, and coalesces adjacent runs with equal effective fonts; plain text matches an equivalent default-font rich-text run |
lcoPivotTables | Pairs typed PivotTable definitions by name and compares source bindings, layout, fields, ordered view members, data aggregations, filters, grouping references, calculated definitions, styles, and native materialization flags; cache and shared-member IDs resolve to source identities and typed values |
lcoPivotCaches | Pairs local typed PivotCache definitions by source identity and compares refresh metadata, field metadata, grouped labels and ranges, unordered shared-member domains, and ordered typed record values; numeric, text, Boolean, date, error, and empty members remain distinct, dates retain binary64 precision, and cache IDs and shared-member slot order do not create differences |
lcoSlicerState | Pairs named slicer views and caches, including table-column or non-OLAP Pivot bindings, connected PivotTable names, typed member selections, cross-filter and sort settings, caption, scroll position, column layout, dimensions, style, lock and caption flags, and anchor geometry; bindings resolve table, column, sheet, and cache IDs |
lcoTimelineState | Pairs named typed timeline views and local non-OLAP caches, including source-field and connected PivotTable bindings, active date selection, caption, level, and worksheet bounds; inactive selections omit unused date endpoints |
Options has type TlxCompareOptions, a set of TlxCompareOption; enabling an option adds its differences to the default comparison
SetFeatureLimits(MaxBytes, MaxItems) validates both positive limits before changing either setting; MaxFeatureBytes defaults to 64 MiB and MaxFeatureItems defaults to 1,000,000, and the individual setters preserve the same atomic validation
Feature budgets cover the aggregate detached canonical bytes and counted entries from both workbooks, including rich-text runs, filter XML nodes, Pivot fields, domain members and record values, and slicer or timeline connections; readers check counts and large text inputs before constructing native XML, enforce bounded output streams, and raise EXLSXSemanticBudget when a limit is exceeded — the exception is declared in lxSemanticSnapshot as EXLSSemanticBudget, with EXLSXSemanticBudget as its alias on the XLSX facade
SetNumericTolerance(AbsoluteTolerance, RelativeTolerance) validates both arguments before changing either setting; both must be finite and nonnegative, and the individual AbsoluteTolerance and RelativeTolerance setters use the same validation
Numeric literal and numeric cache values compare equally when their absolute difference is at most AbsoluteTolerance or their difference relative to the larger absolute value is at most RelativeTolerance; a threshold of zero retains exact equality, the relative calculation avoids overflow for extreme opposite values, and tolerance does not coerce text or apply to dates, styles, or geometry
LeftName and RightName set optional display names used by Report lines, defaulting to left and right; the names affect reporting only, not sheet pairing or comparison
Comparer := TXLSXWorkbookCompare.Create;
try
Comparer.Options := [lcoFormulaCachedResults, lcoCellStyles,
lcoAxisGeometry];
Comparer.SetNumericTolerance(0.001, 0.000001);
DifferenceCount := Comparer.Compare(LeftWorkbook, RightWorkbook);
for I := 0 to DifferenceCount - 1 do
begin
Entry := Comparer.Diff(I);
ReportLines.Add(Entry.Describe);
end;
finally
Comparer.Free;
end;
Compare returns the difference count, Count reads that count afterward, and Diff(Index) uses zero-based indexing to return a comparer-owned TlxCompareDiff; retain the comparer while reading its entries, and reacquire entries after another successful comparison
Each entry provides Kind, Sheet, one-based Row and Col where applicable, Ref, LeftText, RightText, and typed LeftKind / RightKind values; TlxCompareValueKind contains lcvNone, lcvBlank, lcvNumber, lcvText, lcvBoolean, lcvDateTime, lcvError, and lcvFormula, with lcvNone used for an absent side or a non-value difference
TlxCompareKind retains lckSheetAdded, lckSheetRemoved, lckCellAdded, lckCellRemoved, lckValueChanged, lckFormulaChanged, lckMergeAdded, and lckMergeRemoved, and adds lckFormulaCacheChanged, lckStyleChanged, lckRowGeometryChanged, and lckColumnGeometryChanged
Style differences carry stable canonical style fingerprints in LeftText and RightText; geometry differences carry the compared size, hidden, outline, and collapsed state, with Ref identifying the affected contiguous axis interval, Row set to its first row and Col to zero for rows, or Col set to its first column and Row to zero for columns
Feature differences use lckDefinedNameChanged, lckDataValidationChanged, lckConditionalFormatChanged, lckTableChanged, lckDrawingChanged, lckPivotTableChanged, lckPivotCacheChanged, lckSlicerChanged, or lckTimelineChanged; Change is lccChanged, lccAdded, or lccRemoved, and each present side carries its canonical definition fingerprint while an absent side carries an empty string
lckRichTextChanged identifies a changed run definition at its cell coordinate and carries canonical run fingerprints in LeftText and RightText; numeric tolerance applies to cell literals and formula caches, while typed feature definitions compare exactly
Feature references identify scoped names or table names, or use one-based sequence positions for validation, conditional-format, and drawing definitions; inserting or moving an ordered feature can change several positions, while workbook-level name entries have an empty Sheet
lckBlankStyleRegionChanged identifies a changed blank rectangle through Row, Col, inclusive LastRow and LastCol, and its A1 Ref; stored coordinates are handled by ordinary cell comparison and lcoCellStyles, so enable both style options to inspect stored cells and blank areas together
Describe formats one entry, while Report(List) appends the formatted entries to a caller-owned TStrings; a typed value change includes type labels when the types differ, and results sort by sheet name, row, column, difference kind, and reference rather than cell insertion order
Comparison holds read leases, walks stored cells through detached cursor snapshots, and retains packed storage; geometry partitions stored metadata boundaries and compact repeated-row spans, while blank-style comparison sweeps active rectangle and stored-cell boundaries without scanning a rectangular million-row grid; work grows with stored features, region intersections, and reported differences
A failed comparison preserves the previous successful result; invalid tolerance assignment also preserves the existing settings and result, while passing a nil workbook clears the result and returns zero
This comparison covers the XLSX facade's stored cell content and selected typed feature definitions; name, validation, conditional-format, table, and chart formula spelling normalizes through the semantic formula parser, while Pivot calculated formulas retain their stored definition text
Table filters accept supported custom, value-list, date-group, color, icon, dynamic, and top-count shapes and sort conditions; independent filter columns and value-set entries normalize their order, Boolean defaults and numeric spellings normalize, and sort-condition order remains significant
Typed Pivot, slicer, and timeline comparison resolves supported local worksheet sources and non-OLAP bindings without refreshing or evaluating availability; native slicer availability hints are derived display metadata, while member selections and recognized native sort metadata are compared
Opaque native drawing properties, incomplete binary Pivot models, external or OLAP Pivot sources, raw PivotTable supplemental records and extension XML, unknown filter XML, and unmodeled slicer or timeline extension attributes or children raise EXLSSemanticSnapshot; preservation of such data does not imply semantic equivalence
Selected imported PivotTable and PivotCache features also validate preserved native XML before comparing the typed projection, including nested field metadata and cache records; unknown namespaces, attributes, children, and extension payloads fail explicitly within the same cooperative feature limits, while modeled slicer cache bindings remain supported
TSimpleDomNode.RawName exposes the original element QName alongside the reader-normalized Name, allowing namespace-sensitive inspection without changing existing parser name matching
Workbook settings and opaque package metadata remain outside comparison; base style comparison does not evaluate conditional-format or table-style appearance, and drawing comparison preserves the semantic snapshot's supported image, text-box, chart, and ordered-group boundaries
Effective rich-text properties
TMsoFbtOpt.StoredPids returns stored OfficeArt property identifiers in sorted order, while TMsoFbtSp.PersistentFlags exposes native shape flags without allocating properties or anchors
TMsoShapeContainer.HasPreservedObjectData identifies retained OBJ tail bytes; HasOrdinaryEmbeddedPictureObjectData checks that picture tails contain only recognized clipboard-format and zero picture-flag records, and rejects linked or unknown records without copying the payload
TMSOShapeTextBox.HasValidTextRuns checks stored TXO run boundaries and reserved fields without creating runs; TMsoDrawing.HasUnmodeledAppearance identifies native drawing data skipped by the typed parser, allowing capture to reject unresolved appearance explicitly
TXLSXRichTextRun.BoldSet, ItalicSet, StrikethroughSet, UnderlineSet, VertAlignSet and ColorSet distinguish inherited font properties from explicit overrides, including false flags, none, baseline and automatic colors; setters mark the property explicit even when its value equals the new run's initial default
TXLSXRichText.HasUnsupportedAppearance reports native rich properties that the typed run model cannot represent; portable capture and effective rich-text comparison reject such runs explicitly, while supported shared/inline run properties and whitespace retain their imported semantics
Effective rich-text comparison applies explicit false overrides before coalescing adjacent equal runs; inherited and explicitly cleared properties remain distinct during shared-string deduplication and supported XML roundtrips
XML character normalization
Version 2.384.536 normalizes literal CRLF and lone CR characters to LF before XML tokenization for UTF-8 and UTF-16 input, including line endings split across input reads
Literal tabs and line endings in attributes become spaces, while numeric character references retain their referenced characters; text and CDATA follow the physical-line normalization rule without converting an explicit carriage-return reference into LF
The reader retains its existing whitespace-text setting, namespace inspection and supported entity rules; these changes do not add DTD-based attribute typing or custom entity declarations
Rebuild dependent application and runtime-package units together when upgrading, because the XML scanner state layout has changed
TXMLReader.ResolveNamespaceUri(Prefix, Uri) resolves the current in-scope namespace binding without changing reader position, returning false when no binding exists; an empty prefix requests the default namespace, and raw QNames remain available for namespace-sensitive inspection
The immutable rich/scene records, capture-source extension and HXRSNP02 transfer contract are described in Portable headless output
Detached style and axis inspection
TXLSXWorksheet.ReadSemanticCellStyle(Row, Col) returns a detached TXLSSemanticCellStyle for valid one-based coordinates, resolving stored and packed styles, worksheet defaults, applicable style overlays, implicit date formats, indexed colors, and theme colors without materializing cells or changing style pools; the public call acquires a read lease and excludes conditional-format and table-style rules
TXLSXWorksheet.GetStoredAxisSpans(IsRow) returns TXLSXAxisSpans, an array of TXLSXAxisSpan records with inclusive one-based FirstIndex and LastIndex; it reports size, hidden, outline, and collapsed metadata footprints, preserves compact repeated-row height spans, and leaves the worksheet's effective default available through its ordinary properties
The returned spans describe stored metadata footprints rather than a disjoint normalized partition; applications comparing two axes can combine their first and last boundaries, then inspect the effective state once per resulting interval
TXLSXWorksheet.GetStoredStyleRegions returns detached TXLSXStyleRegions, an array of TXLSXStyleRegion records containing inclusive FirstRow, FirstCol, LastRow, and LastCol boundaries for compact virtual-formatting footprints; these footprints may overlap, and callers read their effective appearance with ReadSemanticCellStyle
TXLSXWorkbook.ReadSemanticFeatures(Kind, Sheet, MaxBytes, MaxItems) returns detached TXLSXSemanticFeatures, an array of TXLSXSemanticFeature records with a stable Key, canonical Definition bytes, and counted ItemCount; optional positive limits default to 64 MiB and 1,000,000 entries
TXLSXSemanticFeatureKind contains xlsxSemanticDefinedNames, xlsxSemanticDataValidations, xlsxSemanticConditionalFormats, xlsxSemanticTables, xlsxSemanticDrawings, xlsxSemanticPivotTables, xlsxSemanticPivotCaches, xlsxSemanticSlicers, xlsxSemanticSlicerCaches, xlsxSemanticTimelines, xlsxSemanticTimelineCaches, and xlsxSemanticCellImages
Defined names and the three cache kinds use workbook-wide scope and permit a nil sheet; the other kinds require a worksheet belonging to the workbook, rules and drawings retain their stored sequence, and returned arrays and buffers are caller-owned copies; these readers acquire read leases and inherit the typed coverage and explicit unsupported-data behavior described above
TXLSXWorksheet.ReadSemanticRichText(Row, Col, IncludePlainText, MaxBytes, MaxItems, ConsumedItems) returns detached canonical run bytes for one-based coordinates, or an empty buffer when no rich text exists and IncludePlainText is false; optional ConsumedItems: PInteger receives the captured run count, and plain-text capture retains packed storage
TXLSPivotCacheField.GroupItemTypes[Index] exposes the typed kind corresponding to GroupItemLabels[Index] and rejects an index outside the stored grouped-label domain
Formula metadata and Pivot query callbacks
TXLSGetCellFormulaText and TXLSCalculator.OnGetCellFormulaText read stored expression text using a one-based SheetIndex and zero-based Row/Col, returning lxOk or a typed error code and respecting formula-hidden protection; TXLSGetPivotTable and OnGetPivotTable locate a borrowed table using one-based SheetIndex and zero-based range coordinates
The workbook engines wire these optional callbacks in normal, read-only and isolated calculation contexts; callbacks do not recalculate targets, refresh Pivot sources or transfer ownership
TXLSPivotDataConstraint stores a FieldName and typed Item, with TXLSPivotDataConstraints collecting field/item pairs; TXLSPivotTable.GetDataValue queries one visible supported aggregate from a detached local table/cache snapshot and IntersectsQueryRange uses one-based worksheet bounds including modeled report-filter cells
TlxPivotQueryBudget receives work and memory estimates synchronously and returns whether evaluation can continue; EXLSPivotQueryBudget and EXLSPivotQueryUnsupported distinguish exhausted limits from unsupported cache or aggregate models
TXLSPivotCache.QueryModelIsComplete records decoded query readiness independently of BIFF raw replay completeness; QueryRecordsValid exposes imported record validity and SetQueryRecordValidity applies format-reader precedence without refreshing records
Explicit code-page bytes
| Member | Contract |
|---|---|
XlsEncodeCodePage(Text, CodePage, MaxBytes = -1) | Returns RawByteString with exact bytes in an explicit nonzero byte-oriented page, preserves embedded nulls, verifies Unicode round-trip identity, and raises EConvertError for unrepresentable text; a nonnegative MaxBytes keeps the longest complete-character prefix that fits, while -1 leaves length unbounded; validation covers the original text before truncation |
XlsDecodeCodePage(Bytes, CodePage) | Returns WideString from the explicit byte encoding and preserves embedded nulls; malformed byte sequences follow the installed decoder behavior; page 0 and UTF-16 page 1200 are rejected because this API does not infer an ANSI locale or handle a UTF-16 byte stream |
TXLSBlob.GetCompressedUnicodeString(Index, Count) | Returns exact BIFF8 compressed Unicode U+0000 through U+00FF code units, preserves embedded nulls, validates the requested byte range, and does not interpret those bytes using a code page |
TXLSBlob.AddRawString | Appends exact encoded bytes without an AnsiString code-page conversion and updates DataLength; an empty input appends no bytes |
TXLSCalculator.CodePage, TXLSFormula.FCodePage | Select the explicit legacy formula byte encoding, defaulting to CP1252; the owning Classic workbook synchronizes its calculator when initialized or when SetCodePage is called |
TXLSFontList.GetFont, TXLSNumFormatList.GetNumFormatBlob, TXLSStyles.GetStyleBlob | The optional CodePage argument defaults to 1252 and encodes BIFF5 text; BIFF8 output remains Unicode |
TMsoDrawing.StoreNotes | The optional CodePage argument defaults to 1252 and encodes pre-Unicode comment text; the existing BIFF5 ordinary-comment record size limit remains; this does not add author, rich-text or geometry fields absent from that record format |
TXLSCustomName.SetSourceData | The optional FileFormat and CodePage arguments identify imported raw NAME bytes and default to xlExcel97 and 1252; raw records are reused only when their format and legacy encoding match the requested output |
TXLSFormulatArrayItem.GetDataSize, TXLSFormulatArray.GetDataSize, TXLSFormulatArray.GetData, TXLSFormulatArrays.GetDataSize, TXLSFormulatArrays.GetData, TXLSCompiledFormula.GetExternalData | The optional ACodePage argument defaults to 1252; legacy string-array size and output use the same encoded-byte count, while BIFF8 strings remain Unicode |
Pass the returned RawByteString directly to AddRawString or a byte-oriented stream operation; converting it to a default AnsiString can recode its bytes on native FPC systems
Classic defined names and array-formula blocks
TXLSCustomName deferred compilation | ClearDefinition frees the compiled RefersTo AST while keeping the stored definition string and any raw imported NAME bytes, Compile rebuilds the AST from the stored definition and reports success, and GetCompiledFormula re-compiles automatically, so a cleared name re-resolves on its next read; PeekCompiledFormula returns the current AST without triggering that re-compile, and StoredDefinition exposes the unparsed definition source |
TXLSCustomName identity and flags | StoreIndex exposes the name's storage position within its collection, NameID its workbook-unique numeric identity as used by the calculation engine, and IsHidden and IsMacro read and write the BIFF NAME record hidden and macro flags |
TXLSFormulatArray.RowsCount, ColsCount | Report the row and column extents of the parsed array-formula block; both start at one and bound the per-cell item domain carried by the emission methods |
Classic font, format, and style pools
TXLSFontList stored font attributes | Indexed properties mirror the stored font key at a zero-based list index: Name, Size, ColorIndex, Bold, Italic, Strikethrough, and Underline join OutLineFont, Shadow, SubScript, SuperScript, Family, and CharSet for read-only inspection |
TXLSNumFormatList.AddValue, FmtExists | AddValue registers a format string and returns its index, mapping built-in format spellings onto their canonical ids and flagging date and time formats; FmtExists reports whether a custom format string is already registered |
TXLSNumFormatList.IsDateFormat, IsDateFormatValue | IsDateFormat reports whether the format stored at an index is flagged as a date or time format, while IsDateFormatValue tests a format string directly for date and time tokens |
TXLSStyles.AddStyle, AddBuiltinStyle | AddStyle registers a named custom cell style bound to an XF record index, and AddBuiltinStyle registers a built-in cell style by its built-in id together with the outline level used by row and column level styles |
TXLSStyles.BuiltinStyleName | Class function returning the canonical Excel built-in cell-style display name for built-in ids 0 through 53; out-of-range ids return an empty name so writers fall back to the raw builtin-byte form |
Package and binary storage helpers
TXLSXOpaquePackage | LoadWorkbookXmlMetadata captures workbook-level XML state, MarkAllPartsClean resets dirty flags, and WorkbookExtLstXml plus WorkbookRootAttributesXml expose preserved workbook XML fragments; IsDiscardedPart reports whether a part name was removed by a discard operation such as web-add-in cleanup |
TXLSFileStorage | Load, LoadFolder, Write, and WriteFolder transfer compound-file content, while LoadEmbeddingStorages populates an empty destination forest with only those embedding storages whose names carry an MBD prefix and eight hexadecimal characters and raises EXLSFilePayloadError when the forest already holds children and WriteEmbeddingStorages(Folder, Names) writes back just the children whose names the list selects; Child and Count enumerate child entries, each a TXLSFileItem — a named storage node whose TXLSFileStream subclass carries the stored bytes as a TXLSBlob with DataSize reporting the payload length |
TXLSBlob | Add appends another blob, while AddByte, AddWord, AddLong, AddDouble, AddString, and AddWideString append typed values; CopyData, CopyMem, FillByte, Write, Clear, Reset, and Dump manage content; Buff and DataLength expose storage |
TXLSBlobList | Append, AppendList, CopyData, and Write combine or emit entries; Entries and TotalSize expose list state |
TXLSWideStringBuilder | AddString appends text and Length reports the accumulated character count |
Drawing and workbook viewer additions
TXLSFillFormat | PictureFill configures a picture-backed shape fill, while FillType (type TXlsShapeFillType: ftAutomatic, ftNone, ftSolid, ftGradient, ftPicture) selects the fill kind (automatic, none, solid, gradient, or picture) that the writer emits |
TXLSShapes | AddScrollBar and AddSpinner create form controls — the returned TXLSScrollBar and TXLSSpinner objects expose the control geometry and linked cell, and the spinner adds Min, Max, and Inc step limits — while RegisterScrollBar and RegisterSpinner register controls loaded from a workbook |
TXLSWorkbookViewer | CanUndo and CanRedo report transaction history availability; ClearSelectedRange, CopySelectedRange, PasteSelectedRange, and PasteText operate on the selected range, while ReferencePickMode enables interactive cell or range reference selection |
TXLSWorkbookEditHistory | The headless content transaction engine in lxWorkbookViewer binds a borrowed classic or XLSX workbook and provides range protection preflight, Unicode text copy and paste, range clear, and one undo/redo transaction per operation; see headless editing transactions |
TXLSCellContentSnapshot | Both worksheet classes expose ReadCellContent(Row, Col) and RestoreCellContent(Snapshot) for detached native content capture and restoration at one-based coordinates in the originating worksheet; capture does not evaluate formulas, create absent cells, or materialize packed storage, and the immutable NativeData payload preserves rich text, formula caches, and cell style; direct restoration is a low-level operation whose caller must validate protection and structural boundaries |
Pagination, image output, and printing
XLSValidateCachedChartSceneModel, XLSRecordCachedChartScene | Preflights cached chart metadata without resolving cells and records bounded vector and text primitives for a detached chart in lxPortableChart, returning TXLSPortableSceneObjects and item, byte, and text accounting; the lxPagination entry points retain the same shared implementation for existing Windows callers; the current subset covers ordinary column, bar, line, scatter, pie, doughnut, and single-series area charts with one primary plot group, and recording requires validated native metadata, finite strictly ordered cache points, and an unattached chart model; see cached chart recording |
TXLSGraphicsBackend | DrawTiledImage paints a sheet background repeatedly across the clipped page region |
TXLSPaginationModel | CompactRangeMode, IncludeDrawings, IncludeGridlines, IncludeCellBorders, and PaintPageBackground control page content; RenderDPI, RenderColorMode, and RenderSession expose output resolution, color handling, and the active render session |
TXLSCellImageExporter | Measure calculates pixel dimensions for classic or XLSX ranges; ImageFormat, JpegQuality, MaxPixels, MaxBytes, IncludeObjects, IncludeGridlines, IncludeCellBorders, BackgroundColor, TransparentBackground, BeforePaint, AfterPaint, and PaginationModel configure and observe the render |
TXLSPageImageExporter | BeforePaint, AfterPaint, MaxPixels, MaxBytes, BackgroundColor, and TransparentBackground apply the same paint hooks and output safety limits to paged image export |
TXLSPrintDocument | PrintWorksheet, PrintWorkbook, and PrintAllVisibleSheets send classic or XLSX content to the VCL printer; FirstPage, PrintRangeOnly, Collate, Copies, OnBeforeNewPage, and OnAfterGeneratePage control the print job |
Classic chart models and worksheet chart objects
TXLSXChartSeries | LineVisible, LineColorRGB, and LineWidthPoints describe an independent series stroke; LineStyleSet, LineColorSet, and LineWidthSet preserve explicit settings, and EffectiveLineVisible resolves the legacy fill-only convention; MarkerFillSet and MarkerBorderSet distinguish explicit black from automatic marker colors, while line and scatter portable recording supports circle diameters from 2 through 72 points; color and width setters validate before mutation and obey workbook read leases |
TXLSChartSeries | AddTrendline and AddErrorBars create typed series annotations, while TrendlineCount and ErrorBarCount report their collection sizes; the existing MarkerSize field retains raw BIFF twips, while the read-only MarkerSizePoints getter returns that value divided by 20, including fractional point sizes |
TXLSChartAxis | HasAxcExtFlag tests one raw AXCEXT flag without requiring callers to decode the bit mask |
TXLSChartModel | AxisGroupCount reports the number of primary and secondary axis groups decoded from the chart |
TXLSCustomChart | AddAreaData appends a pre-built area item for save-time formula rebinding and ApplyDateAxisModel applies a typed date-axis model to the raw chart records; GetStoredRecordInfo reads a zero-based record ID and byte count without allocation, while ReadStoredRecord(Index, MaxBytes) checks the byte limit before returning detached bytes in TXLSChartStoredRecord, without evaluating formulas or modifying caches |
TXLSWorksheet | AddChartObject anchors a chart frame on the worksheet and connects it to the shared chart builder; GetXFIndex(Row, Col, ReplaceIndex) reports the effective style index for a cell and whether it came from a stored cell format; GetHeaderFooterVariants returns the typed header/footer page variants used by print adapters |
TXLSXChartLayoutResolver | TryResolve resolves one layout rectangle with optional size validation and ResolveChart calculates chart, title, legend, plot, and axis rectangles |
Typed chart decode model
GetChartModel and GetChartInfo recognize represented native auxiliary trendline ownership, attach the trend metadata to the actual parent and exclude auxiliary entries from the data-series count
This inspection contract is separate from typed builder reconstruction; ordinary raw-preserving workbook saves and qualified native Classic linear portable projection have their own verified paths
The decoded chart state is exposed as plain records and enums so inspection code never has to walk raw BIFF records: TXLSChartInfo carries the decoded chart summary with ChartType (a TXLSChartTypeFamily: cfBar, cfLine, cfPie, cfArea, cfScatter, cfRadar, cfDoughnut, cfSurface, cfBubble), Is3D, SeriesCount, and HasLegend, each series reports TXLSChartSeriesType, and TXLSChart3DState plus TXLSChart3DInfo describe three-dimensional views. TXLSChartAxisType (catCategory, catValue, catSeries, catDate) and TXLSChartLegendPosition classify axes and legends, while the date-axis model uses TXLSChartDateUnit (xcduDays, xcduMonths, xcduYears) and TXLSChartDateValues. TXLSCustomChart exposes the decoded model through TXLSChartInfo and the richer TXLSChartModel; trendline and error-bar annotations are typed objects (TXLSChartTrendline, TXLSChartErrorBars) reachable from each series. The model's public fields carry the chart family, 3-D state, titles, legend, per-series formulas and styling, and per-axis bounds and tick settings; see TXLSChartModel, TXLSChartSeries, TXLSChartAxis, and TXLSChartLegend
New Classic embedded-chart frames
TXLSWorksheet.AddChartObject initializes the new chart's width and height from the owning worksheet's metric callbacks, preserving the requested cell rectangle during saving instead of collapsing its ending anchor onto the starting cell
Qualified empty, populated and explicitly sized worksheet grids retain a nonzero frame through library save/reopen, actual native rendering and native save/reopen; existing explicit width and height edits retain their previous wire behavior
Chart data, chart sheets and other drawing leaves remain unchanged; this fix does not change worksheet metric serialization or promise exact dimension-getter round trips
Anchor fractions retain the existing BIFF quantization, and automatic plot layout and broader portable chart rendering remain separate contracts
Native Classic linear trendline authoring
TXLSWorksheets.AddChartSheet and TXLSWorksheet.AddChartObject create native linear trends for ordinary primary Line/Scatter groups containing only linear TXLSChartSeriesInfo.Trendlines declarations with both display-label switches disabled
Trend parents require resolved local source rectangles, matching category/value counts and at least two points; Pivot, 3D, secondary-axis and error-bar combinations remain outside this native authoring profile
Multiple parent series and multiple trends retain their own names, declaration order, automatic or finite fixed intercepts and finite nonnegative forward/backward periods through save/reopen and actual native saving
Public Regt=5 declares a linear trend and a NaN NumIntercept requests an automatic intercept; represent FDispEq and FDispRSqr as false for this profile
For public reconstruction, copy the represented names, source references and trend metadata from GetChartModel into a fresh declaration array and call the public authoring API; remove a leading = from decoded source formula text to satisfy the A1 reference-string contract
The maximum eligible parent count is 254 and the combined data/auxiliary series count is at most 255; invalid native parameters and owner-domain overflow refuse before attaching a partial chart
Any unsupported declaration or equation/R-squared display request keeps the whole group on its historical representation; that fallback preserves existing typed behavior and is not newly qualified as native trendline creation
This feature qualifies stored authoring and reconstruction; automatic embedded-chart frame sizing, native attached equation-label structures, broader regressions, independent trend paint and portable projection retain their separate contracts
Chart authoring records
Chart-sheet and builder authoring accepts plain records instead of object graphs: TXLSChartTrendlineInfo, TXLSChartErrorBarsInfo, TXLSChartDataLabelsInfo, and TXLSChartSeriesStyleInfo fill the series entries passed to TXLSWorksheets.AddChartSheet and the shared chart builder, and TXLSPivotChartInfo describes the pivot-chart framing used when a chart is attached to a pivot table
Classic chart fill inspection
TXLSCustomChart.GetChartModel decodes supported native OfficeArt property tables and tertiary property tables in GelFrame records, including properties following complex payload entries; the existing builder representation remains supported, and malformed table bounds leave the prior typed fill unchanged and report the unsupported record
Chart inspection validates the complete stored text and annotation payload before adding typed state: truncated trendline names or data-label separators report their record ID through _UnsupportedSemanticRecordID, while nil or undersized SeriesText headers report that record as unsupported for both BIFF5 and BIFF8; a declared series-text extent that exceeds its payload raises EReadError, frees the partial model and leaves the stored chart records unchanged
The marker getter and fill inspection preserve raw chart storage; the declared appearance capture path separately validates supported core charts, while unverified rich title or shape extension checksums remain unsupported
Bounded stored chart, string and font readers
TXLSChartStoredBytes is a detached byte array and TXLSChartStoredRecord contains RecordId and Data; these readers inspect retained source storage without creating a decoded chart model or evaluating formulas
| TXLSCustomChart.GetStoredRecordInfo | Returns a record ID and counted byte length for a zero-based record index without copying its payload |
| TXLSCustomChart.ReadStoredRecord | Copies one payload after validating the index and nonnegative MaxBytes; the default byte limit is High(Int64) |
| TXLSCustomChart.ReadStoredFormulaLeafInfo | Inspects a coherent stored BRAI leaf using the exact source calculator and nonnegative byte and text quotas; foreign calculators or translation owners return an unsupported leaf, and AllowUnboundBiff defaults to False |
| TXLSCustomChart.ReadStoredFormulaLiteral | Returns a detached literal only after the same provenance and quota checks; an unsupported leaf raises EInvalidOperation |
| TXLSCustomChart.SourceBiffVersion, SourceCodePage | Read-only provenance of the retained chart records |
| TXLSStringTable.GetStoredStringLength, ReadStoredString | Counts existing UTF-16 storage using the table's one-based string identity, then copies only when the nonnegative character quota covers it; invalid identities and incomplete UTF-16 storage reject |
| TXLSFontList.GetStoredNameLength, ReadStoredName | Checks the stored font key at the list's zero-based index before counting or copying its name under a nonnegative character quota |
| TXLSFontList Classic font proofs | RegisterClassicArial10Proof, RegisterClassicFontImportProof and RegisterClassicArial12BoldProof retain exact imported FONT records so a fixed Classic font profile keeps its exact import admission without reconstructing lost FONT fields; HasClassicPlainMetricFontProof, HasClassicArial10Proof and HasClassicArial12BoldProof report those proofs, and ReadClassicFontImportRecord(Index, MaxBytes) copies the stored record under a byte quota; CopyClassicFontImportProof(Source, SourceIndex, DestIndex) copies a proof between two lists when both slots exist and their represented font keys match — a matching key never manufactures the missing imported record |
| TMsoFbtOptItem.HasStoredUnicodeString | Checks bounded stored complex Unicode-string metadata without materializing a string |
| TMsoShapeContainer.HasOrdinaryChartObjectData | Checks stored chart object type, nonzero object identity, supported flags and absence of unknown object-tail data |
Shared string table maintenance and SST emission
TXLSStringTable in lxStringTable backs the classic workbook's shared strings; the members below cover reader-side registration, slot maintenance, and raw SST emission for round-trip saves
KeyExists, AddWithExtras | KeyExists reports whether a string already occupies a slot; AddWithExtras is the reader-side companion to Add that attaches the raw rgRun rich-text and rgExtRst phonetic payload to the entry without raising its reference count, because each referencing cell later restores the count through the normal add path |
Replace, ReplaceIndex | Replace drops one reference at the old slot, freeing it when its count reaches zero, and re-adds the text, returning the resulting slot; ReplaceIndex moves one reference from the old slot to the new slot without copying text |
AddSSTData, InitExtIndex | AddSSTData emits the raw SST payload into the writer's blob list; the overload taking a font-run remap table rewrites each FormatRun font index on the way out ([MS-XLS] §2.5.129) so rich runs follow save-time font reordering, while an empty table keeps legacy verbatim emission, and InitExtIndex numbers the ExtSST buckets over live slots before emission |
SlotCount, ExtIndex, ParsedExtSSTDsst, ParsedExtSSTItemCount, BiffSizeLimit | SlotCount is the one-based upper bound for slot iteration with deleted slots reading empty, ExtIndex resolves a slot to its ExtSST bucket number or -1 for a slot that is not live, ParsedExtSSTDsst and ParsedExtSSTItemCount retain imported EXT/SST header values, and BiffSizeLimit bounds each emitted record chunk — the classic writer sets it to 2080 bytes for BIFF5 and 8224 for BIFF8 |
PDF attachments, signatures, and HTML export
IXLSPDFAttachmentSource | WriteTo streams attachment bytes into the PDF export without requiring the exporter to own the source data |
TXLSPDFExport | AttachmentDuplicatePolicy selects duplicate-name handling, AttachmentSpoolThreshold controls attachment spooling, and DocumentLanguage writes the document language metadata |
TXLSPDFSignature | TextAlign (type TXLSPDFSignatureTextAlign: xlsPdfSigTextLeft, xlsPdfSigTextCenter, or xlsPdfSigTextRight), TextSize, TextColor, TextBold, and TextItalic configure the visible signature appearance |
TXLSHTMLExport | ViewMode (type TXLSHtmlViewMode: xhvmCurrent or xhvmSpreadsheet) chooses the HTML presentation, while HotTrackTargets (type TXLSHtmlHotTrackTargets, a set of TXLSHtmlHotTrackTarget: xhhtCells, xhhtRowHeadings, xhhtColumnHeadings) and HotTrackColor configure interactive cell and object highlighting |
TXLSXHtmlExportOptions | ViewMode, HotTrackTargets, and HotTrackColor provide the equivalent XLSX HTML export controls |
Calculation audit and workbook controls
TXLSCalculationAuditReport | Truncated reports an issue-limit truncation, StackTruncated reports call-stack frame truncation, and Issues indexes the recorded calculation issues |
TXLSUserFunctionRegistry | Generation changes whenever the registered user-function set changes, allowing cached formula bindings to be invalidated |
EXLSReportRecoverableData | Category identifies the recoverable report-data category presented to the caller |
IXLSWorkBook | ManualCalculationThreadCount limits the worker count used by manual calculation |
TXLSXDataValidation | HasUnknownImeMode reports an IME mode value that HotXLS preserved but does not recognize |
TXLSXTable | ColumnCalculatedFormulaArrayRaw and ColumnTotalsFormulaArrayRaw expose the original array-formula text for table columns |
Legacy PivotCache framing compatibility
TXLSPivotCache | RawBucketIndex identifies the source substream position, RawFramingIsLegacy identifies an old HotXLS framing, RawModelIsComplete reports whether the typed model represents every record, and CanUpgradeFraming reports whether opt-in typed re-emission is safe |
TXLSPivotCache | StreamId exposes the classic cache stream identity, SourceDataType exposes the classic source-data type, and RawHasStorageStream reports whether a loaded cache came from an independent PivotCache storage stream |
TXLSWorkbook | UpgradeLegacyPivotCacheFraming opts in to rewriting only legacy HotXLS cache framings whose typed model is complete; ordinary raw cache replay remains the default |
StreamId is written as the SXStreamID record ([MS-XLS] §2.4.303) and repeated as the SXDB header idstm field, which must equal it; SourceDataType is written as the SXVS record ([MS-XLS] §2.4.317: $0001 worksheet, $0002 external, $0004 consolidation, $0010 scenario) and repeated as the SXDB header vsType field, which must equal it. Caches built from a worksheet range start at the worksheet type, while caches read back from a file keep the value their substream carried, so the BIFF writer never leaves an SXDB field naming a record it did not emit; RawHasStorageStream marks a cache loaded from its own storage stream whose workbook-global descriptor precedes the cached records
Clipboard integration and paste options
TXLSPasteOption = (xlpoValuesOnly, xlpoInsertRows, xlpoInsertCols);
TXLSPasteOptions = set of TXLSPasteOption;
function XLSGetClipboardText: WideString;
function XLSSetClipboardText(const Text: WideString): Boolean;
function XLSSetClipboardTextAndHtml(const Text: WideString;
const Html: AnsiString): Boolean;
function XLSBuildHtmlClipboard(const Html: AnsiString): AnsiString;
function XLSEncodeClipboardField(const Text: WideString): WideString;
function XLSClipboardHasText: Boolean;
function XLSParseClipboardGrid(const ClipboardText: WideString;
Loader: TXLSCSVLoader): Boolean;
function XLSClipboardHasXmlSpreadsheet: Boolean;
function XLSGetClipboardXmlSpreadsheet: WideString;
function XLSParseXmlSpreadsheet(const XmlText: WideString;
Loader: TXLSCSVLoader): Boolean;
function XLSClipboardHasBiff8: Boolean;
function XLSGetClipboardBiff8: AnsiString;
function XLSReadClipboardPasteData(out Biff8: AnsiString;
out Text: WideString): Boolean;
function XLSSetClipboardBiff8(const Biff8: AnsiString;
const Text: WideString; const Html: AnsiString = ''): Boolean;
PasteFromClipboard overloads: xlpoValuesOnly keeps the cached values of formula cells and skips formats and merges, while xlpoInsertRows and xlpoInsertCols shift existing content before the block landsCF_UNICODETEXT (falling back to CF_TEXT through the current ANSI code page), XLSSetClipboardTextAndHtml writes text and a styled HTML Format payload in one transaction, XLSBuildHtmlClipboard computes the CF_HTML byte offsets for a document or fragment, and XLSEncodeClipboardField quotes one tab-separated field. XLSParseClipboardGrid parses clipboard text as tab-separated rows with the same type sniffing TXLSCSVLoader uses for CSV, XLSParseXmlSpreadsheet runs the same loader fill over a SpreadsheetML 2003 payload fetched with XLSGetClipboardXmlSpreadsheet, and the Biff8 helpers detect and read the native stream Excel itself places on the clipboard so pasted data keeps values, formulas, and formatting without text lossXLSReadClipboardPasteData captures the Biff8 stream and the Unicode text in a single clipboard lock, so a paste never has to re-open the clipboard between the two reads and loses neither format to a concurrent holder. XLSSetClipboardBiff8 is the matching write side: it places the BIFF8 compound-file stream, tab-delimited Unicode text, and an optional CF_HTML payload in one transaction — pass an empty Text or Html to skip either companion format, while the Biff8 part is requiredCell display text resolution
TXLSCellDisplayMode = (xcdmFormattedValue, xcdmFormulaText,
xcdmSuppressedZero);
TXLSCellDisplayOptions = record
ShowFormulas: Boolean;
ShowZeros: Boolean;
SheetProtected: Boolean;
FormulaWidthFactor: Double;
DateSerialZero: Double;
end;
TXLSCellDisplayInput = record
HasFormula: Boolean;
FormulaHidden: Boolean;
IsNumericZero: Boolean;
FormulaText: WideString;
FormattedText: WideString;
end;
TXLSCellDisplayResult = record
Mode: TXLSCellDisplayMode;
Text: WideString;
TreatAsText: Boolean;
EffectiveWidthFactor: Double;
end;
function XLSDefaultCellDisplayOptions: TXLSCellDisplayOptions;
function XLSNormalizeFormulaDisplayText(const FormulaText: WideString): WideString;
function XLSResolveCellDisplay(const Options: TXLSCellDisplayOptions;
const Input: TXLSCellDisplayInput): TXLSCellDisplayResult;
XLSResolveCellDisplay directly with their own input records; XLSDefaultCellDisplayOptions returns the canonical defaults and XLSNormalizeFormulaDisplayText normalizes a formula string for displayClassic data validation objects
TXLSDataValidationType = (xlsDvAny, xlsDvWhole, xlsDvDecimal, xlsDvList,
xlsDvDate, xlsDvTime, xlsDvTextLength, xlsDvCustom);
TXLSDvErrorStyle = (xlsDvErrStop, xlsDvErrWarning, xlsDvErrInformation);
TDVRange = class; { one validation rule over one or more ranges }
TDVRangeList = class; { the per-sheet rule collection }
TDataValidation = class; { one validation rule with its ranges and messages }
TDataValidator = class; { engine that checks edits against the rules }
TXLSWorksheet.Add*Validation helpers create TDVRange rules in the sheet's TDVRangeList; each rule carries its TXLSDataValidationType, bounds, input and error messages, and TXLSDvErrorStyle. TDataValidator evaluates an edit against the rules and reports whether the value is acceptable, which is also the check behind Excel's own validation promptsTDVRange | row1, row2, col1, and col2 expose the zero-based inclusive bounds; IsContainRow tests one row and IsContainRange tests whether a rectangle overlaps this one; ExtendRange grows the bounds to include another rule's rectangle, ShiftRange offsets them by a row and column delta and answers False when the rectangle moves entirely above or left of the sheet, and AddData appends the four bounds to a binary blob |
TDVRangeList | Range, Count, and IsEmpty expose the collection; ClearRow, ClearCol, and ClearRange remove the covered parts of every rule and split a rule when the cleared area falls inside it; MoveRanges shifts the covered parts and drops rules that become empty; Store serializes the remaining rectangles |
TDataValidation | Ranges holds the rule's TDVRangeList; ValidationType, Operator_, and ErrorStyle report the rule kind, comparison, and alert icon; AllowBlank, ShowDropDown, ShowInputMessage, ShowErrorMessage, ImeMode, and HasUnknownImeMode expose the stored entry options, where ShowDropDown true means the list arrow is shown; PromptTitle, PromptText, ErrorTitle, and ErrorText are the messages set through SetPrompt and SetError; Formula1 and Formula2 expose the compiled bound formulas; IsEmpty is true when no range remains, and ClearRow, ClearCol, ClearRange, and MoveRanges edit the rule's ranges |
TDataValidator | AddListValidation creates an inline or range-referenced list rule and answers its zero-based index in the collection; AddValidation creates a typed whole, decimal, date, time, text-length, or custom rule and returns the rule object, or nil when a formula cannot compile; FindAt returns the first rule covering a zero-based cell; ClearRow, ClearCol, ClearRange, and MoveRange maintain the rules through structural edits, dropping a rule whose ranges become empty; BindStoredFunctionNames binds the workbook calculator's user-function names to every rule formula before a BIFF8 save; Count and Items expose the collection, and AssignFrom deep-copies rules from another sheet |
Indexed color scanning and resolution
TXLSIndexedColorKind = (xickPalette, xickAutomatic, xickSystem, xickInvalid);
TXLSSystemColorRole = (xscrNone, xscrWindowText, xscrWindowBackground,
xscrChartText, xscrChartBackground, xscrChartNeutral, xscrToolTipText);
TXLSIndexedColorResolution = record
Kind: TXLSIndexedColorKind;
RawIndex: Int64;
PaletteSlot: Integer;
SystemColorRole: TXLSSystemColorRole;
ARGB: LongWord;
HasResolvedColor: Boolean;
end;
TXLSNearestIndexedColorMatch = record
InputARGB: LongWord;
ColorIndex: Integer;
PaletteSlot: Integer;
ARGB: LongWord;
DistanceSquared: Double;
ExactMatch: Boolean;
end;
TXLSIndexedColorUsageKind = (xicukFont, xicukFillForeground,
xicukFillBackground, xicukGradient, xicukBorder, xicukConditionalFormat,
xicukChart, xicukShape, xicukComment, xicukWorksheet, xicukOther);
ResolveIndexedColor, NearestIndexedColor, and ScanIndexedColorUsage methods: a resolution reports which of the four TXLSIndexedColorKind sources an indexed token came from together with its palette slot, system-color role, and normalized ARGB, a nearest match adds the squared RGB distance and exact-match flag, and the usage scan tags every consumer category that locks a palette slot. The library keeps an internal TXLSIndexedColorMatcher cache keyed by palette generation — FindNearest answers nearest-color queries from it and UpdateSlot patches one palette slot — so repeated resolutions stay allocation-freeA1 reference helpers
function XLSA1CellRef(ARow, ACol: Integer): WideString;
function XLSTryParseA1CellRef(const ARef: WideString;
out ARow, ACol: Integer): Boolean;
function XLSTryParseA1RangeRef(const ARef: WideString;
out ARow1, ACol1, ARow2, ACol2: Integer): Boolean;
False for malformed input instead of raisingSee also
- Additional classic XLS API members
- Advanced XLSX API members
- Sparse outline geometry
- Formula trace and audit
- Workbook viewer
Interactive form controls
See seven public form-control families for the current model, linked-state, XLSX/ODS and native interaction contract