Home » excel » excel – Example of how to create a Pivot Table in ClosedXML

excel – Example of how to create a Pivot Table in ClosedXML

Posted by: admin May 14, 2020 Leave a comment


We are using ClosedXML to generate .XLSX spreadsheets because it is small, nimble, and quick. It appears that all the pivot table classes and methods are there in the API, but there is no documentation or examples on how to go about (in the correct sequence) creating pivot tables. Our attempts at guessing have produced files that when opened, give an error about XML corruption, and Excel prompts you to delete the pivot table.

How to&Answers:

I’m not sure at what version ClosedXML implemented Pivot Tables, but as of at least v0.70 they have been implemented. An example can be found in the ClosedXML Documentation. Below is an C# example I’m using in my own project.

IXLWorksheet xlPvSheet = xlBook.Worksheets.Add("Pivot");
IXLPivotTable xlPvTable = xlPvSheet.PivotTables.AddNew("PivotTable", xlPvSheet.Cell(1,1), xlForecastSheet.Range(1, 1, r, 11));
xlPvTable.RowLabels.Add("Box Type");
xlPvTable.RowLabels.Add("Box Color");
xlPvTable.ColumnLabels.Add("Request Date");
xlPvTable.Values.Add("Total Boxes");