Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect pivot table in Microsoft Excel using Interop c#

Tags:

c#

excel

interop

I am trying to detect whether a cell in Microsoft excel contains a Pivot Table by using Microsoft Interop c#

What I want to do is loop through all of the cells as indicated in the code below, and then if the cell contains a pivot table, I want to store the row and column information of that cell in an integer value as such:

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;
        }
    }
}

I've tried looking at MSDN and other sources but can't seem to find any methods for detecting if a cell contains a pivot table.

Any help is appreciated, thanks.

like image 417
Alex Avatar asked Jan 07 '23 14:01

Alex


2 Answers

Here is some code for reference. Identify the overall Range occupied by PivotTables in the sheet and validate whether the cell is a part of the Range.

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;
            }
        }
    }
}
like image 65
CS. Avatar answered Jan 09 '23 05:01

CS.


look here is got a couple of examples about looping through Pivot tables list

pivotSheet.Activate();
Microsoft.Office.Interop.Excel.PivotTables pivotTables = 
        (Microsoft.Office.Interop.Excel.PivotTables)pivotSheet.PivotTables(missing);
int pivotTablesCount = pivotTables.Count;

Refreshing an Excel Pivot table from C#

like image 36
Ggalla1779 Avatar answered Jan 09 '23 05:01

Ggalla1779