Hi,
Thanks for your posting and using Aspose.Cells.
Please split your outer foreach loop into two loops like this and it works fine.
foreach (Worksheet wsheet in wb.Worksheets)
{
wsheet.RefreshPivotTables();
foreach (PivotTable pivot in wsheet.PivotTables)
{
<span style=“color: rgb(255, 20, 147); font-family: “Courier New”; font-size: small;”> pivot.CalculateData();
}
}
foreach (Worksheet wsheet in wb.Worksheets)
{
foreach (Aspose.Cells.Charts.Chart chart in wsheet.Charts)
{
chart.RefreshPivotData();
chart.Calculate();
}
}
Here is the complete sample code for your reference.
C#
Workbook wb = new Workbook(“sampleIn1.xlsx”);
//simulate getting new data set
Worksheet ws = wb.Worksheets[“Raw_Data”];
ws.Cells.Clear();
int currentRow = 0;
Cell clHead = ws.Cells[currentRow++, 0];
clHead.Value = “Color”;
for (int i = 0; i < 20; i++)
{
Cell cl = ws.Cells[currentRow++, 0];
cl.Value = “Blue”;
}
for (int i = 0; i < 30; i++)
{
Cell cl = ws.Cells[currentRow++, 0];
cl.Value = “Red”;
}
for (int i = 0; i < 40; i++)
{
Cell cl = ws.Cells[currentRow++, 0];
cl.Value = “Green”;
}
Cell lastcell = ws.Cells[currentRow - 1, 0];
//Resize the Named range (pivot table data source)
NameCollection names = wb.Worksheets.Names;
Name name = names[“ColorsRange”];
name.RefersTo = “=Raw_Data!$A$1:” + lastcell.Name;
wb.CalculateFormula();
foreach (Worksheet wsheet in wb.Worksheets)
{
wsheet.RefreshPivotTables();
foreach (PivotTable pivot in wsheet.PivotTables)
{
<span style=“color: rgb(128, 0, 128); font-family: “Courier New”; font-size: small;”> pivot.CalculateData();
}
<span style=“color: rgb(128, 0, 128); font-family: “Courier New”; font-size: small;”>}
foreach (Worksheet wsheet in wb.Worksheets)
{
foreach (Aspose.Cells.Charts.Chart chart in wsheet.Charts)
{
chart.RefreshPivotData();
chart.Calculate();
}
}
SaveFormat saveFormat = SaveFormat.Xlsx;
wb.Save(“o.xlsx”, saveFormat);
saveFormat = SaveFormat.Pdf;
wb.Save(“output.pdf”, saveFormat);