Quantcast
Channel: ClosedXML - The easy way to OpenXML
Viewing all articles
Browse latest Browse all 1877

New Post: Code examples on creating Pivot Table?

$
0
0
I'm using the latest from NuGet, and PivotTables do seem to work, though it's definitely possible to create one that Excel thinks is invalid. I was running into the same issue (Excel offering to delete the PivotTable on startup) when I just used the PivotTables.AddNew() method. However, if I then set at least one RowLabel and one Value, it does work.

Here's what I'm doing:
var workbook = new XLWorkbook();
var sheet = workbook.Worksheets.Add("Report");

var source = sheet.Cell(1, 1).InsertTable(Items, true);

var pt = sheet.PivotTables.AddNew("PivotTable", sheet.Cell(1, 5), sheet.Range("A1", "C66"));

pt.RowLabels.Add("Division");
pt.Values.Add("Number");
Where "Items" is an IEnumerable of a class of report data stuff I'm trying to make the table from. Note the manual Range in AddNew() - I started by using source.Range, but that didn't work because it didn't include the table header row. Anyway, this code results in a file with a functional PivotTable; if I leave out either of the last two lines I get an error when I open the file.

Viewing all articles
Browse latest Browse all 1877

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>