The solution to this problem was to use the Dynamic named range in excel for the Pivot Table data source. The Dynamic named Range formula uses a combination of the OFFSET function and the COUNTA function as follows:
=OFFSET(DataSourceWorksheet!$A$2,0,0,COUNTA(DataSourceWorksheet!$A$2:$A$1000),1)
The above formula will result in a range of cells inside A2: A1000 that have data. In my case, it took me more than one column and I have more row ranges to validate the data.
Now in C # to create a named range, I used the following:
Names wrkBookNames = wrkBook.Names; string dynamicRangeFormula = "=OFFSET(DataSourceWorksheet!$A$2,0,0,COUNTA(DataSourceWorksheet!$A$2:$A$1000),1)"; wrkBookNames.Add("MyNamedRange", dynamicRangeFormula );
and then specify this named range as the data source when creating a new pivot table, I just simply pass the string value of the range name to the PivotTableWizard method:
//get range for pivot table destination Range pivotDestinationRange = pivotWorkSheet.get_Range("A1", Type.Missing); wrkBook.PivotTableWizard( XlPivotTableSourceType.xlDatabase, "MyNamedRange", pivotDestinationRange, pivotTableName, true, true, true, true, Type.Missing, Type.Missing, false, false, XlOrder.xlDownThenOver, 0, Type.Missing, Type.Missing );
Now that rows are added or deleted in the DataSourceWorkSheet, the pivot table will only reference cells with data values ββusing the Named Range. Updating the pivot table now works as expected by calling RefreshTable:
PivotTable pivot = (PivotTable)pivotWorkSheet.PivotTables(pivotTableName); pivot.RefreshTable();
In general, this will occur as part of the method for creating a new Excel workbook or updating an existing workbook. The call to this method for an existing workbook is now based on the fact that the existing pivot table was created using a dynamic named range and will be updated accordingly.