Calculate formulas
XlsxDocument.Calculate gives every formula the value Excel gives it, in the order the formulas read each other, and the saved workbook carries the results. Evaluate calculates a formula written nowhere. Measured against Excel: thousands of formulas over edge values give Excel's own results.
dotnet add package DocWright.Spreadsheet
Calculate a workbook
using DocWright.Spreadsheet;
XlsxCalculationResult result = workbook.Calculate();
Console.WriteLine($"{result.Calculated} formulas calculated, complete: {result.IsComplete}");
Console.WriteLine($"D5 = {sheet.GetCell("D5").Value.NumberValue}, D6 = {sheet.GetCell("D6").Value.TextValue}");
Formulas are calculated after the cells they read, whatever their order in the sheet. When everything was calculated and nothing changed after, the saved workbook no longer asks Excel to calculate it when it opens. A formula that uses a function not calculated here, one that reads another workbook, a cycle, and the cells that read them keep the values the file stores; XlsxCalculationResult names them, and the workbook still asks Excel to calculate. Set XlsxCalculationOptions.UnknownFunction to NameError to calculate an unknown function as #NAME? instead.
Names, tables, criteria and TEXT
Defined names (the sheet's own before the workbook's), table references (Orders[Qty], Orders[@Qty], Orders[#All]), references through several sheets (SUM(Jan:Mar!B4)), COUNTIF, SUMIF, AVERAGEIF and their S forms, SUBTOTAL and TEXT are calculated as Excel calculates them:
using System.Globalization;
using DocWright.Spreadsheet;
sheet.Tables.Add(new XlsxCellRange(1, 1, 5, 4), "Orders");
workbook.Names.Add("TaxRate", "0.15");
for (int r = 2; r <= 5; r++)
{
sheet.SetFormula(r, 4, "Orders[@Qty]*Orders[@Price]*(1+TaxRate)"); // this row of the table
}
sheet.SetFormula("F1", "SUMIF(Orders[Region],\"North\",Orders[Total])");
sheet.SetFormula("F2", "COUNTIFS(Orders[Qty],\">2\",Orders[Region],\"<>East\")");
sheet.SetFormula("F3", "SUBTOTAL(109,Orders[Total])");
sheet.SetFormula("F4", "TEXT(F3,\"#,##0.00\")&\" on \"&TEXT(45000,\"d mmm yyyy\")");
XlsxCalculationResult result = workbook.Calculate();
for (int r = 1; r <= 4; r++)
{
XlsxCellValue value = sheet.GetCell(r, 6).Value;
Console.WriteLine($"F{r} = {(value.Kind == XlsxCellValueKind.Number ? value.NumberValue.ToString(CultureInfo.InvariantCulture) : value.TextValue)}");
}
F1 = 31.625
F2 = 2
F3 = 66.7
F4 = 66.70 on 15 Mar 2023
Mittwoch, 15. März 2023
Criteria follow Excel: ">2", "<>East", a bare value or a cell, with *, ? and ~ as wildcards in text. SUBTOTAL leaves out other subtotals, and 101 to 111 leave out hidden rows. TEXT formats in XlsxCalculationOptions.Culture, English (United States) by default, where Excel takes the machine's:
using System.Globalization;
using DocWright.Spreadsheet;
var german = new XlsxCalculationOptions { Culture = new CultureInfo("de-DE") };
Console.WriteLine(sheet.Evaluate("TEXT(45000,\"dddd, d. mmmm yyyy\")", german).TextValue);
Lookups, text and dates
VLOOKUP, XLOOKUP, INDEX, MATCH, OFFSET, INDIRECT and the other lookup and reference functions, the text functions (FIND, SUBSTITUTE, TEXTJOIN, PROPER...) and the date and time functions (DATE, WORKDAY, NETWORKDAYS, EDATE, DATEDIF, YEARFRAC...) are calculated as Excel calculates them, its 1900 leap-year rule and the 1904 date system included:
using System.Globalization;
using DocWright.Spreadsheet;
sheet.SetFormula("D1", "XLOOKUP(\"St*\",A2:A5,B2:B5,\"none\",2)"); // wildcard match
sheet.SetFormula("D2", "INDEX(A2:A5,MATCH(MAX(B2:B5),B2:B5,0))");
sheet.SetFormula("D3", "SUM(INDIRECT(\"B2:B\"&COUNTA(A2:A5)+1))"); // a reference made as it runs
sheet.SetFormula("D4", "TEXTJOIN(\", \",TRUE,A2:A5)");
sheet.SetFormula("D5", "TEXT(WORKDAY(DATE(2026,12,23),3),\"dddd d mmm yyyy\")");
sheet.SetFormula("D6", "TODAY()-DATE(2026,1,1)");
// TODAY and NOW are the moment the options give; no clock is read.
var options = new XlsxCalculationOptions { Now = new DateTime(2026, 11, 19, 9, 30, 0) };
XlsxCalculationResult result = workbook.Calculate(options);
for (int r = 1; r <= 6; r++)
{
XlsxCellValue value = sheet.GetCell(r, 4).Value;
Console.WriteLine($"D{r} = {(value.Kind == XlsxCellValueKind.Number ? value.NumberValue.ToString(CultureInfo.InvariantCulture) : value.TextValue)}");
}
D1 = 9.9
D2 = Ink
D3 = 27.65
D4 = Ink, Paper, Pens, Stapler
D5 = Monday 28 Dec 2026
D6 = 322
An approximate lookup over data that is not in order gives Excel's own answer. A reference OFFSET or INDIRECT makes as the formula runs orders the calculation too. TODAY and NOW give XlsxCalculationOptions.Now: no clock is read, and without it such a formula keeps its stored value.
Math, trigonometry and random numbers
The mathematical and trigonometric functions are calculated as Excel calculates them: SUMPRODUCT (an operator over ranges inside it works on every value), MROUND, CEILING.MATH, GCD, MMULT, MDETERM and the rest. RAND and RANDBETWEEN draw from XlsxCalculationOptions.RandomSeed, the same numbers on every run:
using System.Globalization;
using DocWright.Spreadsheet;
sheet.SetFormula("D1", "SUMPRODUCT((A1:A4>5)*A1:A4*B1:B4)"); // an operator over ranges, inside SUMPRODUCT
sheet.SetFormula("D2", "CEILING.MATH(D1,5)");
sheet.SetFormula("D3", "GCD(A1:A4)&\"/\"&LCM(A1:A4)");
sheet.SetFormula("D4", "INDEX(MMULT({1,2;3,4},{5;6}),2,1)");
sheet.SetFormula("D5", "RANDBETWEEN(1,6)"); // drawn from the seed
var options = new XlsxCalculationOptions { RandomSeed = 2026 };
XlsxCalculationResult result = workbook.Calculate(options);
for (int r = 1; r <= 5; r++)
{
XlsxCellValue value = sheet.GetCell(r, 4).Value;
Console.WriteLine($"D{r} = {(value.Kind == XlsxCellValueKind.Number ? value.NumberValue.ToString(CultureInfo.InvariantCulture) : value.TextValue)}");
}
D1 = 61
D2 = 65
D3 = 1/420
D4 = 39
D5 = 6
Without a seed, a formula that draws a random number keeps its stored value. XlsxCalculationLimits.MaxArrayCells bounds the arrays a formula makes from ranges.
Statistics
MEDIAN, the STDEV and VAR families, PERCENTILE, QUARTILE, RANK, CORREL, FORECAST.LINEAR, LINEST (one x column), FREQUENCY, MAXIFS and the other statistical functions are calculated as Excel calculates them:
using System.Globalization;
using DocWright.Spreadsheet;
sheet.SetFormula("D1", "MEDIAN(B1:B6)");
sheet.SetFormula("D2", "PERCENTILE.INC(B1:B6,0.9)");
sheet.SetFormula("D3", "CORREL(A1:A6,B1:B6)");
sheet.SetFormula("D4", "FORECAST.LINEAR(12,B1:B6,A1:A6)"); // the score 12 hours would give
sheet.SetFormula("D5", "INDEX(FREQUENCY(B1:B6,{60,80}),2)"); // scores above 60, up to 80
XlsxCalculationResult result = workbook.Calculate();
for (int r = 1; r <= 5; r++)
{
Console.WriteLine($"D{r} = {sheet.GetCell(r, 4).Value.NumberValue.ToString(CultureInfo.InvariantCulture)}");
}
D1 = 69.5
D2 = 84.5
D3 = 0.997910659634854
D4 = 98.5952380952381
D5 = 4
Distributions and tests
The normal, t, chi-square, F, binomial, Poisson and the other distributions, their inverses (NORM.S.INV, T.INV.2T, CHISQ.INV.RT...) and the tests (T.TEST, Z.TEST, F.TEST, CHISQ.TEST) are calculated to the double's precision:
using System.Globalization;
using DocWright.Spreadsheet;
sheet.SetFormula("D1", "NORM.S.INV(0.975)");
sheet.SetFormula("D2", "T.INV.2T(0.05,5)"); // the two-tailed 5% critical value, 5 degrees of freedom
sheet.SetFormula("D3", "T.TEST(A1:A6,B1:B6,2,1)"); // a paired test of before and after
sheet.SetFormula("D4", "BINOM.DIST(3,10,0.2,TRUE)");
XlsxCalculationResult result = workbook.Calculate();
for (int r = 1; r <= 4; r++)
{
double value = (double)sheet.GetCell(r, 4).Value.NumberValue;
Console.WriteLine($"D{r} = {value.ToString("G12", CultureInfo.InvariantCulture)}");
}
D1 = 1.95996398454
D2 = 2.57058183564
D3 = 0.000332658686608
D4 = 0.8791261184
Financial functions
The annuity functions (PMT, IPMT, FV, PV, RATE...), NPV, IRR, XIRR, depreciation and the bond functions are calculated as Excel calculates them. A root search (RATE, IRR, XIRR, YIELD) converges where Excel's does, solved to the root itself:
using System.Globalization;
using DocWright.Spreadsheet;
sheet.SetFormula("C1", "PMT(0.05/12,360,250000)"); // a monthly repayment
sheet.SetFormula("C2", "NPV(0.08,A2:A5)+A1");
sheet.SetFormula("C3", "IRR(A1:A5)");
sheet.SetFormula("C4", "DDB(30000,3000,5,2)");
XlsxCalculationResult result = workbook.Calculate();
for (int r = 1; r <= 4; r++)
{
double value = (double)sheet.GetCell(r, 3).Value.NumberValue;
Console.WriteLine($"C{r} = {value.ToString("G12", CultureInfo.InvariantCulture)}");
}
C1 = -1342.05405753
C2 = 605.363530477
C3 = 0.104845294792
C4 = 7200
Database, engineering and information functions
The database functions (DSUM, DCOUNT, DGET and the rest) take a criteria range as Excel does: headings in its first row, criteria that must all hold in a row, any row picking a record, text picking what begins with it. CONVERT knows every unit Excel documents, with its prefixes; the base conversions, the BIT functions and the complex-number functions (IMSUM, IMPRODUCT, IMSQRT...) are there too, and so are TYPE, ERROR.TYPE, SHEET, SHEETS, FORMULATEXT, ISFORMULA, ISREF, N, T and CELL for a cell's row, column, contents and type:
using DocWright.Spreadsheet;
// A criteria range for the database functions: "P" picks the items that begin with P.
sheet.SetValue("D1", XlsxCellValue.Text("Item"));
sheet.SetValue("D2", XlsxCellValue.Text("P"));
sheet.SetFormula("F1", "DSUM(A1:B5,\"Qty\",D1:D2)");
sheet.SetFormula("F2", "CONVERT(26.2,\"mi\",\"km\")");
sheet.SetFormula("F3", "DEC2HEX(255,4)");
sheet.SetFormula("F4", "IMPRODUCT(\"3+4i\",\"1-2i\")");
sheet.SetFormula("F5", "FORMULATEXT(F1)");
XlsxCalculationResult result = workbook.Calculate();
for (int row = 1; row <= 5; row++)
{
XlsxCellValue value = sheet.GetCell(row, 6).Value;
Console.WriteLine($"F{row} = {(value.Kind == XlsxCellValueKind.Number ? value.NumberValue.ToString(System.Globalization.CultureInfo.InvariantCulture) : value.TextValue)}");
}
F1 = 23
F2 = 42.1648128
F3 = 00FF
F4 = 11-2i
F5 = =DSUM(A1:B5,"Qty",D1:D2)
CELL for a cell's look (width, format, prefix...) and INFO describe the machine and the window, not the workbook: such a formula keeps the value the file stores.
Array formulas and dynamic arrays
A dynamic array, which is what Excel 365 makes of a formula whose result is several values, spills from its cell as far as the result reaches: SetDynamicFormula enters one. A legacy array formula (Ctrl+Shift+Enter) fills the range it was entered over: SetArrayFormula enters one. FILTER, SORT, SORTBY, UNIQUE, SEQUENCE, RANDARRAY, LET, @ and A1# are calculated, and in an array formula any function is called once for each value of an argument it takes one value for (LEN(A1:A3), VLOOKUP(A1:A3,...)):
using DocWright.Spreadsheet;
// A dynamic array spills from its cell; the newer functions carry Excel's prefixes, as the file stores them.
sheet.SetDynamicFormula("D1", "_xlfn._xlws.SORTBY(A1:B4,B1:B4,-1)");
sheet.SetDynamicFormula("G1", "_xlfn._xlws.FILTER(A1:A4,B1:B4>2)");
sheet.SetFormula("H1", "ROWS(_xlfn.ANCHORARRAY(G1))"); // G1# in Excel
// A legacy array formula fills the range it is entered over.
sheet.SetArrayFormula("C1:C4", "ROUND(B1:B4*1.15,2)");
// A spill with a value in its way.
sheet.SetValue("J2", XlsxCellValue.Text("taken"));
sheet.SetDynamicFormula("J1", "_xlfn.SEQUENCE(3)");
XlsxCalculationResult result = workbook.Calculate();
for (int row = 1; row <= 4; row++)
{
Console.WriteLine($"{sheet.GetCell(row, 4).Value.TextValue,-6} {sheet.GetCell(row, 5).Value.NumberValue,6} C{row} = {sheet.GetCell(row, 3).Value.NumberValue}");
}
Console.WriteLine($"FILTER: {sheet.GetCell("G1").Value.TextValue}, {sheet.GetCell("G2").Value.TextValue} ({sheet.GetCell("H1").Value.NumberValue} rows)");
Console.WriteLine($"J1 = {sheet.GetCell("J1").Value.TextValue}");
Ink 12 C1 = 1.44
Paper 4.5 C2 = 13.8
Pens 1.25 C3 = 5.18
Clips 0.75 C4 = 0.86
FILTER: Ink, Paper (2 rows)
J1 = #SPILL!
A spill gives #SPILL! when a cell it would fill holds a value or a formula, another spill reached it first, or the sheet ends. The file is written as Excel 365 writes it: the formula on the first cell over the spill's range, the other cells' results as values, #SPILL! and #CALC! as Excel stores them. One cell of an array cannot be changed alone (UnsupportedFeatureException, as in Excel); a whole range can be given a new array formula, and a dynamic array's own cell any new value or formula, its spill going with it.
Download the workbook: stock-arrays.xlsx.
Evaluate a formula
using DocWright.Spreadsheet;
XlsxCellValue average = sheet.Evaluate("AVERAGE(B2:B4)"); // written nowhere
Console.WriteLine($"average price {average.NumberValue}; 0.1+0.2-0.3 = {sheet.Evaluate("0.1+0.2-0.3").NumberValue}");
Numbers behave as in Excel: 0.1+0.2-0.3 is 0, ROUND(2.5,0) is 3, MOD(-7,3) is 2, text that reads as a number counts in arithmetic, and an error anywhere in a sum is the result. XlsxDocument.CalculatedFunctions lists the functions.
Note
A calculation is bounded: XlsxCalculationLimits.MaxSteps (100,000,000 by default) stops it with ResourceLimitExceededException, writing nothing. Nothing is recursive, and nothing a formula calls reaches outside the workbook.
The whole run prints:
5 formulas calculated, complete: True
D5 = 94.01, D6 = large order
average price 5.91666666666667; 0.1+0.2-0.3 = 0
Download the workbook: orders-calculated.xlsx.