如何仅对数据透视表层次结构中的顶级行应用条件格式

问题描述 投票:0回答:1

我正在尝试查找层次结构中所有顶级行的地址,以将条件格式应用于数据透视表。看来使用下面的方法,我只能提取字段的定义,而不能提取工作表上的实际位置。

  function fn2(workbook: ExcelScript.Workbook) {

    const sheet = workbook.getWorksheet("RC PivotTable");

    // Get the PivotTable (assuming it's the first one)
    const pivotTable = sheet.getPivotTables()[0];

    // Access the row hierarchy
    const rowHierarchies = pivotTable.getRowHierarchies();

    // Iterate through each row hierarchy
    for (let i = 0; i < rowHierarchies.length; i++) {
        const hierarchy = rowHierarchies[i];

        // Get the fields
        const fields = hierarchy.getFields();
        for (let j = 0; j < fields.length; j++) {
            const field = fields[j];

            // Get the items
            const items = field.getItems();
            for (let k = 0; k < items.length; k++) {
                const item = items[k];
                console.log(`hierarchy: ${hierarchy.getName()} | field: ${field.getName()} | item: ${item.getName()}`);
            }
        }
    }
}

有没有办法提取工作表上显示的每个顶级行的地址范围?

pivot-table office-scripts excel-automation
1个回答
0
投票

有一个解决方案可以获取顶级行的范围。根据需要修改您的枢轴布局。

function main(workbook: ExcelScript.Workbook) {
    const sheet = workbook.getWorksheets()[0];
    // Get the PivotTable (assuming it's the first one)
    const pivotTable = sheet.getPivotTables()[0];
    // Access the row hierarchy
    const rowHierarchies = pivotTable.getRowHierarchies();
    // Iterate through each row hierarchy
    let topList :string[] = []; 
    const TARGET_CATE = "Category";
    for (let i = 0; i < rowHierarchies.length; i++) {
        const hierarchy = rowHierarchies[i];
        // Get the fields
        const fields = hierarchy.getFields();
        for (let j = 0; j < fields.length; j++) {
            const field = fields[j];
            // Get the items
            const items = field.getItems();
            for (let k = 0; k < items.length; k++) {
                const item = items[k];
                if (hierarchy.getName() === TARGET_CATE){
                    // extract "B" from the string "[Range].[Category].&[B]", modify as needed
                    let topItem = item.getName().split("&[").pop()?.split("]")[0] || null
                    topList.push(topItem)
                }
            }
        }
    }
    const pvtRng = pivotTable.getLayout().getRange(); // pivottable range
    const rowLableRng = pivotTable.getLayout().getRowLabelRange(); // row lable range
    const rowCnt = rowLableRng.getRowCount();
    for(let i=0; i<rowCnt; i++){
        const rowCell = rowLableRng.getCell(i, 0);
        if (topList.includes(rowCell.getText())){ // apply filling color
            rowCell.getEntireRow().getIntersection(pvtRng).getFormat().getFill().setColor("FFFF00")
        }
    }
}

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.