Technical Article

Generating Compiled XLSX Reports in Delphi with HotXLS

An optional data source can be missing. The report still renders most of its rows. The HotXLS compiled XLSX report runner lets a Delphi or Free Pascal application supply typed data per run, record the failed lookups with cell coordinates, and save the completed workbook with a diagnostics sheet.

HotXLS compiled report flow: XLSX layout and expressions plus typed Sales data and a title enter the compiled runner, which publishes the regional revenue sheet and an optional diagnostics sheet
The HotXLS compiled runner resolves the expressions in an XLSX layout against typed Sales data and a title, then publishes the regional revenue sheet with an optional diagnostics sheet

Putting the layout in XLSX and the data in the run context

Treat the XLSX template as the report's layout. Designers can change labels and styles without changing the query code, whilst the application supplies tables and values for each run. TXLSCompiledReportRunner writes straight into the workbook that was passed to TXLSCompiledReportTemplate.Create, so each independent job needs a fresh one. Preserve the designer workbook as the source of placeholders; in this example a regional revenue report reads a small Sales table. A title is a string. Each revenue is a numeric table column. One more placeholder reads a table that only some runs register. That data is optional for this report. The example uses Classes, SysUtils, Variants, lxHandleX, and lxReport. The compiled engine is available in the Small Business and Enterprise editions; for Free Pascal, use the HotXLSLazSB add-on and add lxSmallBusiness to the uses clause.

procedure BuildRevenueTemplate(Book: TXLSXWorkbook);
var
  Sheet: TXLSXWorksheet;
begin
  Sheet := Book.Sheets.Add('Regional revenue');
  Sheet.Cells[1, 1].Value := '{{Title}}';
  Sheet.Cells[2, 1].Value := 'Region';
  Sheet.Cells[2, 2].Value := 'Revenue';
  Sheet.Cells[3, 1].Value := '{{=dbvalue(''Sales'',0,''Region'')}}';
  Sheet.Cells[3, 2].Value := '{{=dbvalue(''Sales'',0,''Revenue'')}}';
  Sheet.Cells[4, 1].Value := '{{=dbvalue(''Sales'',1,''Region'')}}';
  Sheet.Cells[4, 2].Value := '{{=dbvalue(''Sales'',1,''Revenue'')}}';
  Sheet.Cells[5, 1].Value := 'Regions';
  Sheet.Cells[5, 2].Value := '{{=dbcount(''Sales'')}}';
  Sheet.Cells[6, 1].Value := 'Optional data';
  Sheet.Cells[6, 2].Value := '{{=dbvalue(''Missing'',0,''Name'')}}';
  Sheet.Range['B3:B4'].SetNumberFormat('#,##0.00');
end;

The application writes the template's expressions as cell values. The report runner interprets {{Title}} and {{=...}} whilst rendering. A placeholder that fills the whole cell can return a number, which gives Excel a numeric value to sort or total. Adding currency text around the placeholder makes it part of a display label. Use Excel number formatting. The amount then still works in calculations. Two kinds of indexing apply in the template. Cells[3, 2] is B3, but dbvalue('Sales',0,'Revenue') addresses the first row of the registered dataset.

The template itself is a useful test input: authors can create it in Excel using the exact strings shown above, then load it into a TXLSXWorkbook with Open and pass that workbook to the same compiled template constructor. Make one change to the title cell's fill, render the report, and check the new colour alongside the rendered values. Report designers can keep finance in charge of choosing a readable currency format whilst the application supplies the amount. It also gives you a quick way to catch an accidentally typed placeholder such as {{TItle}} or a column name copied from an earlier report.

Rendering one report with typed rows

Create a TXLSReportDataContext. Register a TXLSReportMemoryTable in it and attach the context to the compiled report template. RegisterTable holds the table through its report-table interface, so the context keeps it alive during output. Keep both alive until the runner returns. The table can come from query results, an object list, or already calculated totals, as long as the values retain the types the worksheet expects. In particular, send amounts as numbers rather than formatting them with the server's decimal separator.

procedure WriteRegionalReport(const OutputFile: WideString);
var
  Book: TXLSXWorkbook;
  Context: TXLSReportDataContext;
  Sales: TXLSReportMemoryTable;
  Template: TXLSCompiledReportTemplate;
  Runner: TXLSCompiledReportRunner;
  Values: TStringList;
  RunResult: IXLSReportRunResult;
begin
  Book := TXLSXWorkbook.Create;
  Context := TXLSReportDataContext.Create;
  Values := TStringList.Create;
  try
    BuildRevenueTemplate(Book);
    Sales := TXLSReportMemoryTable.Create('Sales', ['Region', 'Revenue']);
    Sales.AddRow(['North', 125000.0]);
    Sales.AddRow(['South', 98000.0]);
    Context.RegisterTable(Sales);
    Values.Values['Title'] := 'Regional sales';

    Template := TXLSCompiledReportTemplate.Create(Book);
    try
      Template.DataContext := Context;
      Runner := TXLSCompiledReportRunner.Create(Template);
      try
        Runner.StrictDataAccess := True;
        Runner.ErrorMode := xremWriteAndContinue;
        Runner.RuntimeDiagnosticsSheetName := 'Report Diagnostics';
        Runner.RunToFile(Values, OutputFile);
        RunResult := Runner.LastResult;
        Writeln('Issues: ', RunResult.IssueCount);
        Writeln('Code: ', RunResult.Issues[0].Code);
        Writeln('Sheet: ', RunResult.Issues[0].SheetName);
        Writeln('Row: ', RunResult.Issues[0].Row);
        Writeln('Column: ', RunResult.Issues[0].Col);
        Writeln('Message: ', RunResult.Issues[0].Message);
      finally
        Runner.Free;
      end;
    finally
      Template.Free;
    end;
  finally
    Values.Free;
    Context.Free;
    Book.Free;
  end;
end;

The run is not a failure. Runner.State is xrrsCompletedWithErrors when RunToFile returns, and LastResult holds the single issue recorded for B6. A console program that calls WriteRegionalReport with the name of a new file prints these lines. Expected output:

Issues: 1
Code: REPORT_DATA_TABLE_MISSING
Sheet: Regional revenue
Row: 6
Column: 2
Message: Report data table not found: Missing

The two dbvalue expressions hard-code source row indexes because the template built above has two named slots. When your input comes from a SQL query, specify an order that matches the worksheet's intended display. Otherwise a changed execution plan might return the same rows in a new order. Either let each label come from its corresponding source row, as the code above does, or resolve the required region before passing the table to the runner when the labels in the worksheet are fixed. Do the same for totals derived upstream so a new region cannot quietly land under an old heading.

Use strict data access when you need a missing table to show up as an issue. With xremWriteAndContinue, the failed placeholder is replaced by diagnostic text and the remaining cells still render. RunToFile publishes the destination only after rendering and serialisation have completed, which protects readers against a partially written workbook. It still leaves the application to decide whether a report with a recorded data error should be made available to the end user. An optional commentary field is different. A report with an issue logged can be appropriate there. For a missing revenue input, send it for review before publishing it to customers.

Generation and publication are different results. The difference matters to a batch job. Use a fresh filename for a one-off check, or keep the previous completed file at its existing path until you have decided what to publish. If the application accepts recoverable issues in a preview but refuses them for delivery, run to a separate candidate path. Inspect LastResult and the saved file at that candidate path before moving it into place. By the time the example inspects the issue, RunToFile has already written the file requested by its caller.

Reading the amounts and the issue back from the published file

Read the structured issue from LastResult for application logging, and read the diagnostics sheet in the saved workbook when that sheet is part of the delivery. That sheet has a header row followed by one row per issue, in this order: Severity, Code, Category, Target index, Target, Sheet, Cell, Band input row, Message. So the first issue is in row 2. Its code is in column 2, its worksheet name in column 6, and its cell address in column 7. CheckRegionalReport opens the saved file into a new TXLSXWorkbook, so that a correct value in the original object cannot hide a serialisation or output-path problem. Its output follows the code. Expected output:

procedure CheckRegionalReport(const OutputFile: WideString);
var
  Readback: TXLSXWorkbook;
  Report, Issues: TXLSXWorksheet;
begin
  Readback := TXLSXWorkbook.Create;
  try
    if Readback.Open(OutputFile) <> 1 then
      raise Exception.Create('Could not reopen the regional report');
    Report := Readback.Sheets.SheetByName('Regional revenue');
    Issues := Readback.Sheets.SheetByName('Report Diagnostics');
    if (Report = nil) or (Issues = nil) then
      raise Exception.Create('Could not find the report worksheets');
    Writeln('A1: ', VarToStr(Report.Cells[1, 1].Value));
    Writeln('Row 3: ', VarToStr(Report.Cells[3, 1].Value), ' ',
      VarToStr(Report.Cells[3, 2].Value));
    Writeln('Row 4: ', VarToStr(Report.Cells[4, 1].Value), ' ',
      VarToStr(Report.Cells[4, 2].Value));
    Writeln('B5: ', VarToStr(Report.Cells[5, 2].Value));
    Writeln('B6: ', VarToStr(Report.Cells[6, 2].Value));
    Writeln('Amounts are numeric: ',
      VarIsNumeric(Report.Cells[3, 2].Value) and
      VarIsNumeric(Report.Cells[4, 2].Value) and
      VarIsNumeric(Report.Cells[5, 2].Value));
    Writeln('Issue code: ', VarToStr(Issues.Cells[2, 2].Value));
    Writeln('Issue sheet: ', VarToStr(Issues.Cells[2, 6].Value));
    Writeln('Issue cell: ', VarToStr(Issues.Cells[2, 7].Value));
  finally
    Readback.Free;
  end;
end;
A1: Regional sales
Row 3: North 125000
Row 4: South 98000
B5: 2
B6: [Report error REPORT_DATA_TABLE_MISSING] Report data table not found: Missing
Amounts are numeric: TRUE
Issue code: REPORT_DATA_TABLE_MISSING
Issue sheet: Regional revenue
Issue cell: B6

Before a scheduled job depends on this layout, try one run with the optional table registered: register a second table named Missing with one column named Name and a first row such as Verified. B6 then contains that value and the run completes without the missing-table issue. No diagnostics sheet is written on that run. The output above belongs to the run without the table. Reserve the diagnostics sheet name when designing the template. If a sheet already uses that name, the runner chooses a numbered variant such as Report Diagnostics 2 to preserve the existing sheet.

A support log should record the issue's code, worksheet, and row and column from the structured result. For this example those fields locate B6 even if the diagnostics sheet is sent in a separate file during troubleshooting. Compare the row label and its amount too. Source rows may switch places. The combined revenue is still 223,000. Pairing the label with the amount makes that mismatch apparent before a reader makes a decision from the wrong region's numbers.

Choosing where the report logic belongs

A compiled report is a good fit when analysts are responsible for the template and the application supplies the facts behind it. Layouts generated entirely from code are different. A direct workbook loop can be simpler. For a small number of editable placeholders and detail rows, the manual Excel template workflow shows how to find tokens, copy a styled row, and recalculate. If the task is simply to turn a query result into an Excel worksheet, start with the dataset export workflow.

The HotXLS Delphi spreadsheet component provides the workbook APIs and the compiled report add-on.