ICustomFunction 機能の使用

序章

この記事では、ICustomFunction 機能を使用して、Aspose.Cells API でカスタム関数を実装する方法について説明します。

ICustomFunction インターフェイスを使用すると、特定の要件を満たすために、Aspose.Cells コア計算エンジンを拡張するカスタム数式計算関数を追加できます。この機能は、カスタム (ユーザー定義) 関数をテンプレート ファイルまたはコードで定義する場合に便利です。カスタム関数は、他の既定の Microsoft Excel 関数と同様に、Aspose.Cells API を使用して実装および評価できます。

ICustomFunction 機能の使用

次のサンプル コードは、2 つのカスタム関数、つまり MySampleFunc() と YourSampleFunc() の値を評価して返す ICustomFunction インターフェイスを実装します。これらのカスタム関数は、それぞれセル A1 と A2 内にあります。次に、IWorkbook.CalculateFormula(false, ICustomFunction) メソッドを呼び出して、ICustomFunction.CalculateCustomFunction() メソッドの実装を呼び出します。次に、実際には ICustomFunction.CalculateCustomFunction() によって返される値である A1 と A2 の値をコンソールに出力します。詳細については、以下のサンプル コードのコンソール出力を参照してください。

サンプルコード

//For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-C
//Implement ICustomFunction interface
class CustomFunction : public ICustomFunction
{
public:
//Evalaute and return the values of your custom functions
intrusive_ptr<Aspose::Cells::System::Object>
CalculateCustomFunction(
intrusive_ptr<Aspose::Cells::System::String> functionName,
intrusive_ptr<Aspose::Cells::System::Collections::ArrayList> paramsList,
intrusive_ptr<Aspose::Cells::System::Collections::ArrayList> contextObjects)
{
if (functionName->Equals(new String("MySampleFunc")))
{
return new String("MY sample function was called successfully.");
}
if (functionName->Equals(new String("YourSampleFunc")))
{
return new String("YOUR sample function was called successfully.");
}
return NULL;
}
};
//Using ICustomFunction Feature
void UsingICustomFunctionFeature()
{
//Create workbook
intrusive_ptr<IWorkbook> wb = Factory::CreateIWorkbook();
//Access first worksheet in the workbook
intrusive_ptr<IWorksheet> ws = wb->GetIWorksheets()->GetObjectByIndex(0);
//Adding custom formulas to Cell A1 and A2
ws->GetICells()->GetObjectByIndex(new String("A1"))->SetFormula(new String("=MySampleFunc()"));
ws->GetICells()->GetObjectByIndex(new String("A2"))->SetFormula(new String("=YourSampleFunc()"));
// Calcualting Formulas
intrusive_ptr<CustomFunction> custFunc = new CustomFunction();
wb->CalculateFormula(false, custFunc);
//Print the value of cell A1 and A2 after the calculation of custom function implemented by us.
intrusive_ptr<String> valA1 = ws->GetICells()->GetObjectByIndex(new String("A1"))->GetStringValue();
intrusive_ptr<String> valA2 = ws->GetICells()->GetObjectByIndex(new String("A2"))->GetStringValue();
//Print the values on console
StringPtr str1 = new String("Value of A1: ");
Console::WriteLine(str1->StringAppend(valA1));
StringPtr str2 = new String("Value of A2: ");
Console::WriteLine(str2->StringAppend(valA2));
}

コンソール出力

 Value of A1: MY sample function was called successfully.

Value of A2: YOUR sample function was called successfully.