Fading Coder

One Final Commit for the Last Sprint

Home > Tools > Content

Visualizing Spreadsheet Formula Dependencies with ECharts Tree Maps

Tools Dec 3 5

Understanding Precedent and Dependent Relationships in Spreadsheets

In spreadsheet applications and financial reporting systems, formula dependencies often span multiple cells and layers of calculations. When auditing or reviewing complex workbooks, manually tracing these relationships becomes error-prone and time-consuming. This article demonstrates how to visualize cell dependencies using the SpreadJS spreadsheet component and ECharts tree diagrams.

Precedents vs Dependents

  • Precedents: When cell B1 contains the formula =SUM(A1), cell A1 serves as a precedent (reference) to B1
  • Dependents: Conversely, cell B1 is a dependent of cell A1, meaning A1 is referenced by B1

Building the Dependency Tree Structure

The visualization begins by extracting relationship data from the spreadsheet and constructing a hierarchical tree structure compatible with ECharts.

// Recursively builds a tree structure representing cell dependencies
function constructDependencyTree(spreadsheet, cellAddress, relationshipMode) {
    const sheet = spreadsheet.getSheetFromName(cellAddress.sheetName);
    const cellInfo = parseCellInfo(cellAddress);
    
    // Initialize root node
    const rootNode = createTreeNode(
        cellInfo.rowIndex, 
        cellInfo.columnIndex, 
        sheet, 
        0, 
        relationshipMode
    );
    
    let referenceTree = null;
    let dependentTree = null;
    
    // Handle precedents (upstream dependencies)
    if (relationshipMode === 'Precedents' || relationshipMode === 'Combined') {
        traverseDependencies(rootNode, sheet, 'Precedents');
        
        if (relationshipMode === 'Combined') {
            const branchData = JSON.parse(JSON.stringify(rootNode.children));
            rootNode.children = [];
            referenceTree = JSON.parse(JSON.stringify(rootNode));
            referenceTree.children.push({
                name: 'Precedents',
                value: 'Precedents',
                children: branchData
            });
        }
    }
    
    // Handle dependents (downstream dependencies)
    if (relationshipMode === 'Dependents' || relationshipMode === 'Combined') {
        traverseDependencies(rootNode, sheet, 'Dependents');
        
        if (relationshipMode === 'Combined') {
            const branchData = JSON.parse(JSON.stringify(rootNode.children));
            rootNode.children = [];
            dependentTree = JSON.parse(JSON.stringify(rootNode));
            dependentTree.children.push({
                name: 'Dependents',
                value: 'Dependents',
                children: branchData
            });
        }
    }
    
    // Merge both trees for combined view
    if (relationshipMode === 'Combined') {
        referenceTree.children = referenceTree.children.concat(dependentTree.children);
        return referenceTree;
    }
    
    return rootNode;
}

// Creates a single node representing a cell in the dependency tree
function createTreeNode(rowIndex, colIndex, worksheet, depth, relationType) {
    const cellRange = new GC.Spread.Sheets.Range(rowIndex, colIndex, 1, 1);
    const formulaReference = GC.Spread.Sheets.CalcEngine.rangeToFormula(cellRange);
    const cellValue = worksheet.getValue(rowIndex, colIndex);
    
    return {
        value: cellValue,
        position: `${worksheet.name()}!${formulaReference}`,
        depth: depth,
        name: `${worksheet.name()}!${formulaReference}\nvalue:${cellValue}`,
        sheetName: worksheet.name(),
        row: rowIndex,
        col: colIndex,
        trackType: relationType,
        children: []
    };
}

// Recursively traverses and builds child nodes
function traverseDependencies(parentNode, worksheet, traversalMode) {
    const childNodes = [];
    const { row, col, depth } = parentNode;
    
    // Fetch related cells based on mode
    const relatedCells = traversalMode === 'Precedents' 
        ? worksheet.getPrecedents(row, col)
        : worksheet.getDependents(row, col);
    
    if (relatedCells && relatedCells.length > 0) {
        relatedCells.forEach(rangeInfo => {
            const targetSheet = worksheet.parent.getSheetFromName(rangeInfo.sheetName);
            const { row: startRow, col: startCol, rowCount, colCount } = rangeInfo;
            
            // Handle cell ranges
            const rowLimit = startRow + rowCount;
            const colLimit = startCol + colCount;
            
            for (let r = startRow; r < rowLimit; r++) {
                for (let c = startCol; c < colLimit; c++) {
                    const childNode = createTreeNode(r, c, targetSheet, depth + 1, traversalMode);
                    traverseDependencies(childNode, targetSheet, traversalMode);
                    childNodes.push(childNode);
                }
            }
        });
    }
    
    parentNode.children = childNodes;
}

Rendering with ECharts

Once the tree srtucture is constructed, it can be rendered using ECharts' tree diagram:

function initializeDependencyChart(chartInstance, treeData, displayMode) {
    const isReviewMode = displayMode === 'review';
    const orientation = isReviewMode ? 'LR' : 'RL';
    const labelPosition = isReviewMode ? 'left' : 'right';
    const alignment = isReviewMode ? 'right' : 'left';
    
    chartInstance.setOption({
        tooltip: {
            trigger: 'item',
            triggerOn: 'mousemove'
        },
        series: [{
            type: 'tree',
            data: [treeData],
            top: '1%',
            left: '15%',
            bottom: '1%',
            right: '7%',
            symbolSize: 10,
            orient: orientation,
            label: {
                position: labelPosition,
                verticalAlign: 'middle',
                align: alignment
            },
            leaves: {
                label: {
                    position: isReviewMode ? 'right' : 'left',
                    verticalAlign: 'middle',
                    align: isReviewMode ? 'left' : 'right'
                }
            },
            emphasis: {
                focus: 'descendant'
            },
            expandAndCollapse: true,
            animationDuration: 550,
            animationDurationUpdate: 750
        }]
    });
}

Key Implemnetation Details

Range Handling: The getPrecedents() and getDependents() methods return range objects that may represent multiple cells. The implemantation loops through each row and column to properly expand range references into individual nodes.

Tree Orientation: The display direction switches based on whether viewing precedents or dependents. Precedents display right-to-left (RL) since they represent upstream dependencies, while dependents display left-to-right (LR).

Combined View: When both relationship types are needed, the implementation creates separate root nodes for each, wraps them in container nodes labeled "Precedents" and "Dependents", then merges them under a unified parent.

This approach transforms opaque spreadsheet formulas into clear visual dependency graphs, enabling auditors and analysts to trace calculation logic through complex multi-sheet workbooks with minimal effort.

Related Articles

Efficient Usage of HTTP Client in IntelliJ IDEA

IntelliJ IDEA incorporates a versatile HTTP client tool, enabling developres to interact with RESTful services and APIs effectively with in the editor. This functionality streamlines workflows, replac...

Installing CocoaPods on macOS Catalina (10.15) Using a User-Managed Ruby

System Ruby on macOS 10.15 frequently fails to build native gems required by CocoaPods (for example, ffi), leading to errors like: ERROR: Failed to build gem native extension checking for ffi.h... no...

Resolve PhpStorm "Interpreter is not specified or invalid" on WAMP (Windows)

Symptom PhpStorm displays: "Interpreter is not specified or invalid. Press ‘Fix’ to edit your project configuration." This occurs when the IDE cannot locate a valid PHP CLI executable or when the debu...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.