检测循环引用
Contents
[
Hide
]
介绍
工作簿可以有循环引用,有时需要检测是否存在循环引用。
检测循环引用背后的概念
循环引用只有在计算公式时才能检测到,因为一个公式的引用通常依赖于其他部分或其他公式的计算结果。所以我们在公式计算的过程中针对这个需求(收集循环引用的单元格)提供了新的API:
计算单元格代表正在计算一个cell的相关数据的计算
AbstractCalculationMonitor.OnCircular(IEnumerator circularCellsData)遇到循环引用时会被公式计算引擎调用,枚举器中的元素为计算单元格代表一个圆圈中所有单元格的对象。返回值表示在本次调用后公式引擎是否需要循环计算这些单元格。
用户可以在执行时收集那些循环引用AbstractCalculationMonitor.OnCircular()方法。
可以从以下链接下载源示例文件:
This file contains hidden or 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-.NET | |
LoadOptions LoadOptions = new LoadOptions(); | |
Workbook objWB = new Workbook(sourceDir + "Circular Formulas.xls", LoadOptions); | |
objWB.Settings.FormulaSettings.EnableIterativeCalculation = true; | |
CalculationOptions copts = new CalculationOptions(); | |
CircularMonitor cm = new CircularMonitor(); | |
copts.CalculationMonitor = cm; | |
objWB.CalculateFormula(copts); | |
int lngCircularRef = cm.circulars.Count; | |
Console.WriteLine("Circular References found - " + lngCircularRef); |
的定义圆形显示器派生自的类抽象计算监视器类如下:
This file contains hidden or 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-.NET | |
public class CircularMonitor : AbstractCalculationMonitor | |
{ | |
public ArrayList circulars = new ArrayList(); | |
public ArrayList Circulars { get { return circulars; } } | |
public override bool OnCircular(IEnumerator circularCellsData) | |
{ | |
CalculationCell cc = null; | |
ArrayList cur = new ArrayList(); | |
while (circularCellsData.MoveNext()) | |
{ | |
cc = (CalculationCell)circularCellsData.Current; | |
cur.Add(cc.Worksheet.Name + "!" + CellsHelper.CellIndexToName(cc.CellRow, cc.CellColumn)); | |
} | |
circulars.Add(cur); | |
return true; | |
} | |
} |