Technical Article

Reading Excel Cached Formula Values in Delphi Without Recalc

Every workbook Excel has saved already carries the answer to each of its formulas. In the sheet XML of a typical .xlsx a total looks like <c r="E12"><f>SUM(E2:E11)</f><v>48210.5</v></c>, and that <v> is the number the author saw on screen when pressing Save. A nightly job pulling one column of totals out of a few hundred such files needs precisely that number. Most spreadsheet APIs, though, put a single question to a formula cell (what is your value?), and the only general way of answering it is to run the formula again, against whatever functions and external links the reading code happens to resolve

Evaluating a formula and reading its stored result call for two different methods

HotXLS answers the two questions through two entry points. On the classic TXLSWorkbook engine, asking a formula cell for its ordinary value sends the cell through the formula evaluator, which is what an application editing workbooks wants. TryGetCachedFormulaValue, available on both TXLSWorkbook and TXLSXWorkbook, answers the narrower question of what the producing application stored beside the formula. It does not call the calculator, run user-defined functions, decompile formula tokens, update dependencies or dirty state, or write anything into the cell model

Evaluation during an extract carries costs beyond CPU time. It writes results back into cells, so the in-memory workbook no longer matches the file it came from, and anything that later saves that object carries the recomputed numbers to disk. It can also disagree with Excel: a function the reader does not implement, or an external workbook absent from the extraction server, produces a different result from the one the author signed off on. The extract then loads that figure without any error, and it no longer matches the author's copy of the file

For a pipeline that only extracts, read the cache and make recalculation an explicit decision taken per workbook. A job your operations team was told is read-only should contain no code path capable of changing a number. When fresh results are what you actually want, HotXLS still provides incremental recalculation driven by a dependency graph, and you call it on purpose

Three facts about a single cached value

TXLSFormulaCacheInfo reports a cached formula value by way of three independent fields, a single Variant being unable to carry all of them. State (a TXLSFormulaCacheState) says where the value came from: xlfcsNotFormula, xlfcsMissing, xlfcsLoaded, xlfcsCalculated or xlfcsInvalidated. Kind (a TXLSFormulaCacheValueKind) classifies the payload as xlfcvBlank, xlfcvNumber, xlfcvDateTime, xlfcvString, xlfcvBoolean or xlfcvError. Value carries the payload itself

The split matters because a formula can legitimately evaluate to very little. A cached blank, an empty string, False, zero and an error code are all genuine results that Excel wrote into the file, and code testing VarIsEmpty or VarIsNull to decide whether a cache exists will misreport several of them. TryGetCachedFormulaValue returns True only when State is xlfcsLoaded or xlfcsCalculated; on False it still fills in State, so the caller can tell which case applied

The HotXLS record TXLSFormulaCacheInfo keeps three orthogonal facts about one formula cell apart: the provenance State across five cases, the payload Kind across six, and the Variant Value, so a cached blank or False is never taken for an absent cache
Provenance, payload type and payload value stay apart, which is the only way a cached blank, zero, empty string or error can be reported as the real value it is
var
  Book: TXLSXWorkbook;
  Info: TXLSFormulaCacheInfo;
begin
  Book := TXLSXWorkbook.Create;
  try
    Book.Open('quarterly-model.xlsx');
    // SheetIndex, Row and Col are all 1-based: sheet 1, cell E12
    if Book.TryGetCachedFormulaValue(1, 12, 5, Info) then
      Writeln('cached value: ', VarToStr(Info.Value))
    else
      Writeln('no usable cache, state ordinal ', Ord(Info.State));
  finally
    Book.Free;
  end;
end;

Why does TryGetCachedFormulaValue return False?

There are three ways of getting False, and State names each of them. xlfcsNotFormula means the cell holds a literal or nothing whatsoever; sheet, row or column indexes outside the workbook produce the same answer, so a typo in a column number looks like an empty cell rather than an exception. xlfcsMissing means the cell really is a formula, but the file stored no result for it. Report generators often write formulas and leave the results for Excel to fill in on first open, so every formula in such a file reports xlfcsMissing. xlfcsInvalidated means the formula text was replaced after the workbook was loaded, and the old result described an expression that no longer exists

xlfcsCalculated is the other success state. It marks a result produced during this session by the HotXLS evaluator, as against xlfcsLoaded, which came straight from the file. Most extract jobs will only ever see xlfcsLoaded, but a job that recalculates one workbook and then reads it back gets xlfcsCalculated, and logging the difference tells you later which numbers Excel produced and which ones your server did

The save path follows the same rules. Only xlfcsLoaded and xlfcsCalculated write a cached result into the output file; xlfcsMissing and xlfcsInvalidated write the formula alone, so a stale number never gets frozen into a file beside a formula it has no business belonging to

In a pipeline, a missing cache leaves three reasonable moves: skip the row and record the gap, recalculate that one workbook and accept the cost, or evaluate and compare. Recording the gap is the right default, keeping the extract honest and giving the file owner something concrete to fix. If you do evaluate and the result disagrees with what Excel would have written, the formula evaluation tracer shows where the two computations part company

A single reader interface for .xls, .xlsx and .ods

IXLSFormulaCacheReader gives extraction code one read-only entry point whatever the file format. TXLSWorkbook.CreateFormulaCacheReader covers classic .xls files, and TXLSXWorkbook.CreateFormulaCacheReader covers .xlsx along with OpenDocument spreadsheets loaded via TXLSXWorkbook.OpenODS. Both hand back a small object with a single method, TryGetCachedFormulaValue, taking the same 1-based sheet, row and column coordinates as the workbook method, and both look the cell up directly. Reading an empty coordinate creates no cell there

Pass the reader into your extraction routine and keep the workbook object out of it. The routine then has no means of editing, recalculating or saving anything. All it receives is an interface with one method, and that method only reads

function SumCachedColumn(const Reader: IXLSFormulaCacheReader;
  Sheet, Col, FirstRow, LastRow: Integer;
  out Missing, Errors: Integer): Double;
var
  Info: TXLSFormulaCacheInfo;
  Row: Integer;
begin
  Result := 0;
  Missing := 0;
  Errors := 0;
  for Row := FirstRow to LastRow do
    if Reader.TryGetCachedFormulaValue(Sheet, Row, Col, Info) then
    begin
      case Info.Kind of
        xlfcvNumber: Result := Result + Double(Info.Value);
        xlfcvError:  Inc(Errors);
      end;
    end
    else if Info.State = xlfcsMissing then
      Inc(Missing);
end;

// The same routine serves both engines (XlsBook: TXLSWorkbook, XlsxBook: TXLSXWorkbook)
Total := SumCachedColumn(XlsBook.CreateFormulaCacheReader, 1, 7, 2, 500, Missing, Errors);
Total := SumCachedColumn(XlsxBook.CreateFormulaCacheReader, 1, 7, 2, 500, Missing, Errors);

The reader does not keep its workbook alive. The workbook classes deliberately do not implement the interface themselves, so freeing a workbook works just as it always has, whatever reader references happen to be about. Once the workbook is gone, any reader created from it raises EXLSFormulaCacheReaderInvalidated on its next query. When that exception turns up in a log, the usual cause is a list of readers kept about longer than the batch that opened the files

Where the cached bytes sit, and which type comes back

Classic .xls: an eight-byte field that is not always a double

In a BIFF8 file the cache is the FormulaValue field of the Formula record, eight bytes described in [MS-XLS] §2.5.133. Usually those bytes are an IEEE 754 double. When the high word equals $FFFF, the field is a tagged variant instead: the type sits in val[0], the boolean or BErr error payload sits in val[2], and val[1] is undefined. A reader taking the payload from val[1] looks correct on every file caching numbers and strings, and goes wrong only on the cells caching TRUE or #N/A. HotXLS reads and writes the payload at the same offset, ordinary and shared formulas alike, so a cached boolean or error comes back unchanged after a load and save

The eight-byte FormulaValue field of a classic XLS Formula record as HotXLS reads it: an IEEE 754 double unless the high word equals FFFF, whereupon the variant type sits in val zero and the Boolean or error payload in val two
When the high word is FFFF the field is a tagged variant, and the payload sits in val[2] with val[1] undefined, which is precisely the byte a naive reader takes

A BIFF numeric cache carries no date flag. A formula like =TODAY()+30 formatted as a date still caches a plain number, so HotXLS returns it as a Double with Kind = xlfcvNumber. Turning it into a date is your decision, taken from the cell format you know about. The library does not guess from the number format, the format being presentation and the cache being data, and a guess would turn every serial-number-looking total into a date somewhere

OOXML and ODF: explicit types, and a Delphi RTL trap

In OOXML the cache is the <v> child of the c element, and the t attribute names its type (ECMA-376 Part 1 §18.3.1.4). HotXLS reads t="e" straight into a varError Variant, so an error never passes itself off as an ordinary integer, and writes the standard error text back on save. t="d" and the ODF date value type are explicit date declarations and come back as varDate with Kind = xlfcvDateTime

Building an error Variant yourself, say to compare against a cached one, runs into the Delphi RTL: VarAsType(Integer, varError) raises a conversion exception instead of producing an error Variant. The construction that works sets TVarData.VType and TVarData.VError directly

ODF has two cases of its own. office:value-type="void" declares a cache that exists yet holds no value; it loads as xlfcsLoaded with Kind = xlfcvBlank and a Null payload. And because ODF has no error value type, a cell whose cached text reads #DIV/0! remains a string. Promoting it to an error would mean divining an intent the file never stated

// Your own helper, not part of HotXLS: VarAsType(Code, varError) raises a conversion exception
function MakeErrorVariant(Code: Integer): Variant;
begin
  VarClear(Result);
  TVarData(Result).VType := varError;
  TVarData(Result).VError := Code;
end;

function DescribeCache(const Info: TXLSFormulaCacheInfo): string;
begin
  case Info.State of
    xlfcsNotFormula:  Result := 'not a formula cell';
    xlfcsMissing:     Result := 'formula stored with no cached value';
    xlfcsInvalidated: Result := 'formula replaced since load';
  else
    case Info.Kind of
      xlfcvError:    Result := 'error code ' + IntToStr(TVarData(Info.Value).VError);
      xlfcvDateTime: Result := DateTimeToStr(VarToDateTime(Info.Value));
      xlfcvBoolean:  Result := BoolToStr(Info.Value, True);
      xlfcvNumber:   Result := FloatToStr(Double(Info.Value));
      xlfcvString:   Result := VarToStr(Info.Value);
    else
      Result := 'present but blank';
    end;
  end;
end;

Do shared formulas share their cached values?

No. An OOXML shared formula shares the expression and the storage layout; each member cell still owns its own <v>. Assuming otherwise is how a sweep ends up reporting the root cell's total for an entire column. HotXLS never copies the root member's cache to a follower that arrived without one, and that follower reports xlfcsMissing both after load and after a save and reopen. How the group itself is stored and expanded is covered in the article on the shared formula si attribute and its expansion. For cache reading, the practical rule is to query every cell and treat each answer on its own merits

A HotXLS view of an OOXML shared formula group in which the si attribute shares only the expression and the storage layout, wherein every member cell owns its own cached value, so a follower that loaded without one carries on reporting xlfcsMissing
The group shares the expression, not the numbers, so the root cache is never propagated and a member arriving without a value keeps reporting that gap

The cache reader, the per-workbook TryGetCachedFormulaValue and the recalculation engine you can leave switched off all form part of the HotXLS Delphi Spreadsheet Component, which reads and writes .xls, .xlsx and .ods from Delphi and C++Builder with no Excel installation. The product page carries the full reference for both workbook classes and the reader interface