操作数据透视表

可能的使用场景

除了创建新的数据透视表外,您还可以操作新的和现有的数据透视表。您可以更改数据透视表的源范围中的数据,然后刷新和计算它,并获取数据透视表单元格的新值。更改数据透视表源范围中的值后,请使用PivotTable.RefreshData()PivotTable.CalculateData() 方法来刷新数据透视表。

操作数据透视表

以下示例代码加载了示例excel文件,并访问了它的第一个工作表中的现有数据透视表。它更改了位于数据透视表源范围内的单元格B3的值,然后刷新了数据透视表。在刷新数据透视表之前,它访问了数据透视表单元格H8的值,为15,刷新数据透视表后,其值变为6。请参阅使用此代码生成的输出excel文件和显示示例代码对示例excel文件的影响的屏幕截图。还请参阅下面的控制台输出,显示刷新数据透视表前后数据透视表单元格H8的值。

todo:image_alt_text

示例代码

Aspose::Cells::Startup();
//For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-C
//Source directory path
U16String dirPath(u"..\\Data\\PivotTables\\");
//Output directory path
U16String outPath(u"..\\Data\\Output\\");
//Path of input excel file
U16String sampleManipulatePivotTable = dirPath + u"sampleManipulatePivotTable.xlsx";
//Path of output excel file
U16String outputManipulatePivotTable = outPath + u"outputManipulatePivotTable.xlsx";
//Load the sample excel file
Workbook wb(sampleManipulatePivotTable);
//Access first worksheet
Worksheet ws = wb.GetWorksheets().Get(0);
//Change value of cell B3 which is inside the source data of pivot table
ws.GetCells().Get(u"B3").PutValue(u"Cup");
//Get the value of cell H8 before refreshing pivot table
U16String val = ws.GetCells().Get(u"H8").GetStringValue();
std::cout << "Before refreshing Pivot Table value of cell H8: " << val.ToUtf8() << std::endl;
//Access pivot table, refresh and calculate it
PivotTable pt = ws.GetPivotTables().Get(0);
pt.RefreshData();
pt.CalculateData();
//Get the value of cell H8 after refreshing pivot table
val = ws.GetCells().Get(u"H8").GetStringValue();
std::cout << "After refreshing Pivot Table value of cell H8: " << val.ToUtf8() << std::endl;
//Save the output excel file
wb.Save(outputManipulatePivotTable);
Aspose::Cells::Cleanup();

控制台输出

以下是上述示例代码在提供的示例excel文件上执行时的控制台输出。

 Before refreshing Pivot Table value of cell H8: 15

After refreshing Pivot Table value of cell H8: 6