カスタム関数をワークシートに書かずに直接計算

カスタム関数をワークシートに書かずに直接計算

このトピックでは、最初にカスタム関数をワークシートに記述せずに直接計算する方法について説明します。をご利用くださいWorksheet.CalculateFormula(文字列式、CalculationOptions オプション)この目的のためのメソッド。

このメソッドの使用法を示す次のサンプル コードを参照してください。 MyCompany.CustomFunction() という名前のカスタム関数を使用し、その値を “Aspose.Cells” として計算します。この値は、計算エンジンによって「Welcome to」であるセル A1 の値と自動的に連結され、最終的に計算された値は「Welcome to Aspose.Cells.」として返されます。カスタム関数はワークシートのどこにも記述されておらず、独自のカスタム ロジックによって直接計算されます。

プログラミングサンプル

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
class ICustomEngine : AbstractCalculationEngine
{
// Override the Calculate method with custom logic
public override void Calculate(CalculationData data)
{
// Check the forumla name and calculate it yourself
if (data.FunctionName == "MyCompany.CustomFunction")
{
// This is our calculated value
data.CalculatedValue = "Aspose.Cells.";
}
}
}
class ImplementDirectCalculationOfCustomFunction
{
public static void Run()
{
// Create a workbook
Workbook wb = new Workbook();
// Accesss first worksheet
Worksheet ws = wb.Worksheets[0];
// Add some text in cell A1
ws.Cells["A1"].PutValue("Welcome to ");
// Create a calculation options with custom engine
CalculationOptions opts = new CalculationOptions();
opts.CustomEngine = new ICustomEngine();
// This line shows how you can call your own custom function without
// a need to write it in any worksheet cell
// After the execution of this line, it will return
// Welcome to Aspose.Cells.
object ret = ws.CalculateFormula("=A1 & MyCompany.CustomFunction()", opts);
// Print the calculated value on Console
Console.WriteLine("Calculated Value: " + ret);
}
}

コンソール出力

以下は、上記のサンプル コードのコンソール出力です。

Calculated Value: Welcome to Aspose.Cells.

関連記事