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 which do not need 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 whilst keeping loaded criteria and dropdown shapes, and disregards nonpositive or reversed bounds plus 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 linked to 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 picking 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 pick automatic minimum and maximum endpoints; IsIndexedColor, IndexedColorIndex, and ClearIndexedColor manage the palette-index bar colour |
TXLSIconSetSpec | ThresholdEqualsInclude selects inclusive or exclusive comparison for each icon threshold |
TXLSCfValue | IsIndexedColor and IndexedColorIndex report a threshold colour stored as a legacy palette index, ClearIndexedColor removes that form again, and theme or literal colours remain available through the existing accessors |
TXLSCfValue, TXLSDataBarSpec, TXLSColorScaleSpec, TXLSIconSetSpec, and TXLSDxfStyle accept AttachWriteGuardOwner, attaching 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 colours, 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 colour members; each assignment acquires the write guard and marks the rule dirty for re-emission; differential fills can also carry an x14 gradient by way of 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 logs 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 every 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 that rectangle and ellipse/line primitives use; each point reports X and Y. Coordinates are normalised to the icon box, and colours follow 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 materialisation; 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 behaviour |
Import validation schemas
Small Business edition: Import validation (lxImportCheck) comes with HotXLS Small Business and Enterprise (plus their DCU editions), in the HotXLSSB runtime package for RAD Studio and HotXLSLazSB.lpk for Lazarus; the trial build ships with it subject to the usual trial restrictions
TXLSImportCheck from lxImportCheck validates a TXLSXWorksheet against rules owned by the application; it inspects 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, whilst a positive LastRow can include absent cells without creating them; columns must lie 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, whilst irRequired reports them; uniqueness retains the distinct policies described below; nonempty whitespace still counts as a value; a number does not qualify as a Boolean, a date does not qualify as an ordinary number, and a numeric-looking string stays 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 any worksheet validation starts
Number bounds compare numeric values whilst 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 behaviour, so use anchors such as ^...$ when the complete text must match; an invalid regex turns off 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 the accepted import schema calls for one; the mode affects validation only and never alters 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 since that interval denotes the fictitious leap day; the 1904 system maps serial zero to January 1, 1904
Date bounds include the 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 whole of the 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 across 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 in ordinal order |
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 normalisation, 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 leaves that row out of 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 together with the first matching row via FirstDuplicateRow
The existing single-column irUnique retains its text-based, case-insensitive matching behaviour 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; mismatched incompatible categories fail even for icNotEqual; string comparisons distinguish composed and decomposed Unicode, preserve embedded null characters, and order shorter prefixes first; 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, whilst 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 from their stored cached values; a formula lacking a stored cached result reports ivFormulaCacheMissing, and an error result reports ivCellError; explicitly recalculate before checking when fresh formula results are required; validation never reaches external sources, alters formula definitions, or evaluates 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 refused by the read lease; callback exceptions propagate and the lease is freed again for subsequent operations
Check never annotates, deletes rows, or materialises packed values; use Annotate after checking to apply red fonts and append error text to existing comments, or else explicitly call KeepOnlyViolations to remove nonviolating rows and create a correction workbook; these methods alter the supplied worksheet, so call them on the intended workbook after studying the report
Validation borrows the worksheet and workbook for the synchronous call; it does not take over the caller's object ownership or require an interface-owned workbook; a read lease shields the 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 authorise 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 whilst leaving caches and workbook semantics unchanged. RecalcAndVerifyEx runs the deep audit: it evaluates every formula once via the dependency graph into an isolated result overlay so dependent cells read this pass rather than 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 across an unchanged workbook structureAbsoluteTolerance and RelativeTolerance control mismatch reporting rather than 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 allowed; 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 alters 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 it accepts the same options record. FormulaIsVolatile reports whether a formula would force a recalculation on each 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 following the calculator convention), AuditOverlayRead and AuditOverlayHash query it, and AuditOverlayClear empties the layer. Overlaid values come back from 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, whilst 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 serialise 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, whilst 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 stay lossless, and explicit assignments emit only canonical values
ExportObjectPlaceholders requests the same low-cost policy without decoding image payloads or building chart scenes
xlsodmHideAll prevents drawing collection and object-driven range expansion before rendering begins; workbook conversion transports 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 smaller 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 gives back 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, a measurement service, and bounded operation-local metric cache; CreateXLSRenderGeometry uses GDI, whilst 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 whilst MaximumDigitWidthPixels, ColumnWidthToPixels, PixelsToColumnWidth, PointsToPixels, PixelsToPoints, and UsableCellWidthPixels provide the shared geometry conversions
MarkSheet measurement, whilst TXLSPaginationModel.Build captures one service for the selected RenderBackend; PDF, SVG, bitmap, print-preview, workbook-viewer, and HTML entry points select their own backend ahead of output, changing workbook calibration cannot mutate an existing snapshot, and output never writes worksheet dimensions
xlsrgbHtml service, whilst an incremental TXLSXHtmlExportSession captures once in BeginExport and reuses that snapshot for every sheet; 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) out of 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 normalised 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 calls for shaping or resolved fallback runs, the caller supplying an explicit locale
Query these optional interfaces through an IXLSRenderGeometry instance with Supports
The existing IXLSRenderGeometry and IXLSRenderFontMetricSource interfaces retain their method order and identifiers
These APIs report physical font metrics within a single captured rendering context They give no text width, glyph positions, ink bounds, or line box for a target application They set no worksheet dimensions and define nothing about Excel's row-height, font-fallback, locale-selection, or default-grid policy Keep the source font, displayed text, locale, and layout policy with their own owners when the results feed 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 behaviour, 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 builds a no-wrap GDI-compatible DirectWrite layout from the explicit locale and the verified primary font Only actual glyph runs that account for the whole source text are accepted, with no overlapping source ranges and no unresolved glyph indices Each accepted run's physical face and size are mapped back into a GDI measurement context and checked by physical face and font-file identity In the returned record every field carries a separate maximum across the primary font contribution and all accepted run contributions Those independent maxima need not belong to one face, and they are neither a measured text bounding rectangle nor a complete application's line-height calculation
An empty string gives back 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
After a failed shaped operation, neither method falls back on a nominal-only result
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 missing; 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 runs past 32767 UTF-16 units, or the geometry calibration or cache-capacity constructor argument falls outside its supported domain |
EInvalidOperation |
The requested primary family was substituted or is unavailable, the selected font context has changed, or an unexpected native measurement or callback failure arose |
The Boolean result is not a licence to suppress exceptions
In particular, an unavailable requested primary family raises an exception rather than silently measuring a substitute family
The used-budget outputs can carry charges from a refused or failed attempt and must never be read as successful metric output
Use AMetrics only after a True result
Text must be well-formed UTF-16 and must already be single-line text fit for the caller's layout
C0 controls, among them tab and line breaks, NEL (U+0085), line separator (U+2028), and paragraph separator (U+2029) raise an input exception
The full spelling is validated before an early missing-glyph result can come back
The shaped method additionally caps text at 32767 UTF-16 code units
The font family name must hold 1 through 255 UTF-16 units without C0 controls, and the point size must be finite and lie between 1/64 and 4096, inclusive
The descriptor also carries the existing bold, italic, underline, strikeout, and charset fields
The shaped locale name must hold 1 through 85 UTF-16 units without characters below U+0021, and the guarded Windows path checks that the locale name can be used
Take the locale from the caller's actual rendering contract rather than presuming 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 decides the primary GDI pixel size chosen from the point-size descriptor
Height correction bears on height, ascent, descent, and external leading; width correction bears on average character width
EmHeightPixels keeps the physical em height without applying height correction
These single-line font metrics take no account of cell margins, multi-line spacing, or implicit-column screen-scaling emulation
Create a fresh operation context when the font environment or intended calibration changes
Call the matching Bounds helper ahead of measurement to get conservative per-call byte and work reservations for the exact text, font, and locale The helpers inspect lengths only: they open no native context, copy or scan no text, and validate neither spelling nor descriptor values The execution method still validates those inputs Use a caller-selected aggregate budget for repeated invocations and account for each call's returned charges
AUsedBytes reports charged reservations, native-context allowance included, not a measured process-memory peak
AUsedWork reports the controlled validation, scan, glyph, range, and identity-comparison work this operation charged
Neither limit is a guarantee of the Windows font-cache peak or of the system shaping engine's internal allocation and work
Exhausted supplied quotas raise an exception; unsupported finite face or run representations return False
The general geometry cache capacity is no substitute for 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
Call these helpers from application code instead of duplicating their implementation formulas
Finite shaped representation
The shaped operation takes up to 256 nonempty, disjoint source ranges and 16 distinct physical face/size tuples in one call A run may hold at most 16 glyphs per source UTF-16 unit plus 16 extra glyphs Physical identity comparison allows 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 get refused by this single-line capability
Neither API takes variation-axis coordinates
The nonempty shaped-run metric path turns away font resources with an fvar table, since file and face identity alone cannot pin down their variation-axis coordinates
Nominal coverage establishes no axis-specific variation instance either
The empty-string primary-metric shortcut proves nothing about nonempty variable-font support
Platform and build scope
The GDI factory is Windows-specific and keeps its existing unsupported-platform behaviour 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 lacking that guard, the optional methods still validate their input and quotas and return False without ever constructing the guarded native context
The optional interface can therefore be present even where the native measurement path is unavailable
DirectWrite must likewise be available at runtime
That portable render geometry implementations expose these optional interfaces is not implied
The qualified evidence for this addition comes from the Windows Win64 command-line compiler and its pinned Windows font environment It establishes nothing about 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 rather than mixing old and new unit files
Bounds and method examples
The following helpers query the optional interfaces and reserve every call ahead of measurement Invalid input, exhausted quotas, and unexpected native failures propagate out of them as exceptions The calibration and generation come from 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 where that suits the caller's policy
Do not swap a shaped refusal for 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 no more than 4096 UTF-16 units on the existing TXLSRenderFont, an explicit locale and the geometry's captured calibration
Query the capability on IXLSRenderGeometry with Supports and call XLSCellLineMetricBounds before measuring
The result carries source-owned em and descent components together with separately named layout height and baseline observations The producer value says how those observations were obtained This capability sets no worksheet row heights and selects no spreadsheet application's font, locale or grid policy
Version 2.384.530 improves source ownership when text is split across separate shaping runs
The method considers every boundary-aligned source occurrence and assigns a range only where a forced choice stays compatible with complete, disjoint source coverage
A fixed point with unresolved alternatives returns False with zero metrics, even where a costlier search might settle on a unique assignment
Source-range preparation and shaping keep cumulative work charges ahead of controlled operations and preserve the existing byte and work limits
A quota failure supplies no 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 carry complete, unambiguous source ranges, cluster mapping, glyph indices and physical font ownership | The union of positioned physical font-cell boxes 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 as converted from DIPs into captured measurement pixels |
xlsclpEmptyPrimary | An empty source has independently verified primary physical font metrics and lays claim to no source glyph | The primary GDI font-cell height and ascent |
EmHeightPixels and DescentPixels keep 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 separate quantities
Neither the layout height nor any sum of components amounts to 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 at both creation and measurement time
The caller owns a suitable, consistent DPI-awareness context; capturing a DPI value on its own changes nothing about 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 behaviour or identify an application's UI language
An optional interface may be present even when its guarded native capability returns False
Input must be normalised 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 hands over the small observation record for this captured context
An unavailable finite capability returns False with zeroed 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 behaviour
Use the metrics only after a True result, and keep charges from refused or failed attempts under the caller's budget owner
Per-call reservations and qualification
XLSCellLineMetricBounds is a pure reservation helper and turns away more than 4096 UTF-16 units before any arithmetic
Reserve the returned byte and work allowances ahead of a call
They cover explicit owned buffers and charged operations, not the operating-system font-cache or shaping peak
The reported charges can land below the conservative reservation and are not an aggregate before-work budget callback
A caller needing a cumulative before-work budget must own enough allowance for each operation
The qualifying execution ran on Win64 RAD Studio 37, actual 120 DPI, the pinned font environment, the zh-CN Windows user locale and identity corrections That execution newly qualifies no other compilers, architectures or locales Known regression examples are neither a new blind holdout nor native application acceptance When adopting the new public unit interface, rebuild the affected compiled-unit dependency closure coherently
Query and measurement example
The calling operation supplies a geometry object created under its captured, supported device context The example preserves Boolean unavailability and lets invalid input, quota exhaustion and unexpected native failures 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 a 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) swaps out the default sink — parsed cells go to the callback and no worksheet is needed |
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 synchronised 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) comes with HotXLS Small Business and Enterprise (plus their DCU editions), in the HotXLSSB runtime package for RAD Studio and HotXLSLazSB.lpk for Lazarus; the trial build ships with it subject to the usual trial restrictions
TXLSXWorkbookCompare in lxCompare compares two TXLSXWorkbook instances without recalculating formulas or modifying either workbook; sheets are paired by case-insensitive name, and sheet order changes on their own do 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 merged ranges that were added or removed
Literal comparison tells numbers, text, Boolean values, dates, errors, and blanks apart: 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, whilst distinct Int64 values remain distinct during exact comparison
lcoFormulaCachedResults | For cells whose formula text matches, compares the existing cached result and tells a missing or invalidated cache apart from an available one; loaded and calculated caches holding 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 colours 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 matching the effective default compares equally with 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 never creates differences |
lcoDataValidations | Compares validation definitions in stored order, including normalised 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 behaviour, target ranges, formulas, differential styles, and supported colour-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, whilst colour-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 span images, text boxes, charts, groups, complete typed slicer views, and typed timeline views, and opaque or unsupported drawing nodes raise 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 materialising cells |
lcoRichTextRuns | Compares effective run fonts and text at matching stored text cells, inherits the base font for omitted run properties, disregards 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 materialisation 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 stay distinct, dates retain binary64 precision, and cache IDs and shared-member slot order never 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; the 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 leave out 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 keep 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 building 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 separate AbsoluteTolerance and RelativeTolerance setters apply the same validation
Numeric literal and numeric cache values compare equally when their absolute difference is within AbsoluteTolerance or their difference relative to the larger absolute value is at most RelativeTolerance; a threshold of zero keeps exact equality, the relative calculation avoids overflow for extreme opposite values, and tolerance never coerces text or applies 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 whilst 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 hold the compared size, hidden, outline, and collapsed state, with Ref naming 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 whilst an absent side carries an empty string
lckRichTextChanged identifies a changed run definition at its cell coordinate and takes canonical run fingerprints in LeftText and RightText; numeric tolerance applies to cell literals and formula caches, whilst 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, whilst 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 covered by ordinary cell comparison and lcoCellStyles, so switch on both style options to inspect stored cells and blank areas together
Describe formats one entry, whilst Report(List) appends the formatted entries to a caller-owned TStrings; a typed value change includes type labels when the types differ, and results are sorted 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, whilst 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, whilst 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 normalises through the semantic formula parser, whilst Pivot calculated formulas retain their stored definition text
Table filters accept supported custom, value-list, date-group, colour, icon, dynamic, and top-count shapes and sort conditions; independent filter columns and value-set entries normalise their order, Boolean defaults and numeric spellings normalise, 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, whilst member selections and recognised 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 unmodelled 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, whilst modelled slicer cache bindings remain supported
TSimpleDomNode.RawName exposes the original element QName alongside the reader-normalised Name, permitting 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 keeps 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, whilst 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 recognised 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, letting capture 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 colours; 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, whilst 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 stay distinct during shared-string deduplication and supported XML roundtrips
XML character normalisation
Version 2.384.536 normalises literal CRLF and lone CR characters to LF before XML tokenisation 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 normalisation rule without converting an explicit carriage-return reference into LF
The reader keeps its existing whitespace-text setting, namespace inspection and supported entity rules; these changes add no DTD-based attribute typing and no custom entity declarations
When upgrading, rebuild dependent application and runtime-package units together, because the XML scanner state layout has changed
TXMLReader.ResolveNamespaceUri(Prefix, Uri) resolves the current in-scope namespace binding without altering reader position, returning false when no binding exists; an empty prefix requests the default namespace, and raw QNames stay 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 colours, and theme colours without materialising 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, keeps compact repeated-row height spans, and leaves the worksheet's effective default reachable through its ordinary properties
The returned spans describe stored metadata footprints rather than a disjoint normalised 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 carrying inclusive FirstRow, FirstCol, LastRow, and LastCol boundaries for compact virtual-formatting footprints; such footprints can overlap, and callers read their effective appearance with ReadSemanticCellStyle
TXLSXWorkbook.ReadSemanticFeatures(Kind, Sheet, MaxBytes, MaxItems) returns detached TXLSXSemanticFeatures, an array of TXLSXSemanticFeature records carrying a stable Key, canonical Definition bytes, and a 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 behaviour 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 is present 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 honouring formula-hidden protection; TXLSGetPivotTable and OnGetPivotTable locate a borrowed table through one-based SheetIndex and zero-based range coordinates
The workbook engines wire these optional callbacks in normal, read-only and isolated calculation contexts; callbacks never recalculate targets, refresh Pivot sources or take over 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 or cache snapshot and IntersectsQueryRange uses one-based worksheet bounds including modelled report-filter cells
TlxPivotQueryBudget receives work and memory estimates synchronously and reports whether evaluation can continue; EXLSPivotQueryBudget and EXLSPivotQueryUnsupported distinguish exhausted limits from unsupported cache or aggregate models
TXLSPivotCache.QueryModelIsComplete records decoded query readiness separately from 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, keeps embedded nulls, verifies Unicode round-trip identity, and raises EConvertError for unrepresentable text; a nonnegative MaxBytes keeps the longest complete-character prefix that fits, whilst -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 behaviour; 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 never interprets 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 synchronises its calculator when initialised 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 still applies; no author, rich-text or geometry fields absent from that record format are added |
TXLSCustomName.SetSourceData | The optional FileFormat and CodePage arguments identify imported raw NAME bytes and default to xlExcel97 and 1252; raw records are only reused 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, whilst 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 whilst 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 hidden and macro flags of the BIFF NAME record |
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 that the emission methods carry |
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 sit alongside 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 canonical ids and flagging date and time formats; FmtExists reports whether a custom format string is registered already |
TXLSNumFormatList.IsDateFormat, IsDateFormatValue | IsDateFormat reports whether the format stored at an index is flagged as a date or time format, whilst 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 that row and column level styles use |
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 on 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, whilst LoadEmbeddingStorages fills an empty destination forest with just those embedding storages whose names carry an MBD prefix and eight hexadecimal characters and raises EXLSFilePayloadError where the forest already holds children; WriteEmbeddingStorages(Folder, Names) writes back just the children 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, whilst FillType (type TXlsShapeFillType: ftAutomatic, ftNone, ftSolid, ftGradient, ftPicture) selects the fill kind (automatic, none, solid, gradient, or picture) that the writer will emit |
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 — whilst 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, whilst ReferencePickMode enables interactive cell or range reference selection |
TXLSWorkbookEditHistory | The headless content transaction engine in lxWorkbookViewer binds a borrowed classic or XLSX workbook and offers 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 materialise 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 check 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 within lxPortableChart, returning TXLSPortableSceneObjects and item, byte, and text accounting; the lxPagination entry points keep 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, colour 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 colours, whilst line and scatter portable recording supports circle diameters from 2 through 72 points; colour and width setters validate before mutation and obey workbook read leases |
TXLSChartSeries | AddTrendline and AddErrorBars create typed series annotations, whilst TrendlineCount and ErrorBarCount report their collection sizes; the existing MarkerSize field retains raw BIFF twips, whilst 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, whilst 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 hooks it up to the shared chart builder; GetXFIndex(Row, Col, ReplaceIndex) reports the effective style index for a cell and whether a stored cell format supplied it; 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 leave auxiliary entries out of the data-series count
This inspection contract sits apart 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 needs 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, whilst 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, plus 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, keeping the requested cell rectangle intact during saving instead of collapsing its ending anchor onto the starting cell
Qualified empty, populated and explicitly sized worksheet grids hold on to a nonzero frame through library save/reopen, actual native rendering and native save/reopen; existing explicit width and height edits keep their previous wire behaviour
Chart data, chart sheets and other drawing leaves stay unchanged; this fix alters neither worksheet metric serialization nor the promise of exact dimension-getter round trips
Anchor fractions keep 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 holding only linear TXLSChartSeriesInfo.Trendlines declarations with both display-label switches switched off
Trend parents call for resolved local source rectangles, matching category/value counts and at least two points; Pivot, 3D, secondary-axis and error-bar combinations stay outside this native authoring profile
Multiple parent series and multiple trends keep 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 asks for an automatic intercept; represent FDispEq and FDispRSqr as false for this profile
For public reconstruction, take the represented names, source references and trend metadata from GetChartModel into a fresh declaration array and call the public authoring API; strip 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 tops out at 255; invalid native parameters and owner-domain overflow refuse before a partial chart is attached
Any unsupported declaration or equation/R-squared display request keeps the whole group on its historical representation; that fallback preserves existing typed behaviour and is not newly qualified as native trendline creation
This feature qualifies stored authoring and reconstruction; automatic embedded-chart frame sizing, natively attached equation-label structures, broader regressions, independent trend paint and portable projection keep their separate contracts
Chart authoring records
Chart-sheet and builder authoring works from 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 applied when a chart is attached to a pivot table
Classic chart fill inspection
TXLSCustomChart.GetChartModel decodes supported native OfficeArt property tables plus tertiary property tables in GelFrame records, including properties following complex payload entries; the existing builder representation stays 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 via _UnsupportedSemanticRecordID, whilst nil or undersized SeriesText headers report that record as unsupported under 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, whilst 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 building a decoded chart model or evaluating formulas
| TXLSCustomChart.GetStoredRecordInfo | Returns a record ID and counted byte length for a zero-based record index without duplicating 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 yield an unsupported leaf, and AllowUnboundBiff defaults to False |
| TXLSCustomChart.ReadStoredFormulaLiteral | Supplies a detached literal only once the same provenance and quota checks pass; 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 are rejected |
| TXLSFontList.GetStoredNameLength, ReadStoredName | Checks the stored font key at the list's zero-based index before counting or copying its name within a nonnegative character quota |
| TXLSFontList Classic font proofs | RegisterClassicArial10Proof, RegisterClassicFontImportProof and RegisterClassicArial12BoldProof hold on to 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 fabricates the missing imported record |
| TMsoFbtOptItem.HasStoredUnicodeString | Checks bounded stored complex Unicode-string metadata without materialising a string |
| TMsoShapeContainer.HasOrdinaryChartObjectData | Checks stored chart object type, nonzero object identity, supported flags and the absence of unknown object-tail data |
Shared string table maintenance and SST emission
TXLSStringTable in lxStringTable underpins 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, since each referencing cell later restores the count through the normal add path |
Replace, ReplaceIndex | Replace removes 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 duplicating 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, whilst 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 where deleted slots read as 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 fixes it at 2080 bytes for BIFF5 and 8224 for BIFF8 |
PDF attachments, signatures, and HTML export
IXLSPDFAttachmentSource | WriteTo streams attachment bytes into the PDF export without the exporter having 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, whilst 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, so cached formula bindings can 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 recognise |
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 arrived 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 stays 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, whilst 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 comes before 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, whilst 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 its 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 writer. XLSSetClipboardBiff8 is the matching write side: it puts 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, whilst 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 normalises 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 }
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 that stands behind Excel's own validation promptsTDVRange | row1, row2, col1 and col2 expose the zero-based inclusive bounds; IsContainRow tests a single row, while IsContainRange tests whether a rectangle overlaps this one; ExtendRange grows the bounds to take in another rule's rectangle, ShiftRange offsets them by a row and column delta and answers False when the rectangle ends up 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 each rule and split a rule where the cleared area lies inside it; MoveRanges shifts the covered parts and drops rules that become empty; Store serialises 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 a true ShowDropDown means the list arrow is shown; PromptTitle, PromptText, ErrorTitle and ErrorText hold 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 builds a list rule, inline or backed by a range, and returns its zero-based index within the collection; AddValidation creates a typed whole, decimal, date, time, text-length or custom rule and returns the rule object, or nil where a formula cannot compile; FindAt returns the first rule covering a zero-based cell; ClearRow, ClearCol, ClearRange and MoveRange keep the rules in step with structural edits, removing any rule whose ranges end up empty; BindStoredFunctionNames links the user-function names from the workbook calculator to each rule formula ahead of a BIFF8 save; Count and Items expose the collection, and AssignFrom deep-copies rules from another sheet |
Indexed colour 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-colour role, and normalised 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-colour 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
Refer to the seven public form-control families for the current model, linked state, XLSX/ODS behaviour and the native interaction contract