实施自定义计算引擎以扩展 Aspose.Cells 的默认计算引擎

实施自定义计算引擎

以下代码实现自定义计算引擎。它实现了接口抽象计算引擎只有一种方法计算(计算数据数据).针对您的所有公式调用此方法。在这个方法中,我们捕获公式并将其值增加 30。因此,如果 Aspose.Cells 计算值是 20,那么我们的自定义引擎将通过添加 30 使其变为 50。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
public class CustomEngine extends AbstractCalculationEngine {
public void calculate(CalculationData data) {
if (data.getFunctionName().toUpperCase().equals("TODAY")) {
data.setCalculatedValue(CellsHelper.getDoubleFromDateTime(DateTime.getNow(), false) + 1.0);
}
}
public getProcessBuiltInFunctions() { return true; }
}
public static void main(String[] args) throws Exception {
// The path to the documents directory.
String dataDir = Utils.getDataDir(ImplementCustomCalculationEngine.class);
Workbook workbook = new Workbook();
Worksheet sheet = workbook.getWorksheets().get(0);
Cell a1 = sheet.getCells().get("A1");
Style style = cell.getStyle();
style.setNumber(14);
cell.setStyle(style);
a1.setFormula("=TODAY()");
// Without Custom Engine, the value of cell A1 will be 20
workbook.calculateFormula();
System.out.println("Without Custom Engine Value of A1: " + a1.getStringValue());
// With Custom Engine, the value of cell A1 will be 50
CalculationOptions opts = new CalculationOptions();
opts.setCustomEngine(new CustomEngine());
workbook.calculateFormula(opts);
System.out.println("With Custom Engine Value of A1: " + a1.getStringValue());
}

控制台输出

这是上述示例代码的控制台输出。

 Without Custom Engine Value of A1: 20

With Custom Engine Value of A1: 50

相关文章