直接计算自定义函数,无需先将其编写在工作表中
Contents
[
Hide
]
本文解释了如何在不首先将其写入工作表的情况下直接计算自定义函数。请使用Worksheet.calculateFormula(string formula, CalculationOptions opts) 方法来实现此目的。
在不将其写入工作表的情况下直接计算自定义函数
请参阅以下示例代码,以了解此方法的用法。我们使用了一个名为*MyCompany.CustomFunction()*的自定义函数,我们自己计算其值为"Aspose.Cells.",然后此值会自动与单元A1的值"Welcome to “由计算引擎连接,并计算出最终计算后的值"Welcome to Aspose.Cells."。从代码中可以看到,我们没有在工作表中编写自定义函数,而是通过我们自己的自定义逻辑直接计算出来。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
public class CustomEngine extends AbstractCalculationEngine | |
{ | |
// Override the Calculate method with custom logic | |
public void calculate(CalculationData data) | |
{ | |
// Check the forumla name and calculate it yourself | |
if (data.getFunctionName().equals("MyCompany.CustomFunction")) | |
{ | |
// This is our calculated value | |
data.setCalculatedValue("Aspose.Cells."); | |
} | |
} | |
} | |
public static void main(String[] args) throws Exception { | |
// Create a workbook | |
Workbook wb = new Workbook(); | |
// Accesss first worksheet | |
Worksheet ws = wb.getWorksheets().get(0); | |
// Add some text in cell A1 | |
ws.getCells().get("A1").putValue("Welcome to "); | |
// Create a calculation options with custom engine | |
CalculationOptions opts = new CalculationOptions(); | |
opts.setCustomEngine(new CustomEngine()); | |
// 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 | |
System.out.println("Calculated Value: " + ret.toString()); | |
} |
控制台输出
以下是上面示例代码的控制台输出。
Calculated Value: Welcome to Aspose.Cells.