Search code examples
excelc#-4.0epplus

EPPlus how to check for circular references?


I'm using the EPPlus library to build an excel file, and was wondering whether there is a way using this library to check for circular references in a formula?

I know the Microsoft Interop has this functionality with Range CircularReference { get; }, but I'm trying to avoid using it.


Solution

  • If there is a circular reference and you do not allow it in the calculation options, an exception will be thrown when trying to calculate.

    BTW, by default circular references throw exceptions. To Allow them change the property to true.

    You can also calculate entire worksheets/workbooks.

    Example code for checking if cell contains a circular reference:

    //Assign Formula
    var cell = worksheet.Cells["A2"]; //Example Cell
    cell.Formula = "YourFormula";
    
    //Initiate calculation option
    var calculateOptions = new ExcelCalculationOption();
    calculateOptions.AllowCirculareReferences = false;
    
    bool isFormulaCircularReference = false;
    try
    {
        cell.Calculate(calculateOptions);
    }
    catch (CircularReferenceException ex)
    {
        //If there is a circular reference this exception will be thrown
        isFormulaCircularReference = true;
    }