减少Cell.Calculate方法的计算时间

可能的使用场景

通常,我们建议用户拨打工作簿.CalculateFormula()方法一次,然后获取各个单元格的计算值。但有时,用户不想计算整个工作簿。他们只想计算单个单元格。 Aspose.Cells提供计算选项.递归您可以设置的属性错误的它将显着减少单个单元格的计算时间。因为当递归属性设置为真的,然后在每次调用时重新计算单元格的所有依赖项。但是当递归属性是错误的,则相关单元格仅计算一次,并且不会在后续调用中再次计算。

减少 Cell.Calculate() 方法的计算时间

下面的示例代码说明了计算选项.递归财产。请使用给定的执行此代码示例 excel 文件并检查其控制台输出。您会发现将递归属性设置为错误的大大减少了计算时间。另请阅读评论以更好地了解此属性。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// Test calculation time after setting recursive true
TestCalcTimeRecursive(true);
// Test calculation time after setting recursive false
TestCalcTimeRecursive(false);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
static void TestCalcTimeRecursive(bool rec)
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Load your sample workbook
Workbook wb = new Workbook(dataDir + "sample.xlsx");
// Access first worksheet
Worksheet ws = wb.Worksheets[0];
// Set the calculation option, set recursive true or false as per parameter
CalculationOptions opts = new CalculationOptions();
opts.Recursive = rec;
// Start stop watch
Stopwatch sw = new Stopwatch();
sw.Start();
// Calculate cell A1 one million times
for (int i = 0; i < 1000000; i++)
{
ws.Cells["A1"].Calculate(opts);
}
// Stop the watch
sw.Stop();
// Calculate elapsed time in seconds
long second = 1000;
long estimatedTime = sw.ElapsedMilliseconds / second;
// Print the elapsed time in seconds
Console.WriteLine("Recursive " + rec + ": " + estimatedTime + " seconds");
}

控制台输出

这是使用给定的执行时上述示例代码的控制台输出示例 excel 文件在我们的机器上。请注意,您的输出可能会有所不同,但将递归属性设置为错误的将永远小于将其设置为真的.

Recursive True: 96 seconds

Recursive False: 42 seconds