Техническая статья

HotXLS: database export to spreadsheet reports in Delphi

Создавайте, редактируйте, проверяйте, вычисляйте и экспортируйте книги Excel напрямую из кода Delphi или C++Builder. HotXLS — нативная библиотека Object Pascal с исходным кодом для рабочих процессов XLS и XLSX, предназначенная для настольных инструментов, batch-задач, систем отчетности и серверной генерации документов без автоматизации Microsoft Excel.

Эта статья предназначена для teams moving datasets from Delphi applications into customer-ready workbook reports. Она рассматривает database export to spreadsheet reports как промышленную инженерию документов, а не как одиночный вызов компонента.

Практический риск состоит в том, что a dataset dump is not a report when type conversion, null handling, totals, grouping, sorting, and workbook styling are not part of the export contract. Поэтому процессу нужны письменный контракт, наблюдаемая диагностика и реалистичные регрессионные файлы.

Архитектурные решения

Treat the dataset schema as a workbook contract. field-to-column mapping, captions, order, grouping, and sort rules / null, date, time zone, currency, decimal, and Boolean formatting

  • field-to-column mapping, captions, order, grouping, and sort rules
  • null, date, time zone, currency, decimal, and Boolean formatting
  • formula totals, subtotals, filters, frozen panes, and table-like navigation
  • streaming, pagination, and memory policy for large result sets

Порядок реализации

Map database fields to worksheet semantics. The order below keeps the workflow reviewable for Delphi and C++Builder teams.

  1. derive an export profile from the report requirement and dataset schema
  2. validate field types and required columns before creating the workbook
  3. write headers, formats, and formulas before streaming large row groups
  4. apply filters, freeze panes, totals, and page setup after the data range is known
  5. compare row counts and key aggregates with the source query

Доказательства проверки

Export diagnostics for support and finance teams. Keep these fields with the output or support record.

  • query identifier, field mapping, row count, column count, and export profile
  • null and data-type conversions, locale profile, and formula summary
  • source aggregate totals compared with workbook totals
  • warnings for truncated text, unsupported types, or memory-limit fallback

Types matter more than cell values

Database export needs explicit mapping from field types to worksheet cells, number formats, formulas, totals, and visible labels. Without that mapping, users receive a workbook that looks correct but behaves poorly in analysis.

Заметки по промышленной реализации

Рассматривайте HotXLS: database export to spreadsheet reports in Delphi как явный сервисный контракт вокруг вызовов HotXLS, разделяя проверку входных данных, запись книги, контроль результата и сведения для поддержки

  • Определите источник данных, диапазоны ячеек и формат вывода до создания книги
  • Записывайте число строк, листы, предупреждения и путь вывода в проверяемые сведения поддержки
  • Инкапсулируйте прикладные детали в тестируемые helper-функции, а не в события UI
  • Повторно откройте или проверьте сохраненный файл перед передачей другой системе или клиенту

Сценарии отказов для проверки

  • Успешный SaveAs не доказывает, что бизнес-контракт остался корректным
  • Шрифты, права и региональные настройки на сервере могут отличаться от машины разработчика
  • Журналы не должны раскрывать пароли, данные клиентов или внутренние ссылки

Подробный пример Delphi

Следующий пример Delphi показывает практическую границу сервиса для этой темы, где политика, журналирование и проверка остаются тестируемыми

procedure ExportCustomerReport(DataSet: TDataSet; const OutputFile: string);
var
  Wb: TXLSXWorkbook;
  Sh: IXLSWorksheet;
  RowIndex: Integer;
begin
  RequireOpenDataSet(DataSet);
  Wb := TXLSXWorkbook.Create;
  try
    Sh := Wb.Sheets[0];
    Sh.Name := 'Customers';
    WriteHeaderRow(Sh, ['CustomerId', 'Name', 'Region', 'Balance', 'LastOrder']);

    RowIndex := 2;
    DataSet.First;
    while not DataSet.Eof do
    begin
      Sh.Range['A' + IntToStr(RowIndex)].Value := DataSet.FieldByName('CustomerId').AsString;
      Sh.Range['B' + IntToStr(RowIndex)].Value := DataSet.FieldByName('Name').AsString;
      Sh.Range['C' + IntToStr(RowIndex)].Value := DataSet.FieldByName('Region').AsString;
      Sh.Range['D' + IntToStr(RowIndex)].Value := DataSet.FieldByName('Balance').AsCurrency;
      Sh.Range['E' + IntToStr(RowIndex)].Value := DataSet.FieldByName('LastOrder').AsDateTime;
      Inc(RowIndex);
      DataSet.Next;
    end;

    Sh.Range['A1:E1'].ApplyBuiltinStyle(xbsTitle);
    ApplyDateAndCurrencyFormats(Sh, RowIndex - 1);
    AddAutoFilterToHeader(Sh, 'A1:E' + IntToStr(RowIndex - 1));
    WriteExportManifest(Wb, DataSet, RowIndex - 2);

    if Wb.SaveAs(OutputFile) <> 1 then
      RaiseWorkbookSaveError(OutputFile);
  finally
    Wb.Free;
  end;
end;

Производственный чек-лист

  • Run the workflow on an empty workbook, a normal customer workbook, and a worst-case workbook
  • Open the output with the target spreadsheet application or downstream importer
  • Log product version, template version, profile, row count, output path, elapsed time, and warning count
  • Keep passwords, temporary files, customer data, and support bundles under explicit retention rules
  • Add regression workbooks when a customer file exposes a new edge case

Product documentation

HotXLS Component