自定义函数直接计算,无需写在工作表中

自定义函数直接计算,无需写在工作表中

本主题说明如何直接计算自定义函数而无需先将它们写入工作表。请使用Worksheet.CalculateFormula(字符串公式,CalculationOptions opts)为此目的的方法。

请参阅下面的示例代码,该代码说明了此方法的用法。我们使用了一个名为 MyCompany.CustomFunction() 的自定义函数,并将其值计算为“Aspose.Cells”。由我们自己计算,然后该值自动与计算引擎“欢迎使用”的单元格 A1 的值连接,最终计算值返回为“欢迎使用 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.

相关文章