Pivot Table and Source Data
Pivot Table’s Source Data
There are times when you want to create Microsoft Excel reports with pivot tables that take data from different data sources (such as a database) that are not known at design time. This article provides an approach to dynamically change a pivot table’s data source.
Changing a Pivot Table’s Source Data
- Creating a new designer template.
-
Create a new designer template file as in the screenshot below.
-
Then define a named range, DataSource, which refers to this range of cells.
Creating a designer template & defining a named range, DataSource
-
- Creating a Pivot Table Based on this named range.
-
In Microsoft Excel, choose Data, then PivotTable and PivotChart Report.
-
Create a pivot table based on the named range created in the first step.
Creating a pivot table based on the named range, DataSource
-
- Drag the corresponding field to pivot table row and column, then create the resulting pivot table as in the screenshot below.
Creating a pivot table based on a corresponding field
- Right-click the pivot table and select Table Options.
-
Check Refresh on open in Data options settings.
Setting the pivot table options
-
Now, you can save this file as your designer template file.
- Populating new data and changing source data of a pivot table.
- Once the designer template is created, use the following code to change the source data of the pivot table.
Executing the example code below changes the source data of the pivot table.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
string InputPath = dataDir + "Book1.xlsx"; | |
// Creating a file stream containing the Excel file to be opened | |
FileStream fstream = new FileStream(InputPath, FileMode.Open); | |
// Opening the Excel file through the file stream | |
Workbook workbook = new Workbook(fstream); | |
// Accessing the first worksheet in the Excel file | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Populating new data to the worksheet cells | |
worksheet.Cells["A9"].PutValue("Golf"); | |
worksheet.Cells["B9"].PutValue("Qtr4"); | |
worksheet.Cells["C9"].PutValue(7000); | |
// Changing named range "DataSource" | |
Range range = worksheet.Cells.CreateRange(0, 0, 9, 3); | |
range.Name = "DataSource"; | |
// Saving the modified Excel file | |
workbook.Save(dataDir + "output.xls"); | |
// Closing the file stream to free all resources | |
fstream.Close(); |