Implement Custom Calculation Engine to extend the Default Calculation Engine of Aspose.Cells
Aspose.Cells has a powerful calculation engine that can calculate almost all of the Microsoft Excel formulas. Despite this, it also allows you to extend the default calculation engine which provides you greater power and flexibility.
The following property and classes are used in implementing this feature.
Implement Custom Calculation Engine
The following code implements the Custom Calculation Engine. It implements the interface AbstractCalculationEngine which has only one method calculate(CalculationData data). This method is called against all of your formulas. Inside this method, we capture the SUM formula and increases its value by 30. So if the Aspose.Cells calculated value is 20, then our custom engine will make it 50 by adding 30.
// 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()); | |
} |
Console Output
Here is the console output of the above sample code.
Without Custom Engine Value of A1: 20
With Custom Engine Value of A1: 50