Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refreshing an Excel Pivot table from C#

Tags:

c#

.net

I am trying to refresh a pivot table in an Excel sheet and get the following exception:

Item method in the PivotTables class failed

Heres the code:

pivotSheet.Activate();
Microsoft.Office.Interop.Excel.PivotTables pivotTables = 
        (Microsoft.Office.Interop.Excel.PivotTables)pivotSheet.PivotTables(missing);
int pivotTablesCount = pivotTables.Count;  
    if (pivotTablesCount > 0)
    {
        for (int i = 0; i <= pivotTablesCount; i++)
        {
            pivotTables.Item(i).RefreshTable(); //The Item method throws an exception
        }
    }

Any idea?

like image 295
badmaash Avatar asked Dec 22 '22 21:12

badmaash


2 Answers

Assuming the indexing starts at zero you will overrun the collection with your loop.

Try:

for (int i = 0; i < pivotTablesCount; i++)

If that doesn't work Excel probably starts indexing at 1 not at 0.

Try:

for (int i = 1; i <= pivotTablesCount; i++)
like image 90
Richard Smith Avatar answered Dec 24 '22 11:12

Richard Smith


This will help you it's working.

Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel.Workbook mWorkBook;
Microsoft.Office.Interop.Excel.Sheets mWorkSheets;
        
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
mWorkSheets = mWorkBook.Worksheets;
foreach (Microsoft.Office.Interop.Excel.Worksheet pivotSheet in mWorkSheets)
{
    Microsoft.Office.Interop.Excel.PivotTables pivotTables = pivotSheet.PivotTables();
    int pivotTablesCount = pivotTables.Count;
    if (pivotTablesCount > 0)
    {
        for (int i = 1; i <= pivotTablesCount; i++)
        {
            pivotTables.Item(i).RefreshTable(); //The Item method throws an exception
        }
    }
}     
 
like image 24
Ashish Rathore Avatar answered Dec 24 '22 09:12

Ashish Rathore