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

实现自定义计算引擎

以下代码实现了自定义计算引擎。它实现了接口AbstractCalculationEngine,该接口只有一个方法calculate(CalculationData data)。此方法针对所有公式进行调用。在此方法中,我们捕获了TODAY函数,并将系统日期加一天。因此,如果当前日期是2023年07月27日,那么自定义引擎将计算TODAY()为2023年07月28日。

编程示例

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

结果

请检查上述示例代码的控制台输出,具有自定义引擎的 A1 的值(日期时间)应该比没有自定义引擎的结果晚一天。

相关文章