How to update PivotTable data source using C#?

Joel Briggs picture Joel Briggs · Nov 21, 2011 · Viewed 11.8k times · Source

I would like to know how to update an existing pivot table data source. I am using Microsoft.Office.Interop.Excel and targeting users with Excel 2010.

I am currently able to refresh the pivot table which works fine, however when more rows are added I want to include these rows in the pivot table data source. For example, the pivot table data source when viewed in Excel is DataSourceWorksheet!$A$2:$U$26 and I would like it to be changed to DataSourceWorksheet!$A$2:$U$86 (60 more rows) after my update/refresh excel file code has run.

Here's a simplified version of my code

Application excelApplication = new Application();
Workbooks workbooks = excelApplication.Workbooks;
wrkBook = workbooks.Open(EXCEL_DOCUMENT_PATH, Missing.Value, false, Missing.Value,
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                    Missing.Value, true, Missing.Value, Missing.Value,
                    Missing.Value, Missing.Value, Missing.Value);

/* update data source worksheet code here (omitted for example) */

Worksheet pivotWorkSheet = (Worksheet)wrkBook.Sheets[PIVOT_SHEET_NAME];
PivotTable pivot = (PivotTable)pivotWorkSheet.PivotTables(pivotTableName); 

/* I would like to update the pivot tables data source here...

   I could use Range object from data source worksheet...

   Basically just want to tell pivot table, use these cells now... */

pivot.RefreshTable();

/* cleanup code here (omitted for example) */

A solution which may work, would be to just regenerate the pivot table again using wrkBook.PivotTableWizard( ... ) . However, this will not work for my situation since users would prefer to modify their pivot table by changing selected fields, rows, columns, etc. It just needs to be updated when the data source worksheet changes.

Answer

Palanivel picture Palanivel · Mar 19, 2012

its very simple..

pivot.SourceData = "SheetName!R1C1:R18C18"
pivot.RefreshTable();

Thats all..

Remember, always we need to give Row and Column format.

E.g.

"SheetName!" + R + Rowstartingnumber + C + Column StartingNumber  : R + Rowendnumber + C + Column Endnumber.

i.e "SheetName!R1C1:R12C13" like that.

If you give "SheetName!$A$1:$Q$18" like this, it will not work.