ワークシートに書き込まずにカスタム関数を直接計算する
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.