Workbook Viewer Feature
Overview
In addition to file manipulation, Delphi desktop applications often need to visually display workbooks to users; HotXLS includes a visual control to render spreadsheets directly inside VCL and FMX forms
TXLSWorkbookViewer Control
The TXLSWorkbookViewer component provides scrolling, rectangular selection, editing, formula input, comments, hyperlinks, conditional formatting, and print preview without writing temporary files
Assign Workbook for classic XLS or XlsxWorkbook for XLSX, XLSB and ODS workbooks, or call LoadFromFile to let the control own the loaded workbook; LoadFromFile takes .xls, .xlsx, .xlsm, .xlsb, .xltx, .xltm and .ods files
Editing and Formula Input
Set Editable to True to enable F2, double-click, printable-key, Delete, and formula-bar editing; protected locked cells remain read only whilst explicitly unlocked cells remain editable
FormulaBarText returns the selected cell formula with its leading equals sign or its input value, and assigning the property applies a new formula or typed value and recalculates the dependent formulas
Undo and Redo use a bounded circular history controlled by UndoLimit; each cell edit, range clear, or text paste creates one transaction, and undo brings back sparse absence, native rich text, formula caches, and the previous cell style in either workbook model
Delete and ClearSelectedRange clear the entire selection, Ctrl+C and CopySelectedRange copy tab-separated Unicode text, and Ctrl+V and PasteSelectedRange paste clipboard text at the selection's top-left cell; PasteText accepts the same text directly
Every target is checked before a write starts, including protected blank cells and effective XLSX styles inherited from rows, columns, or overlays; a rejected target turns down the whole operation, and a formula-entry exception restores the captured content before it propagates
Text paste accepts tabs, CRLF or LF row breaks, quoted fields, doubled quotes, and quoted multiline text; ragged rows are padded out with blank fields, a final row break does not add a row, empty text represents one blank cell, and a leading apostrophe keeps literal text
Existing array formulas and data-table regions reject content edits, partial merged-range clears reject the whole operation, and a multi-cell paste into a merge is turned away; single merged-anchor edits and clears containing the whole merge preserve its geometry
The single-cell editing hooks are typed callbacks: OnBeforeEdit (a TXLSViewerBeforeEditEvent) receives the proposed text and can veto or rewrite it through Allow and Text, and OnAfterEdit (a TXLSViewerAfterEditEvent) reports the committed text; a single-cell Delete keeps these hooks, whilst range clear and paste operate through the headless transaction API without invoking cell editing callbacks
Viewer.Editable := True; Viewer.GoToCell(2, 3); Viewer.FormulaBarText := '=A1*2'; Viewer.Undo; Viewer.Redo;
Headless editing transactions
TXLSWorkbookEditHistory in lxWorkbookViewer provides the same transaction engine without building a control; bind a borrowed classic or XLSX workbook, then call EditCell, ClearRange, CopyRangeText, PasteText, Undo, or Redo with one-based sheet, row, and column coordinates
ClearHistory releases retained undo and redo transactions and resets LastTransaction; it preserves the bound workbook and its current cell content
Every stack entry is a TXLSWorkbookEditTransaction record carrying the sheet index, a sheet identity token, inclusive FirstRow/FirstCol/LastRow/LastCol bounds, and a TXLSCellContentSnapshotArray of the captured TXLSCellContentSnapshot values; both history stacks have type TXLSWorkbookEditTransactionArray
CanEditRange, copying, and preflight do not create blank cells or materialise packed XLSX storage; successful edits may materialise the stored cells they change, and the caller keeps workbook ownership and must detach or destroy the history before freeing the workbook
The headless engine restores formula cache states without evaluating formulas; invoke the workbook's Recalculate after a successful operation when updated calculated results are required, whilst the viewer does this automatically once per operation
MaxOperationCells defaults to 100000 and accepts 1 through 1000000; UndoLimit defaults to 100, accepts 0 through 100000, and empties both history stacks when changed, with zero disabling history; clipboard text is limited to 16 Mi characters
LastTransaction exposes the most recent successful operation's sheet and bounds without revealing the stored history payload; a blocked undo or redo leaves its stack entry available for a later attempt
Undo and redo recheck current protection and structural bounds, rejecting a changed worksheet identity or an array, data table, or merge reaching beyond the transaction; externally recalculated spills can therefore block a history operation until their intersecting bounds become editable
History := TXLSWorkbookEditHistory.Create;
try
History.Bind(Workbook);
if History.PasteText(1, 2, 1, '42'#9'TRUE'#13#10'''literal'#9'=A2*2') then
Workbook.Recalculate;
if History.Undo then
Workbook.Recalculate;
finally
History.Free;
end;
Range and Reference Selection
Use Shift navigation, mouse dragging, or SelectRange to create a rectangular selection exposed through SelectionTop, SelectionLeft, SelectionBottom, SelectionRight, and SelectedRange
BeginReferencePick enables formula-reference mode and OnReferencePick (a TXLSViewerReferenceEvent) publishes the current A1 range whenever the selection changes; call EndReferencePick when the host formula editor has accepted the reference
Dropdown Lists and Input Prompts
Both TXLSWorksheet and TXLSXWorksheet resolve list data validations and input prompts straight through FindDataValidationAt, TryGetCellDropdownItems, GetCellDropdownItems, TryGetCellValidationPrompt, and SelectCellDropdownItem; AddListValidation and DataValidations.AddList take inline item lists as well as range or defined-name formulas with or without a leading = (such as '=$A$1:$A$9'); both worksheet classes also take an array of items, and inline items may hold double quotes, escaped as an Excel formula string so Classic XLS and XLSX keep the same item text
When a cell carrying an in-cell list validation or input message is selected, TXLSWorkbookViewer draws the dropdown button on the right edge of the active cell (controlled by ShowValidationDropdown) and shows the yellow validation prompt callout underneath or above the cell (controlled by ShowValidationPrompt)
The viewer offers the same lookup through TryGetCellDropdownItems(Row, Col, Items, ShowDropDown) and GetCellDropdownItems(Row, Col), plus GetSelectedCellDropdownItems, which returns the item array of the current selection and an empty array when the selected cell has no list
Clicking the dropdown button, pressing Alt+Down, or calling ShowDropdownList opens the embedded popup list; picking an item by mouse click, Enter, Tab, or SelectDropdownItem commits the value through the edit history, fires OnBeforeEdit and OnAfterEdit, and recalculates dependent formulas; the popup grows to its longest caption within the viewer bounds; see Demo/Delphi/WorkbookViewer/WorkbookViewer.dpr (and WorkbookViewer.lpi for Lazarus) plus Demo/Delphi/Miscellaneous/DataValidation/DataValidation.dpr for complete runnable examples
Sheet.DataValidations.AddList('C2:C10', '=$A$1:$A$9');
Sheet.DataValidations[0].SetPrompt(
'Please input a value from 0 to 8',
'- Range: 0 ~ 8'#10'- Default value: 3');
Viewer.Editable := True;
Viewer.GoToCell(2, 3);
Viewer.ShowDropdownList;
Viewer.SelectDropdownItem(5);
Typed input follows the same rules: ValidateCellInput tests candidate text with the same text-to-value conversion as WriteAutoValue, ValidateCellValue tests what is already stored, and TryGetCellValidationError returns the rule's error-alert title, message and style; all three exist on TXLSWorksheet, TXLSXWorksheet and the viewer itself; Classic XLS custom-formula rules are evaluated for stored values only
With EnforceDataValidation left at its default of True, the viewer checks every typed edit (in-cell editor, EditSelectedCell and FormulaBarText) against rules that show an error alert, just as Excel does: Stop offers Retry or Cancel, Warning asks whether to keep the value, and Information reports it with OK or Cancel; clearing a cell, entering a formula and pasting skip the check; assign an OnValidationError handler (type TXLSViewerValidationErrorEvent) and set Handled to replace the built-in dialog with your own UI or logging, choosing Action as xvaAccept, xvaRetry, or xvaCancel; Style is the rule's TXLSViewerValidationErrorStyle (xveStop, xveWarning, or xveInformation), and CircleInvalidData draws red circles round visible cells whose stored values break their rule
Idx := Sheet.AddWholeNumberValidation('B2:B10', xlsxDvOpBetween, '1', '100');
Sheet.DataValidations[Idx].SetError('Quantity check',
'Enter a whole number from 1 to 100', xlsxDvErrWarning);
if not Sheet.ValidateCellInput(2, 2, '250') then
ShowMessage('250 is outside the rule');
Viewer.EnforceDataValidation := True; // default
Viewer.CircleInvalidData := True;
Viewer.OnValidationError := HandleValidationError;
procedure TForm1.HandleValidationError(Sender: TObject; Row, Col: Integer;
const Text: WideString; Style: TXLSViewerValidationErrorStyle;
const AlertTitle, AlertText: WideString;
var Action: TXLSViewerValidationAction; var Handled: Boolean);
begin
StatusBar1.SimpleText := AlertTitle + ': ' + AlertText;
Action := xvaRetry; // reopen the editor with the rejected text
Handled := True;
end;
Display Properties
Check the configuration controls below
- WorkbookViewer component reference guide — Layout property controls
- DisplayGridLines property — Toggle grid borders
- Zoom property — Set sheet zoom ratios