Table of Contents

Read an Excel formula as its parts

XlsxFormula.Parse reads a formula as its tokens, its tree and every reference in it. The formula is read, and its text comes back character for character; to calculate formulas, see [Calculate formulas](xlsx-calculate.md).

dotnet add package DocWright.Spreadsheet

Parse a formula

using DocWright.Spreadsheet;

XlsxFormula formula = XlsxFormula.Parse("=IF(Data!$B$4>=10, SUM(B2:B9)*Rate, -Table1[[#Totals],[Qty]])");

Console.WriteLine(formula);                    // the text, character for character
foreach (XlsxFormulaToken token in formula.Tokens)
{
    if (token.Kind != XlsxFormulaTokenKind.Whitespace)
    {
        Console.WriteLine($"  {token.Kind,-19} {token.Text}");
    }
}

The leading = is optional. ToString() and the tokens' texts joined give the text back exactly: spacing, the case of a function's name and the way a reference is written are kept.

XlsxFormulaToken.Kind Example
Number, Text, Boolean, Error 1.5E+3, "a""b", TRUE, #N/A
Operator + - * / ^ & = <> < > <= >= % : @ #
OpenParenthesis, CloseParenthesis, Comma, Semicolon, OpenBrace, CloseBrace ( ) , ; { }
Function SUM, _xlfn.XLOOKUP: the name, without its parenthesis
Reference B4, $B$4:D8, A:C, 1:3, 'My Sheet'!B4, Jan:Mar!B4, [1]Sheet1!B4
Name Rate, Data!Rate
StructuredReference Table1[Qty], [@Qty]
R1C1Reference R[1]C[-1]: kept as text. A workbook file never holds one.
Whitespace, Unknown Spaces and line breaks; characters that are not part of a formula.

The references

using DocWright.Spreadsheet;

foreach (XlsxFormulaReference reference in formula.References)
{
    XlsxCellRange? cells = reference.Range;    // null for a name and a table
    string where = cells is null ? "" : $"rows {cells.Value.FirstRow} to {cells.Value.LastRow}";
    Console.WriteLine($"{reference.Kind,-5} {reference.Text,-24} sheet: {reference.Sheet ?? "its own",-8} {where}");
}
XlsxFormulaReference
Kind Cell, Range, Rows, Columns, Name, Table, or Deleted for Data!#REF!.
Text, Start, Length The reference as written and where it is in the formula.
Sheet The sheet's name without its apostrophes; null for the formula's own sheet.
LastSheet The last sheet of a reference through several sheets (Jan:Mar!B4).
Workbook The other workbook, for a reference into one (1 in [1]Sheet1!B4).
Name The defined name or the table's name.
Range The cells, corners in order. Whole rows cover every column. Null for a name and a table.
IsRowAbsolute, IsColumnAbsolute, IsLastRowAbsolute, IsLastColumnAbsolute Where the $ signs are, for each corner as written.

A reference is what the text says: a sheet that does not exist is still a reference, and a defined name is not resolved to its cells. What only looks like a cell is told apart: LOG10( is a function, ABC1!B2 names the sheet ABC1, and Tax_A1 is a name.

The tree

using DocWright.Spreadsheet;

// A stack of our own: a chain such as A1+A2+A3+... is as deep as it is long.
var pending = new Stack<(XlsxFormulaNode Node, int Depth)>();
pending.Push((formula.Root, 0));
while (pending.Count > 0)
{
    (XlsxFormulaNode node, int depth) = pending.Pop();
    Console.WriteLine($"{new string(' ', depth * 2)}{node.Kind} {node.Text}");
    for (int i = node.Children.Count - 1; i >= 0; i--)
    {
        pending.Push((node.Children[i], depth + 1));
    }
}

Root is an XlsxFormulaNode with a Kind, a Text, Children, and Start and Length in the formula. For a Function, Text is the name and the children are the arguments; an argument left empty is a Missing node. For an operator node, Text is the operator, and the intersection operator's text is one space.

The precedence is Excel's, tightest first: the range operator :, intersection (a space), union (a comma outside a function's arguments), the prefix operators, %, ^, * and /, + and -, &, the comparisons.

Note

Checked against Excel. -2^2 parses as (-2)^2, which is 4 in Excel, and 2^3^2 as (2^3)^2, which is 64. Of a list of formulas put to Excel, the 138 it takes parse and print back the same, and the 23 it refuses for their grammar are refused.

Important

Walk the tree with a stack of your own. A chain of one operator, such as A1+A2+A3+…, is as deep as it is long: up to 4,095 levels. One method call for each level can run out of stack.

The formulas of a workbook

XlsxDocumentCell.ParsedFormula is a cell's formula parsed, or null when the cell has no formula.

using DocWright.Spreadsheet;

// Which sheets do the formulas of a sheet read?
var sheets = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (XlsxDocumentCell cell in orders.Cells)
{
    XlsxFormula? parsed = cell.ParsedFormula;      // null: no formula
    if (parsed is null)
    {
        continue;
    }

    foreach (XlsxFormulaReference reference in parsed.References)
    {
        sheets.Add(reference.Sheet ?? orders.Name);
    }
}

Console.WriteLine("Orders reads: " + string.Join(", ", sheets));

What is not a formula

using DocWright.Spreadsheet;

Console.WriteLine(XlsxFormula.TryParse("SUM(A1", out _));      // False: no exception

try
{
    XlsxFormula.Parse("SUM(A1:A3)+*2");
}
catch (FormatException refused)
{
    Console.WriteLine(refused.Message);
}

TryParse returns false. Parse throws FormatException with the place and the reason, and ArgumentNullException for null.

Limit Value
Length, not counting a leading = XlsxFormula.MaxLength: 8,192 characters
Functions inside a function's arguments XlsxFormula.MaxNestingDepth: 64 levels
Parentheses inside one another 256

These are Excel's own limits, measured: text past one is refused. A function's name and its number of arguments are not checked, so FOO(1,2) parses.

Output

=IF(Data!$B$4>=10, SUM(B2:B9)*Rate, -Table1[[#Totals],[Qty]])
  Operator            =
  Function            IF
  OpenParenthesis     (
  Reference           Data!$B$4
  Operator            >=
  Number              10
  Comma               ,
  Function            SUM
  OpenParenthesis     (
  Reference           B2:B9
  CloseParenthesis    )
  Operator            *
  Name                Rate
  Comma               ,
  Operator            -
  StructuredReference Table1[[#Totals],[Qty]]
  CloseParenthesis    )

Cell  Data!$B$4                sheet: Data     rows 4 to 4
Range B2:B9                    sheet: its own  rows 2 to 9
Name  Rate                     sheet: its own  
Table Table1[[#Totals],[Qty]]  sheet: its own  

Function IF
  BinaryOperator >=
    Reference Data!$B$4
    Number 10
  BinaryOperator *
    Function SUM
      Reference B2:B9
    Name Rate
  PrefixOperator -
    StructuredReference Table1[[#Totals],[Qty]]

Orders reads: Orders, Rates, Year 2026

False
The formula is not valid at character 12: '*' is not expected.

What is not done

Calculation Not done by parsing: a formula cell's Value is the result the file stores until Calculate runs (Calculate formulas).
A sheet renamed, deleted, moved or copied Every reference follows: see Rename, delete, move and copy sheets. Inserting and deleting rows and columns rewrites them too: see Insert and delete rows and columns.
The R1C1 notation Kept as a token, not resolved.