在 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();
}
}