PowerShell Excel数据透视


class data{
[string[]]$Name
[string[]]$Orientation
[string[]]$Caption
[int32[]]$Function

}

Function New-PivotTable{

param(
[parameter(mandatory=$true)][string]$Path,
[parameter(mandatory=$true)][int]$SheetIndex,
[parameter(mandatory=$true)][string[]]$Rows,
#[parameter(mandatory=$true)][string[]]$Columns,
[parameter(mandatory=$true)][System.Object]$Data,
#[parameter(mandatory=$true)][string[]]$Filter,
[parameter(mandatory=$true)][string]$RowName

)

$xl=New-Object -ComObject excel.application
$xl.visible=$true
$xl.AlertBeforeOverwriting=$false
$xl.DisplayAlerts=$false
$wb=$xl.Workbooks.Open($Path)
$func=$xl.WorksheetFunction #Excel函数
$ws=$wb.sheets.item($SheetIndex)
$pv=$wb.sheets.add() #数据透视表
$cache=$wb.PivotCaches().Create([Microsoft.Office.Interop.Excel.XlPivotTableSourceType]::xlDatabase,$ws.UsedRange) # 创建缓存
$pivot=$cache.CreatePivotTable($pv.UsedRange) #创建数据透视表

#增加行
foreach($item in $Rows){
$row=$pivot.PivotFields($item)
$row.Orientation =[Microsoft.Office.Interop.Excel.XlPivotFieldOrientation]::xlRowField
}

$pivot.CompactLayoutRowHeader=$RowName#更改行名称b
#增加列

for($i=0;$i -lt $Data.Name.Length;$i++){

$info=$pivot.PivotFields($Data.Name[$i])
$info.Orientation =[Microsoft.Office.Interop.Excel.XlPivotFieldOrientation]::xlDataField

$info.Function=[int32]($Data.Function[$i]) #-4112计数,-4157求和 -4106 平均 Max -4136 Min -4139 Product -4149 CountNumbers -4113 StdDev -4155 StdDevp -4156 Var -4164 Var -4165,记得转换
$info.Caption=$Data.Caption[$i] #记得顺序在function之下
}
#$wb.save()
#$wb.close()

}

$Data=[data]::new()
$Data.Caption=@(“AgeT”,’NumT’)
$Data.Function=@(-4112,-4106)
$Data.Name=@(“Age”,’Num’)
New-PivotTable -Path “C:\Users\lwang52\OneDrive – Schlumberger\Desktop\test.xlsx” -SheetIndex 1 -Rows @(‘Name’,’Seg’) -data $Data -RowName “Name”

本文链接: https://www.pstips.net/powershell-excel%e6%95%b0%e6%8d%ae%e9%80%8f%e8%a7%86.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注