0

Using ClosedXML-0.76, I'm trying to create a basic Pivot Table with no luck so far. The code is in PowerShell:

# ClosedXML assembly and dependencies
Add-Type -Path "path\to\DocumentFormat.OpenXml.2.5\lib\DocumentFormat.OpenXml.dll"
Add-Type -Path "path\to\closedXML-0.76\ClosedXML.dll" 

# Adding data from a DataTable
$dt = New-Object System.Data.DataTable
$dt.TableName = "test"
$dt.Columns.Add("col1")
$dt.Columns.Add("col2")
$dt.Columns.Add("col3")

$dt.Rows.Add(@(1,2,3))
$dt.Rows.Add(@(4,5,6))

$workbook = New-Object -TypeName ClosedXML.Excel.XLWorkbook
$ws = $workbook.AddWorksheet($dt)

# creating the Pivot Table on another worksheet
$dataRange = $ws.RangeUsed()

# Add a new sheet for our pivot table
$ptSheet = $workbook.Worksheets.Add("Pivot Table");

#Create the pivot table, using the data from the "PastrySalesData" table
$pt = $ptSheet.PivotTables.AddNew("Pivot Table", $ptSheet.Cell(1, 1), $dataRange);

# Simplest Pivot Table with Row Labels
$pt.RowLabels.Add("col1");
$pt.RowLabels.Add("col2")

$workbook.SaveAs("C:/temp/test.xlsx")

The Excel file is corrupted with no recovery. Do I forget something? Found this related post with no answer unfortunately (https://stackoverflow.com/questions/33437738/closedxml-pivot-table-creation-results-in-corrupt-spreadsheet).

halfer
  • 19,824
  • 17
  • 99
  • 186
jgran
  • 1,111
  • 2
  • 11
  • 21
  • My first guess is that you need `RowLabels`, `ColumnLabels` and `Values` in your Pivot table. Will try it out later if you haven't yet. – Raidri Jan 18 '16 at 15:47
  • Thanks. I'm not sure ColumnLabels and Values are mandatory. I'm no a specialist in any way though. The ClosedXML doc [ClosedXML docs](https://closedxml.codeplex.com/wikipage?title=Pivot%20Table%20example&referringTitle=Documentation) and my trials in creating very simple Pivot table in Excel suggest that. – jgran Jan 19 '16 at 10:54

0 Answers0