Artykuł techniczny

HotXLS Component: large workbook performance in Delphi

Twórz, edytuj, sprawdzaj, obliczaj i eksportuj skoroszyty Excel bezpośrednio z kodu Delphi lub C++Builder. HotXLS to natywna biblioteka Object Pascal z kodem źródłowym dla przepływów XLS i XLSX, przeznaczona do narzędzi desktopowych, zadań batch, systemów raportowych i generowania dokumentów po stronie serwera bez automatyzacji Microsoft Excel.

Ten artykuł jest przeznaczony dla teams generating or processing large XLS/XLSX workbooks in desktop utilities, services, or batch jobs. Traktuje large workbook performance jako produkcyjną inżynierię dokumentów, a nie pojedyncze wywołanie komponentu.

Praktyczne ryzyko polega na tym, że large-workbook workflows fail when shared strings, styles, formulas, memory buffers, and output streams are not managed as production resources. Dlatego przepływ wymaga spisanego kontraktu, obserwowalnej diagnostyki i realistycznych plików regresyjnych.

Decyzje architektoniczne

Plan memory, styles, and streaming together. maximum row count, column count, sheet count, and output file size / shared-string strategy, style reuse, formula volume, and image policy

  • maximum row count, column count, sheet count, and output file size
  • shared-string strategy, style reuse, formula volume, and image policy
  • streaming write boundaries, temporary storage, progress, and cancellation
  • Excel compatibility limits and downstream import limits

Przebieg implementacji

Measure workbook size during generation. Poniższa kolejność zachowuje czytelność przepływu pracy dla zespołów Delphi i C++Builder.

  1. create capacity fixtures that represent real customer data distribution
  2. reuse styles and strings instead of generating unique resources per cell
  3. write rows in controlled batches and flush output only at safe boundaries
  4. track memory, elapsed time, file size, and warning counts per stage
  5. open large output with the target application before increasing limits

Dowody walidacji

Performance evidence for capacity planning. Zachowaj te pola wraz z wynikiem lub rekordem wsparcia.

  • row count, column count, sheet count, style count, shared-string count, and file size
  • memory peak, elapsed time, batch size, temporary storage, and cancellation result
  • formula count, image count, comment count, and relationship count
  • target Excel or importer open time for representative output

Rows are not the only scale factor

Workbook size grows with cells, styles, shared strings, formulas, images, comments, and relationships. A performance plan should reduce redundant resources and choose streaming only where it fits the output contract.

Uwagi wdrożeniowe dla produkcji

Traktuj HotXLS Component: large workbook performance in Delphi jako jawny kontrakt usługi wokół wywołań HotXLS, oddzielając walidację wejścia, zapis skoroszytu, kontrolę wyniku i dowody dla wsparcia

  • Ustal źródło danych, zakresy komórek i format wyjściowy przed utworzeniem skoroszytu
  • Zapisuj liczbę wierszy, arkusze, ostrzeżenia i ścieżkę wyjściową w możliwym do sprawdzenia logu
  • Szczegóły aplikacji zamykaj w testowalnych helperach zamiast w zdarzeniach UI
  • Otwórz lub sprawdź zapisany plik przed przekazaniem go do innego systemu lub klienta

Tryby awarii do przećwiczenia

  • Udany SaveAs nie dowodzi, że kontrakt biznesowy nadal jest poprawny
  • Czcionki, uprawnienia i ustawienia regionalne mogą różnić się między serwerem a maszyną deweloperską
  • Logi nie mogą ujawniać haseł, danych klientów ani linków wewnętrznych

Szczegółowy przykład Delphi

Poniższy przykład Delphi pokazuje praktyczną granicę usługi dla tego tematu, z polityką, logowaniem i walidacją w warstwie możliwej do testowania

procedure WriteLargeLedgerWorkbook(const OutputFile: string; const Source: ILedgerReader);
var
  Wb: TXLSXWorkbook;
  Sh: IXLSWorksheet;
  RowIndex: Integer;
  Batch: TArray<TLedgerRow>;
  Item: TLedgerRow;
  Metrics: TWorkbookMetrics;
begin
  Wb := TXLSXWorkbook.Create;
  try
    Sh := Wb.Sheets[0];
    Sh.Name := 'Ledger';
    WriteHeaderRow(Sh, ['Account', 'Date', 'Description', 'Debit', 'Credit', 'Balance']);
    RowIndex := 2;
    Metrics := StartWorkbookMetrics('large-ledger');

    repeat
      Batch := Source.ReadNextBatch(5000);
      for Item in Batch do
      begin
        WriteLedgerRow(Sh, RowIndex, Item);
        Inc(RowIndex);
      end;
      CheckMemoryAndTempQuota(Metrics, RowIndex - 2);
      FlushProgressMetric(Metrics, RowIndex - 2);
    until Length(Batch) = 0;

    Sh.Range['A1:F1'].ApplyBuiltinStyle(xbsTitle);
    AddSummarySheet(Wb, Metrics, RowIndex - 2);
    AssertWorkbookSizePolicy(OutputFile, RowIndex - 2);

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

Lista produkcyjna

  • 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

Dokumentacja produktu

HotXLS Component

Dodatkowe przykłady kodu

// hoist pool lookups out of the hot loop
HeaderFont := Book.Fonts.Add('Calibri', 11, True, False);   // 0-based pool index
for C := 1 to 24 do
  Sheet.Cells[1, C].FontIndex := HeaderFont + 1;            // cells store 1-based; 0 = default
procedure TLedgerExport.FillRow(Sender: TObject;
  SheetIndex, Row, FirstCol, LastCol: Integer;
  var Values: Variant; var Skip: Boolean; var Cancel: Boolean);
begin
  if Row > FCount then
  begin
    Cancel := True;     // stop the whole write
    Exit;
  end;
  Values := VarArrayOf([FRows[Row - 1].Account,
                        FRows[Row - 1].PostedOn,
                        FRows[Row - 1].Amount]);
end;

// one engine call instead of hundreds of thousands of property hits
Sheet.WriteRows(1, 1, FCount, 3, FillRow);
Names := TStringList.Create;
Book := TXLSXWorkbook.Create;
try
  if Book.GetSheetNames('big-unknown.xlsx', Names) <= 0 then
    raise Exception.Create('cannot enumerate sheets');   // failure clears the list
  // pick the target sheet, then decide whether a full Open is worth it
finally
  Book.Free;
  Names.Free;
end;