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

HotXLS Component: ODS open, save, and round-trip in Delphi

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

Эта статья предназначена для teams accepting OpenDocument Spreadsheet files while still producing Excel-compatible workflows. Она рассматривает ODS open, save, and round-trip как промышленную инженерию документов, а не как одиночный вызов компонента.

Практический риск состоит в том, что round-trip support can preserve values but still lose formulas, styles, charts, or page settings when feature gaps are not reported. Поэтому процессу нужны письменный контракт, наблюдаемая диагностика и реалистичные регрессионные файлы.

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

Classify ODS compatibility before editing. accepted ODS sources, supported feature set, and blocked feature categories / formula, style, chart, image, conditional formatting, and page setup handling

  • accepted ODS sources, supported feature set, and blocked feature categories
  • formula, style, chart, image, conditional formatting, and page setup handling
  • save format after editing and whether the user expects ODS or XLSX output
  • warning policy for unsupported or approximated features

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

Track what is preserved, converted, or dropped. The order below keeps the workflow reviewable for Delphi and C++Builder teams.

  1. inspect the ODS package and create a feature inventory before editing
  2. map sheets, cells, formulas, styles, images, and charts to supported workbook objects
  3. apply edits while preserving original intent where possible
  4. save output in the chosen format and compare key sheets with the source
  5. attach a compatibility report when features are converted or dropped

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

Round-trip evidence for customer trust. Keep these fields with the output or support record.

  • source format, sheet count, formula count, style count, chart count, and image count
  • preserved, converted, approximated, and dropped feature counts
  • output format, warning summary, and key-cell comparison
  • viewer compatibility notes for LibreOffice and Excel when relevant

OpenDocument and Excel models overlap but differ

ODS support should identify which workbook features map cleanly, which require conversion, and which need warnings. A professional workflow gives users evidence instead of pretending every spreadsheet model is identical.

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

Рассматривайте HotXLS Component: ODS open, save, and round-trip in Delphi как явный сервисный контракт вокруг вызовов HotXLS, разделяя проверку входных данных, запись книги, контроль результата и сведения для поддержки

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

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

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

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

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

procedure RoundTripOdsWorkbook(const InputOds, OutputOds: string);
var
  Wb: TXLSXWorkbook;
  BeforeState: TWorkbookInventory;
  AfterState: TWorkbookInventory;
begin
  RequireFileExists(InputOds);
  Wb := TXLSXWorkbook.Create;
  try
    Wb.Open(InputOds);
    BeforeState := CaptureWorkbookInventory(Wb);
    NormalizeFeaturesForOdsOutput(Wb);
    WriteCompatibilitySheet(Wb, BeforeState, 'ods-round-trip');

    if Wb.SaveAs(OutputOds) <> 1 then
      RaiseWorkbookSaveError(OutputOds);

    AfterState := InspectSavedWorkbook(OutputOds);
    CompareRoundTripInventory(BeforeState, AfterState, [
      'sheet-count',
      'used-ranges',
      'formula-cells',
      'visible-styles'
    ]);
  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