0
votes

I am trying to use ClosedXML to export data with a pivot table. I am able to create the pivot table with the following code, but the SetCalculation is giving me some trouble. I am wanting to take the difference between the Amount column for each year. The Excel worksheet is unable to load and crashes all of Excel.

var pt = worksheet.PivotTables.AddNew("PivotTable", worksheet.Cell(rowIndex+3, 1), table.AsRange());

pt.ReportFilters.Add("Department");
pt.ReportFilters.Add("Month");
pt.ColumnLabels.Add("Year").SetCollapsed();
pt.RowLabels.Add("Account").SetCollapsed();
pt.RowLabels.Add("Description").SetCollapsed();
pt.Values.Add("Amount", "Amount").NumberFormat.NumberFormatId = 4;
pt.Values.Add("Diff","Diff").SetBaseField("Year").
SetBaseItem("Amount").SetCalculation
(XLPivotCalculation.DifferenceFrom).NumberFormat.NumberFormatId = 4;
1
This looks like a bug. Please log this on the ClosedXML Github repo by completing the full issue template. - Francois Botha

1 Answers

0
votes

I figured it out:

pt.Values.Add("Amount","Diff%").SetCalculation(XLPivotCalculation.PercentageDifferenceFrom).SetBaseField("Year").SetCalculationItem(XLPivotCalculationItem.Previous).NumberFormat.NumberFormatId = 10;