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

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

请参阅下面的示例代码,该代码说明了此方法的用法。我们使用了一个名为*我的公司.CustomFunction()*我们计算它的值为“Aspose.Cells”。由我们自己,然后该值自动与计算引擎“欢迎使用”的单元格 A1 的值连接,最终计算值返回为“欢迎使用 Aspose.Cells”。正如您在代码中看到的那样,我们没有在工作表的任何地方编写我们的自定义函数,它是由我们自己的自定义逻辑直接计算的。

// 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.

相关文章