在 GridWeb 中计算自定义函数

可能的使用场景

Aspose.Cells.GridWeb支持使用GridWeb.CustomCalculationEngine属性计算自定义函数。此属性采用 GridAbstractCalculationEngine 接口的实例。请实现 GridAbstractCalculationEngine 接口并使用您自己的逻辑计算您的自定义函数。

在 GridWeb 中计算自定义函数

下面的示例代码在单元格 B3 中添加了一个名为 MYTESTFUNC() 的自定义函数。然后我们通过实现 GridAbstractCalculationEngine 接口来计算这个函数的值。我们计算 MYTESTFUNC() 的方式是将其参数乘以 2 并返回结果。所以如果它的参数是 9,它会返回 2*9 = 18。

示例代码

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
private class GridWebCustomCalculationEngine : GridAbstractCalculationEngine
{
public override void Calculate(GridCalculationData data)
{
// Calculate MYTESTFUNC() with your own logic. i.e Multiply MYTESTFUNC() parameter with 2 so MYTESTFUNC(3.0) = 6
if ("MYTESTFUNC".Equals(data.FunctionName.ToUpper()))
{
data.CalculatedValue = (decimal)(2.0 * (double)data.GetParamValue(0));
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false && GridWeb1.IsPostBack == false)
{
// Assign your own custom calculation engine to GridWeb
GridWeb1.CustomCalculationEngine = new GridWebCustomCalculationEngine();
// Access the active worksheet and add your custom function in cell B3
GridWorksheet sheet = GridWeb1.ActiveSheet;
GridCell cell = sheet.Cells["B3"];
cell.Formula = "=MYTESTFUNC(9.0)";
// Calculate the GridWeb formula
GridWeb1.CalculateFormula();
}
}