中断或取消工作簿的公式计算

可能的使用场景

Aspose.Cells 提供了一种通过 AbstractCalculationMonitor.Interrupt() 方法来中断或取消工作簿的公式计算的机制。当工作簿的公式计算耗时较长,您希望取消其处理时,这将会很有用。

中断或取消工作簿的公式计算

以下示例代码实现了 BeforeCalculate() 类的 AbstractCalculationMonitor 方法。在此方法内部,它使用行和列索引参数查找单元格名称。如果单元格名称为 B8,则通过调用 AbstractCalculationMonitor.Interrupt() 方法中断计算过程。一旦 AbstractCalculationMonitor 类的具体类实现完成,它的实例将被分配给 CalculationOptions.CalculationMonitor 属性。最后,通过传递 CalculationOptions 作为参数调用 Workbook.CalculateFormula()。请参阅以下示例代码中使用的 示例 Excel 文件 以及代码的控制台输出作为参考。

示例代码

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
class InterruptOrCancelFormulaCalculationOfWorkbook
{
//Implement calculation monitor class
class clsCalculationMonitor : AbstractCalculationMonitor
{
public override void BeforeCalculate(int sheetIndex, int rowIndex, int colIndex)
{
//Find the cell name
string cellName = CellsHelper.CellIndexToName(rowIndex, colIndex);
//Print the sheet, row and column index as well as cell name
System.Diagnostics.Debug.WriteLine(sheetIndex + "----" + rowIndex + "----" + colIndex + "----" + cellName);
//If cell name is B8, interrupt/cancel the formula calculation
if (cellName == "B8")
{
this.Interrupt("Interrupt/Cancel the formula calculation");
}//if
}//BeforeCalculate
}//clsCalculationMonitor
public static void Run()
{
//Load the sample Excel file
Workbook wb = new Workbook("sampleCalculationMonitor.xlsx");
//Create calculation options and assign instance of calculation monitor class
CalculationOptions opts = new CalculationOptions();
opts.CalculationMonitor = new clsCalculationMonitor();
//Calculate formula with calculation options
wb.CalculateFormula(opts);
}
}

控制台输出

 0----1----3----D2

0----4----6----G5

0----7----1----B8