Technical Article

Pull Row Cursor for XLS, XLSX, ODS and CSV in Delphi

A callback-driven spreadsheet reader handed a 200 MB ledger and the requirement "stop after the hundredth reversed posting" needs three pieces of machinery before it reads a single cell: a counter that survives between calls, an abort flag the parser checks after each cell, and a class whose only job is to give the handler somewhere to keep that state. The logic itself is one Break. A pull cursor, where your code asks for the next row instead of being called with it, lets you write that Break and keep the counter in a local variable

The counter is the mild case. A push API owns the loop, so a caller that needs to merge two sources row by row, look at the next record before deciding what to do with the current one, or hand the reader to a routine that expects to drive it, ends up buffering rows or building a small state machine inside the handler. Throughput is rarely the complaint. The cost lands in the calling code, and it multiplies once each file format has its own scanning entry point with its own idea of what a filter means

Giving the loop back with TXLSRowCursor

HotXLS exposes the pull model as TXLSRowCursor in lxDirectRead.pas. TXLSRowCursor.Open takes a file name or a TStream plus an optional TXLSForwardFormat (xffAuto by default, or xffXls, xffXlsx, xffOds, xffCsv, xffTsv), detects the format when asked to, loads the shared-string table and date-style metadata once, and leaves sheet 1 selected. One class covers .xls, .xlsx, .xlsm, .ods, CSV and TSV. SelectSheet takes a 1-based index; SelectSheetByName compares names case-insensitively and returns False when no sheet matches

FindFirst and FindNext each move to the next row that holds at least one cell and return False once the sheet is exhausted. Empty rows are skipped, so RowIndex, the 1-based worksheet row number, can go from 3 to 7 in one step. The current row is readable three ways: CellCount; Cells[0..CellCount-1] in document order, each record carrying a 1-based Col; and ValueByCol[], which takes a 1-based column and returns Null when that column has no cell on the current row

var
  Cursor: TXLSRowCursor;
  Hits: Integer;
begin
  Cursor := TXLSRowCursor.Create;
  try
    Cursor.FirstRow := 2;        // row 1 is the header
    Cursor.IncludeColumn(1);     // decode only the account and status columns
    Cursor.IncludeColumn(7);
    if not Cursor.Open('postings-200mb.xlsx') then
      Exit;
    if not Cursor.SelectSheetByName('Ledger') then
      Exit;

    Hits := 0;
    if Cursor.FindFirst then
      repeat
        if VarToStr(Cursor.ValueByCol[7]) = 'REVERSED' then
        begin
          Inc(Hits);
          if Hits = 100 then
            Break;               // an ordinary Break ends the scan
        end;
      until not Cursor.FindNext;
  finally
    Cursor.Free;                 // Free also closes the source
  end;
end;

Range and column projection are fixed before the pass starts

FirstRow, LastRow, IncludeColumn, ClearColumnProjection, IncludeFormulaText, DetectDates, DetectTextTypes, ValueSeparator and SharedStringMemoryLimit are applied by the format reader while it scans, rather than as a filter over rows that were already decoded. A column outside the projection is dropped before its value, formula text or rich-text runs ever become a cell, so a sheet with a wide free-text comment column costs nothing extra when you only ask for columns 1 and 7. With LastRow set, the scan stops at that row instead of reading the rest of the worksheet and throwing it away

Those options are locked while a pass is running. Assigning any of them between FindFirst and the end of the sheet raises EInvalidOperation with the message "read options cannot change during an active pass". They become writable again once FindNext returns False, after Cancel or SelectSheet, and after Close. The lock is there because a scan that flipped DetectDates halfway through would hand you a column whose first few thousand rows are TDateTime values and whose remainder are serial numbers, with nothing in the cell records to say where the switch happened. An exception on the assignment line is the better failure. PreserveRichText is stricter: it decides how the shared-string table is loaded, so it must be set before Open, and changing it on an open cursor raises

When you only need the sheet inventory, SheetCount and SheetNames[] are available right after Open without starting a pass. For dimensions and other per-sheet details without the cell data, metadata-only and selective sheet loading is the cheaper entry point

Four file formats behind one row shape

Each format has exactly one forward reader behind TXLSRowCursor, and whatever the source, the caller receives the same TXLSRowCursorCell records. Lining the formats up meant handling what each file layout does at the row level

CSV and TSV

A CSV file does not declare its delimiter. With ValueSeparator left at #0, the cursor counts commas, tabs, semicolons and pipes in the first record, ignoring anything inside double quotes, and takes the most frequent; on a tie the one listed earlier in comma, tab, semicolon, pipe order wins, and with none present it falls back to comma. TSV defaults to tab, and any non-zero ValueSeparator overrides both. A quoted field that spans several lines is joined back with #10, so RowIndex counts logical records — a three-line address in record 40 does not push record 41 down to row 43. Empty fields produce no cell, which makes ValueByCol return Null for them exactly as it would for an unpopulated workbook cell. Input is read through a BOM-aware reader that falls back to UTF-8 when there is no byte-order mark

OpenDocument spreadsheets

ODS (OpenDocument §9) stores runs of identical rows compactly: a single <table:table-row> element with table:number-rows-repeated set to 1000 stands for a thousand rows. Expanding that up front is the naive reading and the expensive one. The cursor keeps the one physical row and counts the repeat down as you advance, so each repetition comes back under its own RowIndex with no copies held in memory. Cells hidden under a merged range (table:covered-table-cell) are stepped over to keep the column numbers right, and contribute no value

Classic .xls workbooks

The BIFF8 record stream described in [MS-XLS] has the sharpest edge. A formula whose cached result is text is stored as a Formula record followed immediately by a String record that carries the text. Any reader that pauses at row boundaries has to treat that pair as one unit; split them, and the formula cell comes back without its value while the next row opens on a stray String record. TXLSRowCursor holds a pending formula until its String record arrives before it hands you the row. The forward .xls path also leaves formula tokens compiled, so a classic formula cell reports HasFormula = True, FormulaTextAvailable = False, an empty Formula, and the cached result in Value. Blank and MulBlank records, which are formatted cells with no value, arrive as cells of kind xdkEmpty carrying their StyleIndex

The HotXLS pull row cursor dispatching to one forward scanner per format: an .xlsx row reader, an .xls record reader, a CSV/TSV reader with delimiter detection and an ODS row reader, with the callback reader built on the same cursor
Every format has exactly one forward scanner, and both the pull cursor and the callback reader drive that same scanner, so filtering and error semantics cannot drift apart

Why does an Eof flag hide how a pass ended?

TXLSRowCursor.Eof returns True in four different situations: no source open, sheet read to the end, pass cancelled by the caller, pass failed. Code that checks only Eof after the loop will log a damaged worksheet part as an empty sheet. TXLSRowCursor.State separates them with TXLSRowCursorState

  • xrcsClosed — no source is open
  • xrcsBeforeFirst — opened or re-targeted by SelectSheet, no row read yet
  • xrcsActive — standing on a valid row
  • xrcsEof — the sheet was read to the end
  • xrcsCancelled — the caller stopped the pass with Cancel
  • xrcsFaulted — the pass raised an exception

A missing or unreadable worksheet part raises EReadError from FindFirst. Any exception during FindFirst or FindNext drops the current row, moves the cursor to xrcsFaulted and is re-raised unchanged, so "this sheet was empty" and "this sheet could not be read" never share a plain False return

Cancel and Close do different amounts of work. Cancel stops the current worksheet pass, clears the row and sets RowIndex to 0, while the workbook stays open: shared strings, the sheet list and the source stream are all kept. A second Cancel does nothing. After a cancel or a fault, FindFirst keeps returning False until you call SelectSheet; the cursor will not restart a pass behind your back. Close releases everything and returns to xrcsClosed. Keep the source unchanged while a pass runs, since rows are read from it on demand

Stream ownership follows the same conservative line. Under xsoBorrowed, the default, the cursor never frees your stream, and Close puts the stream position back where it was when Open was called. xsoOwned transfers the stream only when Open returns True; if Open fails, freeing the stream is still your job. Stay with xsoBorrowed unless the stream exists solely for the cursor — a finally block you can read is easier to audit than an ownership transfer that depends on a return value

The six states of the HotXLS row cursor with the transitions between them, showing Cancel moving an active pass to canceled, a failed pass start moving it to faulted, and how both stay distinct from end of sheet
Six named states keep an empty sheet, a deliberate stop and a failed pass distinguishable, which a single Eof boolean cannot do
var
  Cursor: TXLSRowCursor;
  Src: TFileStream;
begin
  Src := TFileStream.Create('quarter.ods', fmOpenRead or fmShareDenyWrite);
  try
    Cursor := TXLSRowCursor.Create;
    try
      if not Cursor.Open(Src, xffAuto, xsoBorrowed) then
        Exit;                        // Src is still ours; the outer finally frees it

      try
        if Cursor.FindFirst then
          repeat
            // UserPressedStop, ProcessRow and Log are your own routines
            if UserPressedStop then
            begin
              Cursor.Cancel;         // ends this pass; the workbook stays open
              Break;
            end;
            ProcessRow(Cursor);
          until not Cursor.FindNext;
      except
        on E: Exception do
          Log('pass failed: ' + E.Message);   // State is xrcsFaulted here
      end;

      case Cursor.State of
        xrcsEof:       Log('sheet read to the end');
        xrcsCancelled: Log('stopped by the operator');
        xrcsFaulted:   Log('see the error logged above');
      end;

      // A cancelled or faulted pass needs an explicit SelectSheet before FindFirst
      if (Cursor.State in [xrcsCancelled, xrcsFaulted]) and
         Cursor.SelectSheet(Cursor.SheetIndex) then
        Log('ready for a fresh pass over sheet ' + IntToStr(Cursor.SheetIndex));
    finally
      Cursor.Free;                   // borrowed: position restored, Src not freed
    end;
  finally
    Src.Free;
  end;
end;

Passing the current row to another routine

TXLSRowCursor.CurrentRowView returns an IXLSRowCursorView that reads the current row in place, without copying the cell array. The view mirrors the cursor's row members and adds Valid. Each view belongs to exactly one row: FindNext, SelectSheet, Cancel, Close and freeing the cursor all retire it. From then on Valid returns False without raising, and every other member raises EXLSRowCursorViewInvalidated, a descendant of EInvalidOperation

What the view checks is lifetime. It does not make the cursor shareable between threads, and reading a view on one thread while another calls FindNext is outside its contract. When a row has to outlive the loop, say because it is queued for a worker, copy the values you need out of Cells[] into your own record

var
  View: IXLSRowCursorView;
  Cell: TXLSRowCursorCell;
  I: Integer;
begin
  if Cursor.FindFirst then
    repeat
      View := Cursor.CurrentRowView;        // reads the row in place, no copy
      for I := 0 to View.CellCount - 1 do   // Cells[] is 0-based; Cell.Col is 1-based
      begin
        Cell := View.Cells[I];
        // UseCachedResult, UseStyleOnly and UseValue are your own routines
        if Cell.HasFormula and not Cell.FormulaTextAvailable then
          UseCachedResult(Cell.Col, Cell.Value)    // .xls: cached result only
        else if Cell.Kind = xdkEmpty then
          UseStyleOnly(Cell.Col, Cell.StyleIndex)  // formatted blank cell
        else
          UseValue(Cell.Col, Cell.Value);
      end;
    until not Cursor.FindNext;

  // The interface variable outlives the loop; the row behind it does not
  if (View <> nil) and not View.Valid then  // Valid never raises
    View := nil;  // View.Cells[0] at this point would raise EXLSRowCursorViewInvalidated
end;

How do you check that memory follows row width?

TXLSRowCursor.PeakRowBufferedBytes reports the largest amount the cursor estimates it held for one logical row since the last Open. The estimate adds up the current row's cell records, their Variant values, formula strings and rich-text runs, and folds in the per-format working set: the logical CSV record, the ODS row being repeated, the largest .xls record read so far, or the raw .xlsx cell being decoded. SheetPassesStarted sits next to it and counts how many worksheet passes actually began

The figure is computed from string lengths and record sizes rather than measured on the heap, and it only rises until the next Open. That makes it a regression instrument for your own import code. A check you can run yourself: build two workbooks with identical columns, one with ten thousand rows and one with a million, read both with the same projection, and compare PeakRowBufferedBytes. Expected: the two values land close together, while widening a single row with a long text cell moves the figure. For the wider picture on very large books, see large workbook performance in Delphi

A HotXLS comparison showing a whole-sheet load keeping every row resident against the pull cursor holding only the current row plus one format working set, which is what PeakRowBufferedBytes accumulates and reports
PeakRowBufferedBytes accumulates the current output row plus the format-specific working set, so memory tracks how wide a row is rather than how many rows the sheet has

TXLSForwardReader runs on the same cursor

TXLSForwardReader, the callback reader with OnSheet and OnCell events, is built on TXLSRowCursor. Its ReadFile and ReadStream copy the reader's options onto a cursor, walk every sheet, and turn each cell of each row into an OnCell call. Because both front ends drive the same format readers, a column projection, a LastRow limit or a malformed record behaves the same whichever one you call, and OnSkippedRecord reports skipped content on both. The streaming direct reader shares the shared-string and date-style loading with the cursor

Two details of the callback contract follow from that design. OnSheet fires before the sheet is selected, so setting SkipSheet to True means that worksheet part is never opened or decompressed, and SheetPassesStarted does not count it. SheetIndex in TXLSForwardReader events is 1-based, matching SelectSheet, whereas TXLSDirectReader reports a 0-based SheetIndex in its own OnSheet event; code that moves between the two readers has to adjust by one. Setting Abort in either TXLSForwardReader event cancels the pass and leaves Aborted at True

For an import with an exit condition, a join across two sources or a lookahead, write it against TXLSRowCursor. TXLSForwardReader remains the shorter code for a whole-book dump where skipping sheets is the only control you need. Editions, supported IDE versions and licensing are listed on the HotXLS Delphi spreadsheet component page