计算公式的方式

介绍

Aspose.Cells内置有公式计算引擎。 它不仅可以重新计算从设计模板导入的公式,还支持计算运行时添加的公式的结果。

添加公式及计算结果

Aspose.Cells支持大部分Microsoft Excel中的公式或函数。它们可以通过API或设计者电子表格使用。Aspose.Cells支持大量的数学、字符串、布尔、日期/时间、统计、查找和引用公式。

使用Cell.SetFormula方法向单元格添加公式。当将公式应用于单元格时,始终以等号(=)开头,就像在Microsoft Excel中创建公式时一样。使用逗号(,)来分隔函数参数。

要计算公式的结果,请调用Workbook.CalculateFormula()方法,该方法可以处理Excel文件中嵌入的所有公式。请参阅下面的示例代码,添加公式并计算其结果。请检查使用此代码生成的输出excel文件

示例代码

Aspose::Cells::Startup();
//For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-C
//Output directory path
U16String outPath(u"..\\Data\\Output\\");
//Path of output excel file
U16String outputAddingFormulasAndCalculatingResults = outPath + u"outputAddingFormulasAndCalculatingResults.xlsx";
//Create workbook
Workbook wb;
//Access first worksheet in the workbook
Worksheet ws = wb.GetWorksheets().Get(0);
//Adding integer values to cells A1, A2 and A3
ws.GetCells().Get(u"A1").PutValue(10);
ws.GetCells().Get(u"A2").PutValue(20);
ws.GetCells().Get(u"A3").PutValue(70);
//Adding a SUM formula to "A4" cell
ws.GetCells().Get(u"A4").SetFormula(u"=SUM(A1:A3)");
//Calculating the results of formulas
wb.CalculateFormula();
//Get the calculated value of the cell
U16String strVal = ws.GetCells().Get(u"A4").GetStringValue();
//Print the calculated value on console
std::cout << "Calculated Result: " << strVal.ToUtf8() <<std::endl;
//Saving the workbook
wb.Save(outputAddingFormulasAndCalculatingResults);
Aspose::Cells::Cleanup();

仅计算一次公式

当调用Workbook.CalculateFormula()来计算工作簿模板中公式的值时,Aspose.Cells会创建一个计算链。当第二或第三次计算公式时,会提高性能。

但是,如果模板包含大量公式,第一次计算公式可能会消耗大量CPU处理时间和内存。

Aspose.Cells允许您关闭创建计算链,这在您只想计算公式一次时很有用。

请调用Workbook.GetISettings().SetCreateCalcChain(),参数为false。您可以使用提供的excel文件测试此代码。

示例代码

Aspose::Cells::Startup();
//For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-C
//Source directory path
U16String dirPath(u"..\\Data\\Formulas\\");
//Path of input excel file
U16String sampleCalculatingFormulasOnceOnly = dirPath + u"sampleCalculatingFormulasOnceOnly.xlsx";
//Create workbook
Workbook wb(sampleCalculatingFormulasOnceOnly);
//Set the CreateCalcChain as false
wb.GetSettings().GetFormulaSettings().SetEnableCalculationChain(false);
//Get the time before formula calculationint
auto startTime = std::chrono::system_clock::now();
//Calculate the workbook formulas
wb.CalculateFormula();
//Get the time after formula calculation
auto interval = std::chrono::system_clock::now() - startTime;
long long time = std::chrono::duration_cast<std::chrono::milliseconds>(interval).count();
std::cout << "Workbook Formula Calculation Elapsed Time in Milliseconds: " << time << std::endl;
Aspose::Cells::Cleanup();