-
Notifications
You must be signed in to change notification settings - Fork 295
Using LAMBDA functions
EPPlus supports Lambda functions from version 8.2. With Lambda functions you can define custom reusable formulas directly in the workbook, without needing VBA or external code.
With EPPlus you can use Lambda functions with defined names, see the following example:
using var package = new ExcelPackage();
var sheet = package.Workbook.Worksheets.Add("Sheet1");
package.Workbook.Names.AddFormula("TestFunc", "LAMBDA(x,y, x/y)");
sheet.Cells["A1"].Formula = "TestFunc(12,3)";
sheet.Calculate();
var v = sheet.Cells["A1"].Value; // v is 4
From version 8.2, EPPlus supports Eta Reduced Lambda expressions. In Excel formula notation, this means you can pass a function directly as an argument to higher‑order functions like MAP, REDUCE, or SCAN, instead of wrapping it in a full LAMBDA. To make this work in EPPlus, you must prefix the function with the special _xleta
attribute. This tells the calculation engine (and Excel) that the function is being used as a lambda reference rather than a direct call.
// Using full LAMBDA
sheet.Cells["B1"].Formula = "MAP(A1:A3, LAMBDA(x, UPPER(x)))";
// Using Eta Reduced Lambda
sheet.Cells["B2"].Formula = "MAP(A1:A3, _xleta.UPPER)";
EPPlus’ calculation engine supports advanced scenarios with LAMBDA, enabling you to express logic that goes far beyond simple formulas. Two particularly powerful techniques are recursion and currying.
Recursion – a LAMBDA can call itself, allowing you to implement classic algorithms directly in Excel.
// Recursive factorial using LET + LAMBDA
ws.Names.AddFormula("Factorial",
"LAMBDA(input, LET(n, input, IF(n = 0, 1, n * Sheet1!Factorial(n - 1))))");
ws.Cells["A1"].Formula = "Factorial(4)";
ws.Calculate();
// Result: 24
Currying – you can create functions that return other functions, building calculations step by step.
sheet.Cells["A1"].Formula = "LAMBDA(a, LAMBDA(b, LAMBDA(c, a + b + c)))(1)(2)(3)";
sheet.Calculate();
//Result: 6
EPPlus Software AB - https://epplussoftware.com
- What is new in EPPlus 5+
- Breaking Changes in EPPlus 5
- Breaking Changes in EPPlus 6
- Breaking Changes in EPPlus 7
- Breaking Changes in EPPlus 8
- Addressing a worksheet
- Dimension/Used range
- Copying ranges/sheets
- Insert/Delete
- Filling ranges
- Sorting ranges
- Taking and skipping columns/rows
- Data validation
- Comments
- Freeze and Split Panes
- Header and Footer
- Hyperlinks
- Autofit columns
- Grouping and Ungrouping Rows and Columns
- Formatting and styling
- The ExcelRange.Text property
- Conditional formatting
- Using Themes
- Working with custom named table- or slicer- styles