使用自定义计算引擎

实现自定义计算引擎

Aspose.Cells.Gridweb拥有强大的计算引擎,可以计算几乎所有的Microsoft Excel公式。尽管如此,它还允许您扩展默认的计算引擎,为您提供更大的能力和灵活性。

在实现此功能中使用了以下属性和类。

以下代码实现了自定义计算引擎。它实现了GridAbstractCalculationEngine接口,具有Calculate(GridCalculationData data)方法。调用此方法以处理所有公式。在此方法中,我们捕获了MYTESTFUNC公式并为其第一个参数值乘以2。

编程示例

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
private class CustomEngineSimple : GridAbstractCalculationEngine
{
public override void Calculate(GridCalculationData data)
{
if (!"MYTESTFUNC".Equals(data.FunctionName.ToUpper()))
{
return;
}
data.CalculatedValue = (decimal)(2.0 * (double)data.GetParamValue(0));
}
}
protected void Page_Load(object sender, EventArgs e)
{
// If first visit this page clear GridWeb1 and load data
if (!IsPostBack && !GridWeb1.IsPostBack)
{
CustomEngineSimple ce = new CustomEngineSimple();
GridWeb1.CustomCalculationEngine = ce;
GridWorksheet sheet = GridWeb1.ActiveSheet;
GridCell cell = sheet.Cells["A1"];
cell.Formula = "=MYTESTFUNC(3.0)";
cell = sheet.Cells["A2"];
cell.PutValue("hello");
cell = sheet.Cells["B1"];
cell.PutValue(1);
cell = sheet.Cells["B2"];
cell.PutValue(2);
cell = sheet.Cells["B3"];
cell.PutValue(3);
cell = sheet.Cells["A3"];
cell.Formula = "=SUM(B1:B3)";
GridWeb1.CalculateFormula();
sheet.ActiveCell = "A4";
}
}