Aspose.Cellsのデフォルトの計算エンジンを拡張するためにカスタム計算エンジンを実装する
カスタム計算エンジンの実装
Aspose.CellsにはほとんどすべてのMicrosoft Excel式を計算できる強力な計算エンジンがあります。それにもかかわらず、デフォルトの計算エンジンを拡張することが可能であり、より大きな力と柔軟性を提供します。
この機能の実装に使用される次のプロパティとクラスは次のとおりです。
以下のコードは、カスタム計算エンジンを実装しています。そのエンジンはAbstractCalculationEngineインターフェースを実装しており、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-.NET | |
// Create a new class derived from AbstractCalculationEngine | |
class CustomEngine : AbstractCalculationEngine | |
{ | |
// Override the Calculate method with custom logic | |
public override void Calculate(CalculationData data) | |
{ | |
// Check the forumla name and change the implementation | |
if (data.FunctionName.ToUpper() == "TODAY") | |
{ | |
// Assign the CalculationData.CalculatedValue: add one day offset for the date | |
data.CalculatedValue = CellsHelper.GetDoubleFromDateTime(DateTime.Today, false) + 1.0; | |
} | |
} | |
public override bool ProcessBuiltInFunctions { get { return true; } } | |
} | |
class ImplementCustomCalculationEngine | |
{ | |
public static void Run() | |
{ | |
// Create an instance of Workbook | |
Workbook workbook = new Workbook(); | |
// Access first Worksheet from the collection | |
Worksheet sheet = workbook.Worksheets[0]; | |
// Access Cell A1 and put a formula to sum values of B1 to B2 | |
Cell a1 = sheet.Cells["A1"]; | |
Style style = a1.GetStyle(); | |
style.Number = 14; | |
a1.SetStyle(style); | |
a1.Formula = "=TODAY()"; | |
// Calculate all formulas in the Workbook | |
workbook.CalculateFormula(); | |
// The result of A1 should be 20 as per default calculation engine | |
Console.WriteLine("The value of A1 with default calculation engine: " + a1.StringValue); | |
// Create an instance of CustomEngine | |
CustomEngine engine = new CustomEngine(); | |
// Create an instance of CalculationOptions | |
CalculationOptions opts = new CalculationOptions(); | |
// Assign the CalculationOptions.CustomEngine property to the instance of CustomEngine | |
opts.CustomEngine = engine; | |
// Recalculate all formulas in Workbook using the custom calculation engine | |
workbook.CalculateFormula(opts); | |
// The result of A1 will be 50 as per custom calculation engine | |
Console.WriteLine("The value of A1 with custom calculation engine: " + a1.StringValue); | |
Console.WriteLine("Press any key to continue..."); | |
Console.ReadKey(); | |
} | |
} |
結果
上記のサンプルコードのコンソール出力を確認してください。カスタムエンジンを使用した場合、A1の値(日時)はカスタムエンジンを使用しなかった場合の結果よりも1日後になるはずです。