Aspose.Cellsのデフォルトの計算エンジンを拡張するためにカスタム計算エンジンを実装する
Aspose.CellsにはほとんどすべてのMicrosoft Excel式を計算できる強力な計算エンジンがあります。それにもかかわらず、デフォルトの計算エンジンを拡張することが可能であり、より大きな力と柔軟性を提供します。
この機能の実装に使用される次のプロパティとクラスは次のとおりです。
カスタム計算エンジンの実装
以下のコードは、カスタム計算エンジンの実装を示しています。それはAbstractCalculationEngine インタフェースを実装し、ただ1つのcalculate(CalculationData data) メソッドを持っています。このメソッドはすべての式に対して呼び出されます。このメソッド内で、TODAY関数を捕捉し、システム日付に1日加えます。したがって、現在の日付が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の値(日時)はカスタムエンジンを使用しなかった場合の結果よりも1日後になるはずです。