XLSX Facade Overview (lxHandleX)
lxHandleX is the dedicated facade unit for Excel 2007+ (.xlsx) and OpenDocument Spreadsheet (.ods) workbook workflows. It coexists with the original lxHandle facade so that legacy code keeps working without any changes:
lxHandle— primary facade for the Excel 97-2003 BIFF format (.xls), HTML, RTF, CSV, and TSV exports. All existing user code continues to use this unit unchangedlxHandleX— primary facade for the Excel 2007+ OOXML format (.xlsx), ODS read/write workflows and the XLSB values-and-styles subset; it provides separate workbook and worksheet types, automatic package detection throughOpen,SourceFormat, explicit output formats andTODSExportOptions
Class hierarchy
The XLSX facade exposes the following classes:
type
TXLSXWorkbook = class // top-level workbook with SaveAs / Open
TXLSXHtmlExportOptions = class // HTML document, style, BOM, and table class options
TODSExportOptions = class // ODS export options for generator, chart, and image output
TXLSXSheets = class // worksheet collection on the workbook
TXLSXFonts = class // workbook-level font palette
TXLSXFont = class // single font descriptor
TXLSXFills = class // workbook-level fill palette
TXLSXFill = class // single fill (pattern + fg/bg color)
TXLSXBorders = class // workbook-level border palette
TXLSXBorder = class // four edges + diagonal border
TXLSXNumberFormats = class // workbook-level custom format codes
TXLSXDefinedNames = class // workbook-level named ranges
TXLSXWorksheet = class // single worksheet with cells and decorations
TXLSXStructuralEditRegistry = class // ordered application participants for row and column reference updates
TXLSXCells = class // cell collection on the worksheet
TXLSXCell = class // single cell (value, formula, *Index style refs)
TXLSXRange = class // rectangular worksheet range wrapper
TXLSXMergedCells = class // merged-range collection
TXLSXHyperlinks = class // hyperlink collection
TXLSXComments = class // cell-comment collection
TXLSXImages = class // image collection (drawings + media)
TXLSXConditionalFormats = class // conditional formatting rules
TXLSXDataValidations = class // data-validation rules
TXLSXTables = class // Excel-style table collection
TXLSXCharts = class // chart collection (anchored or full-page)
TXLSXChart = class // single or combination chart with primary, secondary, date, value, and series axes
TXLSXChartPlotGroup = class // ordered chart-family group with its own series and axis pair
TXLSXChartSeries = class // chart series with formula ranges and typed literal caches
TXLSXTextBox = class // standalone worksheet drawing text box
TXLSXRichText = class // per-run rich-text payload for cells
TXLSXAlignment = class // cell alignment / wrap / indent / rotation
TXLSXExternalLinks = class // external workbook link collection
TXLSXExternalLink = class // single external workbook reference (Target URL + SheetNames)
TXLSConnections = class // external data connection collection
TXLSConnection = class // database, web, text, and refresh connection metadata
TXLSQueryTables = class // worksheet query-result collection
TXLSQueryTable = class // query ownership, fields, and result binding
These classes are independent of lxHandle.TXLSWorkBook and
lxHandle.TXLSWorksheet. Applications that need both formats may
use both facades side by side:
uses
lxHandle, // XLS / HTML / RTF / CSV workbook (TXLSWorkBook)
lxHandleX; // XLSX workbook (TXLSXWorkbook)
Quick start
The XLSX facade follows the same call-shape conventions as the BIFF
facade — SaveAs / Open on the workbook,
Sheets.Add / Sheets[i] on the worksheet
collection, and Cells.Item[Row, Col].Value on the cell
collection. The example below writes a small workbook that exercises every
currently-supported feature:
uses lxHandleX;
var
wb: TXLSXWorkbook;
ws: TXLSXWorksheet;
bold, yellow, box, currency: Integer;
begin
wb := TXLSXWorkbook.Create;
try
bold := wb.Fonts.Add('Calibri', 12, True, False);
yellow := wb.Fills.AddSolid($FFFFFF00);
box := wb.Borders.AddBox(xlsxBorderThin);
currency := wb.NumberFormats.Add('"$"#,##0.00');
ws := wb.Sheets.Add('Demo');
ws.Cells.Item[1, 1].Value := 'Hello';
ws.Cells.Item[1, 1].FontIndex := bold + 1;
ws.Cells.Item[1, 2].Value := 123.45;
ws.Cells.Item[1, 2].NumberFormatIndex := currency + 1;
ws.Cells.Item[2, 1].Value := Now; // tagged as date
ws.Cells.Item[2, 2].Formula := 'SUM(B1:B1)';
ws.Cells.Item[3, 1].FillIndex := yellow + 1; // highlight cell
ws.Cells.Item[3, 2].BorderIndex := box + 1; // boxed cell
ws.ColWidth[1] := 24;
ws.RowHeight[1] := 28;
ws.MergeCells(4, 1, 4, 3);
ws.Range['A8:C10'].Merge(True); // merge across rows
ws.AddHyperlink(5, 1, 'https://www.loslab.com', 'Visit losLab');
ws.AddComment(5, 2, 'Important note', 'Kevin');
ws.AddImageFromFile(6, 1, 'logo.png');
ws.AddConditionalFormat('B1:B10', xlsxCfOpGreaterThan, '100');
ws.AddListValidation('C1:C5', 'Yes,No,Maybe');
wb.DefinedNames.Add('SalesData', 'Demo!$A$1:$B$10');
wb.SaveAs('demo.xlsx');
finally
wb.Free;
end;
end;
Supported features
- Cell values: numbers, booleans, strings, dates, formulas
- Shared strings table (
xl/sharedStrings.xml) with deduplication on the write path - Workbook-level style palettes —
Workbook.Fonts,Fills,Borders, andNumberFormats— plus per-cellFontIndex/FillIndex/BorderIndex/NumberFormatIndex. SaveAs emits real<fonts>/<fills>/<borders>/<numFmts>+<cellXfs>blocks; Open parses them back so Name/Size/Bold/Italic/Color, fill patterns, border edges, and custom number formats all survive the round-trip - Per-column widths via
Worksheet.ColWidth[Col]and per-row heights viaWorksheet.RowHeight[Row](worksheet<cols>block and per-<row>htattributes) - Built-in date
cellXfat indexXlsxXfIndexDate;TDateTimevalues are tagged automatically - Merged cells (
<mergeCells>), includingTXLSXRange.Merge(True)for Excel-style merge across rows - Worksheet ranges via
Worksheet.Range,RCRange,UsedRange,EntireRow, andEntireColumn. See TXLSXRange for batch values, formulas,SetArrayFormula, style indexes, number formats, borders, protection flags, auto-fit, merge, offset, resize,Sortmulti-key sorting,ApplyBuiltinStylebuilt-in cell styles, copy/move helpers, whole-row/whole-column insert/delete helpers, and selected-range HTML export - Hyperlinks (
<hyperlinks>) backed by per-worksheet rels for external URLs - Cell comments with VML drawing (
xl/commentsN.xml+xl/drawings/vmlDrawingN.vml) so balloons render in Excel - Embedded images (PNG / JPEG / GIF / BMP) via
Worksheet.Images, written toxl/media/imageN.<ext>plus per-sheet drawing XML and rels - Standalone drawing text boxes via
Worksheet.AddTextBox, written as worksheet drawing shapes with text bodies instead of cell comments, with direct anchor lookup and range deletion helpers - Workbook-level named ranges via
Workbook.DefinedNames(workbook-scoped or sheet-scoped throughSheetIndex) - Formula calculation via
Workbook.CalculateandWorksheet.Calculate, sharing the XLS formula parser and evaluator for leading-equals formulas, cell and range references, referenced formula cells, cross-sheet references, nested formula-defined names, broadcast arrays with per-cell errors, multivariable regression and prediction arrays, and supported text, date, workday, engineering/base-conversion, bitwise, statistical, aggregate, and math functions; useWorkbook.OnUserFunctionorWorkbook.OnUserFunctionExto resolve custom or unsupported functions - Per-worksheet conditional formatting
(
Worksheet.ConditionalFormats) and data validation (Worksheet.DataValidations) including the dropdownAddListValidation(Range, Items)shortcut - Row / column outline groups (
RowOutlineLevel,ColOutlineLevel), hidden state (RowHidden,ColHidden), and collapsed group state (RowCollapsed,ColCollapsed) - Frozen panes via
Worksheet.FreezePanes(Row, Col) - Page setup — six margin properties, paper size, orientation,
page scale, fit-to-width / fit-to-height, plus
HeaderText/FooterText. NamedxlsxPaper*constants such asxlsxPaperLetter,xlsxPaperA4,xlsxPaperA3, andxlsxPaperLegalcan be assigned toPaperSize - Auto-filter (
Worksheet.SetAutoFilter) - Excel-style tables (TXLSXTable) with style info, table columns, totals-row labels and functions, calculated-column formulas, and totals-row formulas
Facade sub-collection APIs
The facade collection classes manage conditional formats, data validations, named ranges, images, and tables. Here are the core members of each collection:
- TXLSXConditionalFormats:
Exposes conditional formatting rules
Properties:
CountMethods:AddAboveAverage,AddColorScale2,AddColorScale3,AddDataBar,AddExisting,AddExpression,AddIconSet,AddSimpleRule,AddTextRule,AddTop10,DeleteAt,DeleteInRange,FindAt,IndexOfCell - TXLSXDataValidations:
Exposes data validations
Properties:
CountMethods:AddExisting,AddList,DeleteAt,DeleteInRange,FindAt,IndexOfCell - TXLSXDefinedNames:
Exposes defined names (named ranges)
Properties:
CountMethods:DeleteByName,FindByName,IndexOfName - TXLSXImages:
Exposes embedded images
Properties:
CountMethods:DeleteAt,DeleteInRange,FindAt,IndexOfCell - TXLSXTables:
Exposes Excel tables
Properties:
CountMethods:AddExisting,DeleteByName,FindByName,IndexOfName - TXLSConnections:
Exposes workbook external data connections through
Workbook.ConnectionsProperties:CountMethods:Add,AddExisting,FindById,FindByName,NextId,Validate - TXLSQueryTables:
Exposes worksheet query-result definitions through
Worksheet.QueryTablesProperties:CountMethods:Add,AddExisting,FindByName,FindByResultTableName,Validate
Supported features
- Document properties (
Workbook.Title,Author,Subject,Keywords,Description,LastModifiedBy,Company, etc.) written todocProps/core.xml+docProps/app.xml - Worksheet / workbook password protection (legacy 16-bit hash)
through
Worksheet.Protect/Workbook.ProtectWorkbook; Excel-compatible AES password-protected save throughSaveAsEncrypted, using AES-NI acceleration when available and portable software fallback otherwise.OpenEncryptedstill raises for encrypted packages until decrypt support lands - VBA project preservation via
Workbook.LoadVbaProjectFromFile/VbaProject; bytes round-trip unchanged. ValidvbaProject.binpayloads can also be inspected throughWorkbook.ParsedVBAProject - Charts — column / bar / line / pie / area / doughnut / scatter / bubble / radar / stock / surface / 3D and combination charts via
TXLSXChart, anchored
on a worksheet (
Worksheet.AddChart) or full-page on a dedicated chart sheet viaWorkbook.AddChartSheet(Name, Type, Title) - Rich-text cells via TXLSXRichText with per-run font formatting; round-trips through the shared-string table
- Internal hyperlink anchors via
Worksheet.AddHyperlinkToCell(Row, Col, "Sheet2!A1")(no rels relationship needed) - Cell range copy / move / clear API on the worksheet
(
CopyRange,CopyRangeTo,MoveRange,ClearRange) - Cell alignment via
TXLSXAlignment +
per-cell
AlignmentIndex - Worksheet tab color via
Worksheet.TabColor/TabColorIsAuto - Worksheet view mode via
Worksheet.View, including normal view, page-break preview, and page-layout view - Streaming SaveAs path (
Workbook.StreamingWrite := True) that builds and writes each worksheet without holding the others in memory; the per-row XML accumulator usesTXLSWideStringBuilderso the cell loop stays linear - Round-trip
Openfor everything above except encrypted XLSX packages and chart-sheet sheet identification, which fall back to the documented partial behavior - Stream-based export and import:
SaveAs(Stream),Open(Stream)for in-memory or BLOB-field use - OpenDocument Spreadsheet read/write:
Workbook.OpenODSand the genericWorkbook.Opencan load.odspackages, whileWorkbook.SaveAsODSandSaveAs(..., xlsxOpenDocumentSpreadsheet)write ODS output directly. The format surface covers values, formulas, styles, rich text, row/column dimensions, merges, hyperlinks, images, charts, named ranges, AutoFilter, conditional formats, data validations, freeze panes, page setup, headers/footers, print ranges, page breaks, outline groups, tab colour, and sheet visibility across supported round trips - ODS export options: pass
TODSExportOptionstoSaveAsODSto override the document generator string or suppress chart and image parts when producing a lighter package - Delimited-text import:
Workbook.OpenCSV(FileName)andWorkbook.OpenCSV(Stream)import CSV or TSV data with separator sniffing, BOM encoding detection, RFC 4180-style quoting, and optional value type inference.Open(FileName)routes.csvand.tsvfiles to the importer automatically - Workbook metadata scan:
Workbook.GetSheetNames(FileName, List)andWorkbook.GetSheetNames(Stream, List)read ordered sheet names fromxl/workbook.xmlwithout loading worksheet XML - Cell protection:
TXLSXCell.LockedandFormulaHidden— control which cells are editable or whose formulas are visible when the sheet is protected - Auto-fit column width and row height from cell content:
Worksheet.AutoFitColumn,AutoFitColumns,AutoFitRow,AutoFitRows - Row / column insert and delete with full cascade:
InsertRows,DeleteRows,InsertCols,DeleteCols. Side effects propagate through cells, merged ranges, hyperlinks, comments, freeze pane, range-string references, tables, cell formulas, conditional-format / data-validation formulas, internal hyperlink targets, print setup references, manual page breaks, auto-filter column criteria, chart series ranges, defined names, image anchors, and chart anchors - Extended page setup:
PrintArea,PrintTitleRows,PrintTitleCols,PrintGridlines,PrintHeadings,BlackAndWhite,Draft,PrintNotes,PrintOverThenDown - Opaque printer-driver payload access through
PrinterDriverData,HasPrinterDriverData, andClearPrinterDriverData; byte arrays and worksheet copies have independent ownership, payloads are limited to 1 MiB, and clearing removes the worksheet relationship and binary package part without replacing typed page-setup fields; loading binds only the exactpageSetuprelationship identifier with the required relationship type and an existing target, while missing, mistyped, or dangling references emitxlsDiagnosticPrinterSettingsRelationshipInvalidwithout borrowing another binary part - Workbook-local render calibration through
RenderCalibration,CaptureRenderCalibration, andResetRenderCalibration, with validated whole-record assignment and independent operation snapshots for width, height, line spacing, cell margins, screen scaling, and measurement DPI - Operation-owned geometry and font measurement through
CreateRenderGeometry, with immutable calibration and workbook-generation identity, complete font and wrap-aware cache keys, bounded local caching, and shared pixel, point, column-width, MDW, and usable-cell-width conversions - AutoFit captures one workbook-local geometry snapshot per operation and measures visible cell fonts and wrapped text with calibrated spacing and margins; pagination captures a separate snapshot per build, keeps existing logical pages unchanged until the next build, and never writes worksheet dimensions
- Sheet visibility:
Worksheet.Visibility(xlsxSheetVisible/xlsxSheetHidden/xlsxSheetVeryHidden) andIsSelected - Manual page breaks:
AddRowBreak,AddColBreak, index lookup, and range removal helpers - Auto-filter column criteria:
Worksheet.AddAutoFilterColumnwith single or AND/OR two-criterion filter rules, plusWorksheet.AutoFilterColumns.FindByColIdandDeleteByColIdfor direct criteria lookup and removal (TXLSXAutoFilterColumn) - Workbook date base:
Workbook.Date1904switches between the 1900 (Windows default) and 1904 (Mac) date epoch - Diagonal borders:
TXLSXBorder.DiagonalUpandDiagonalDownenable the diagonal lines; theDiagonaledge carries the style and color - Extended font properties:
TXLSXFont.VertAlign(superscript / subscript),OutlineFont,Shadow,Family,CharSet - Named range metadata:
TXLSXDefinedName.HiddenandComment - Sheet view options:
Worksheet.Zoom,DisplayGridLines,DisplayZeros,DisplayRightToLeft,StandardWidth,StandardHeight - OOXML legacy indexed-color palette:
Workbook.IndexedColor[0..63]withResetIndexedColors - External workbook links:
Workbook.ExternalLinks/ TXLSXExternalLink — Target URL + SheetNames metadata round-trip - External data connections and query results:
Workbook.Connections/Worksheet.QueryTables— typed refresh, credentials, command, web, text, parameter, field, table, and defined-name bindings with extension-safe round-trip - Theme color support on
TXLSXFont,TXLSXFill, andTXLSXBorderEdge:ColorTheme/ColorIndex/TintAndShadeproperties with priority ordering (theme > indexed > RGB) - BIFF8 conversion through the file and stream overloads of
SaveXLSXWorkbookAsXLS, with a deterministic 56-color palette plan, preservation of indexed slots already used by workbook styles, weighted OKLab quantization when direct colors exceed the available slots, sparse loaded-cell traversal, and preflight rejection of rows or columns outside the XLS grid; typed print fields and opaque printer data are converted independently, BIFF8 bounds are checked before the destination stream is written, standard fields take priority over duplicate private defaults, and the OOXML-onlyUsePrinterDefaultsflag is not synthesized into Classic XLS - CSV export:
Workbook.SaveAsCSV— 4 overloads (FileName or Stream × active-sheet / explicit SheetIndex + Delimiter), UTF-8 with BOM, RFC 4180 quoting - HTML export:
Workbook.SaveAsHTMLandTXLSXRange.SaveAsHTMLwrite HTML5 tables for a whole workbook sheet or only the selected rectangle. Options overloads acceptTXLSXHtmlExportOptionsfor full-document output, style emission, BOM emission, and table class naming - RTF export:
Workbook.SaveAsRTF— 4 overloads, RTF 1.6 table with column widths, per-cell font formatting, and full-BMP unicode via signed-16-bit\uN?escapes
Shared infrastructure
Both facades share a common set of lower-level helper units, which means style descriptors, hash tables, AVL trees, ZIP and XML I/O, RGB-to-HLS conversions, and string builders are written once and used by either path The shared helpers include:
lxStyleXf,lxStyleFont,lxStyleColor,lxStyleFill,lxStyleBorder— modern style descriptorslxRgb— RGB / HLS color conversionlxHashTable,lxKeyList,lxAvlTree,lxCols,lxRows— deduplicating containers and AVL-backed cell heap building blockslxXmlReader,lxXmlWriter,lxZipArchive— OOXML transport layerlxStrBuilder,lxCacheStream,lxWStream,lxZlibStream— stream and string assembly helpers