直接计算自定义函数,无需先将其编写在工作表中
在不将其写入工作表的情况下直接计算自定义函数
本主题解释了如何在不首先在工作表中编写自定义函数的情况下直接计算您的自定义函数。请使用 Worksheet.CalculateFormula(string formula, CalculationOptions opts) 方法来实现这一目的。
请参阅以下示例代码,演示了如何使用此方法。我们使用了一个名为 MyCompany.CustomFunction() 的自定义函数,并且通过自己的自定义逻辑计算其值为 “Aspose.Cells.",然后该值由计算引擎自动地与单元格 A1 的值 “Welcome to " 进行连接,最终计算的值返回为 “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.