使用Interop c#在Microsoft Excel中检测数据透视表

Tre*_*lez 4 c# excel interop

我试图通过使用Microsoft Interop c#来检测Microsoft Excel中的单元格是否包含数据透视表

我想要做的是循环遍历所有单元格,如下面的代码所示,然后如果单元格包含数据透视表,我想将该单元格的行和列信息存储为整数值,如下所示:

int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;

Excel.Range cell = null;

for (int iRow = 1; iRow < rowCount; iRow++)
{
    for (int iCol = 1; iCol <= colCount; iCol++)
    {
        /* This line of code is probably wrong */
        cell = xlRange.Cells[iRow, iCol] as Excel.Range;

        if(/*Cell contains PivotTable*/)
        {
            int rowLocation = iRow;
            int colLocation = iCol;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试过查看MSDN和其他来源,但似乎无法找到任何方法来检测单元格是否包含数据透视表.

任何帮助表示赞赏,谢谢.

CS.*_*CS. 5

这是一些供参考的代码.确定工作表中数据透视表占用的整个范围,并验证单元格是否是范围的一部分.

private Excel.Range IdentifyPivotRanges(Excel.Range xlRange)
{
    Excel.Range pivotRanges = null;
    Excel.PivotTables pivotTables = xlRange.Worksheet.PivotTables();
    int pivotCount = pivotTables.Count;
    for (int i = 1; i <= pivotCount; i++)
    {
        Excel.Range tmpRange = xlRange.Worksheet.PivotTables(i).TableRange2;
        if (pivotRanges == null) pivotRanges = tmpRange;
        pivotRanges = this.Application.Union(pivotRanges, tmpRange);
    }
    return pivotRanges;
}

private void CheckCellsForPivot(Excel.Range xlRange)
{
    Excel.Range pivotRange = IdentifyPivotRanges(xlRange);
    int rowCount = xlRange.Rows.Count;
    int colCount = xlRange.Columns.Count;
    for (int iRow = 1; iRow <= rowCount; iRow++)
    {
        for (int iCol = 1; iCol <= colCount; iCol++)
        {
            var cell = xlRange.Cells[iRow, iCol];
            if (Application.Intersect(pivotRange, cell) != null)
            {
                int rowLocation = iRow;
                int colLocation = iCol;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)