如何确定数据透视表生成的行数(Aspose Cells)?

时间:2016-11-18 00:30:47

标签: c# excel pivot-table 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上数据透视表上的行,所以我的while循环从未输入。

如何确定数据透视表在工作表上占用的行数,以便我可以遍历数据透视表?

或者,我是以错误的方式接近这个吗?在生成数据透视表后,是否有不同的标准方法来操作数据透视表的样式/格式?

2 个答案:

答案 0 :(得分:1)

数据透视表的RowRange属性应该逐行显示表格中的每个元素:

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

实际数据透视表中的每个单元格(无论是聚合的是什么)。

答案 1 :(得分:1)

@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担任开发人员传播者。