Custom Formula in WPF Spreadsheet (SfSpreadsheet)

23 Jul 20261 minute to read

SfSpreadsheet allows you to add custom formulas to its function library by using the AddFunction method of FormulaEngine.

spreadsheet.WorkbookLoaded += spreadsheet_WorkbookLoaded;

void spreadsheet_WorkbookLoaded(object sender, WorkbookLoadedEventArgs args)
{
    foreach (var grid in args.GridCollection)
        AddCustomFormula(grid); 
  
  //Computing the formula at runtime

   var range = spreadsheet.ActiveSheet.Range["B2"];
   spreadsheet.ActiveGrid.SetCellValue(range,"=Find(sample)");
}  

private void AddCustomFormula(SpreadsheetGrid grid)
{

  // Add a formula named Find to the Library.
   grid.FormulaEngine.AddFunction("Find", new FormulaEngine.LibraryFunction(ComputeLength));      
}    

//Implementation of formula
    
public string ComputeLength(string range)
{
    // Calculate the length of the supplied string.
    return range.Length.ToString();
}

NOTE

For more information, see the WPF Spreadsheet Editor feature tour or browse the WPF Spreadsheet examples on GitHub.