如何确定数据透视表生成多少行(Aspose 单元格)?

How can I determine how many rows a PivotTable generates (Aspose Cells)?

我需要有条件地为数据透视表中的范围着色。我试过这样做:

private void ColorizeContractItemBlocks(List<string> contractItemDescs)
{
    int FIRST_DESCRIPTION_ROW = 7;
    int DESCRIPTION_COL = 1;
    int ROWS_BETWEEN_DESCRIPTIONS = 4;
    int rowsUsed = pivotTableSheet.Cells.Rows.Count;
    int currentRowBeingExamined = FIRST_DESCRIPTION_ROW;
    // Loop through PivotTable data, colorizing contract items
    while (currentRowBeingExamined < rowsUsed)
    {
        Cell descriptionCell = pivotTableSheet.Cells[currentRowBeingExamined, DESCRIPTION_COL];
        String desc = descriptionCell.Value.ToString();
        if (contractItemDescs.Contains(desc))
        {
            // args are firstRow, firstColumn, totalRows, totalColumns
            Range rangeToColorize = pivotTableSheet.Cells.CreateRange(
                currentRowBeingExamined, 0,
                ROWS_BETWEEN_DESCRIPTIONS, _grandTotalsColumnPivotTable + 1);
            Style style = workBook.Styles[workBook.Styles.Add()];
            style.BackgroundColor = CONTRACT_ITEM_COLOR;
            StyleFlag styleFlag = new StyleFlag();
            styleFlag.All = true;
            rangeToColorize.ApplyStyle(style, styleFlag);
        }
        currentRowBeingExamined = currentRowBeingExamined + ROWS_BETWEEN_DESCRIPTIONS;
    }
}

...但它不起作用,因为 rowsUsed 没有考虑 pivotTableSheet 上的 PivotTable 上的行,所以我的 while 循环永远不会进入。

如何确定数据透视表在 sheet 上占用了多少行,以便我可以遍历数据透视表?

或者,我是不是用错了方法?在生成数据透视表后,是否有不同的标准方法来处理数据透视表的 styles/formatting?

支点 table 的 RowRange 属性 应该带您逐行浏览 table 中的每个元素:

Excel.Worksheet ws = wb.Sheets["Sheet1"];
Excel.PivotTable pt = ws.PivotTables("PivotTable1");
Excel.Range cell;

foreach (Excel.Range row in pt.RowRange)
{
    cell = ws.Cells[row.Row, 5];  // for example, whatever is in column E
    // do your formatting here
}

还有其他可用范围——例如,我通常只关心:

pt.DataBodyRange

这是实际数据透视表 table 中的每个单元格(聚合的内容)。

@B。 Clay Shannon,您可以考虑使用以下任何 API 来满足您的要求。我已经为代码添加了注释供您参考。

var book = new Workbook(dir + "sample.xlsx");
var sheet = book.Worksheets[0];
var pivot = sheet.PivotTables[0];

// DataBodyRange returns CellArea that represents range between the header row & insert row
var dataBodyRange = pivot.DataBodyRange;
Console.WriteLine(dataBodyRange);
// TableRange1 returns complete Pivot Table area except page fields
var tableRange1 = pivot.TableRange1;
Console.WriteLine(tableRange1);
// TableRange2 returns complete Pivot Table area including page fields
var tableRange2 = pivot.TableRange2;
Console.WriteLine(tableRange2);
// ColumnRange returns range that represents the column area of the Pivot Table
var columnRange = pivot.ColumnRange;
Console.WriteLine(columnRange);
// RowRange returns range that represents the row area of the Pivot Table
var rowRange = pivot.RowRange;
Console.WriteLine(rowRange);

如果您仍然遇到任何困难,请在 Aspose.Cells support forum 的讨论帖中分享您的示例电子表格以及所需的结果(您可以在 Excel 应用程序中手动创建)以进行彻底调查。

注意我在 Aspose 担任开发人员布道师。