使用 ICustomFunction 功能

创建和评估用户定义的函数

本文演示了 ICustomFunction 接口的实现,以编写自定义函数并在电子表格中使用它来获取结果。我们将按名称定义一个自定义函数我的函数它将接受具有以下详细信息的 2 个参数。

  • 第一个参数是指单个单元格
  • 第二个参数是指单元格范围

自定义函数将添加指定为第二个参数的单元格范围内的所有值,并将结果除以第一个参数中的值。

下面是我们如何实现 CalculateCustomFunction 方法。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
public class CustomFunction : ICustomFunction
{
public object CalculateCustomFunction(string functionName, System.Collections.ArrayList paramsList, System.Collections.ArrayList contextObjects)
{
decimal total = 0M;
try
{
// Get value of first parameter
decimal firstParamB1 = System.Convert.ToDecimal(paramsList[0]);
// Get value of second parameter
Array secondParamC1C5 = (Array)(paramsList[1]);
// get every item value of second parameter
foreach (object[] value in secondParamC1C5)
{
total += System.Convert.ToDecimal(value[0]);
}
total = total / firstParamB1;
}
catch
{
}
// Return result of the function
return total;
}
}

以下是如何在电子表格中使用新定义的函数

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Open the workbook
Workbook workbook = new Workbook();
// Obtaining the reference of the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Adding sample values to cells
worksheet.Cells["B1"].PutValue(5);
worksheet.Cells["C1"].PutValue(100);
worksheet.Cells["C2"].PutValue(150);
worksheet.Cells["C3"].PutValue(60);
worksheet.Cells["C4"].PutValue(32);
worksheet.Cells["C5"].PutValue(62);
// Adding custom formula to Cell A1
workbook.Worksheets[0].Cells["A1"].Formula = "=MyFunc(B1,C1:C5)";
// Calcualting Formulas
workbook.CalculateFormula(false, new CustomFunction());
// Assign resultant value to Cell A1
workbook.Worksheets[0].Cells["A1"].PutValue(workbook.Worksheets[0].Cells["A1"].Value);
// Save the file
workbook.Save(dataDir + "UsingICustomFunction_out.xls");

概述

Aspose.Cells API只是在对应参数为引用或其计算结果为引用时将ReferredArea对象放入“paramsList”中。如果您需要引用本身,那么您可以直接使用 ReferredArea。如果需要从与公式位置对应的引用中获取单个单元格的值,可以使用 ReferredArea.GetValue(rowOffset, int colOffset) 方法。如果您需要整个区域的单元格值数组,则可以使用 ReferredArea.GetValues 方法。

由于 Aspose.Cells API 在“paramsList”中提供了 ReferredArea,因此不再需要“contextObjects”中的 ReferredAreaCollection(在旧版本中,它无法始终为自定义函数的参数提供一对一的映射)因此它已从“contextObjects”中删除。

 public object CalculateCustomFunction(string functionName, ArrayList paramsList, ArrayList contextObjects)

{

    ...

    object o = paramsList[i];

    if(o is ReferredArea) //fetch data from reference

    {

        ReferredArea ra = (ReferredArea)o;

        if(ra.IsArea)

        {

            o = ra.GetValues();

        }

        else

        {

            o = ra.GetValue(0, 0);

        }

    }

    if (o is Array)

    {

        ...

    }

    else if...

    ...

}