使用ClosedXML在Excel-2010中创建数据透视表

时间:2016-01-18 15:28:27

标签: excel powershell pivot-table closedxml

使用ClosedXML-0.76,我试图创建一个基本的数据透视表,到目前为止没有运气。 代码在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")

Excel文件已损坏,无法恢复。我忘了什么吗?发现此相关帖子遗憾无法回答(https://stackoverflow.com/questions/33437738/closedxml-pivot-table-creation-results-in-corrupt-spreadsheet)。

感谢任何提示。

0 个答案:

没有答案