Compare commits

..

34 Commits

Author SHA1 Message Date
dfinke
6166f0e87c Use Copy method to copy ranges from one sheet to another 2022-09-09 19:04:37 -04:00
dfinke
bb8297c528 Multiple ways to try the new HeaderName parameter 2022-09-09 19:04:08 -04:00
dfinke
b61aef888f Add and test new HeaderName parameter 2022-09-09 19:03:06 -04:00
dfinke
4c002358fe bump version, update changelog 2022-09-09 19:02:27 -04:00
dfinke
be5d270f44 update change log 2022-09-03 16:51:59 -04:00
Doug Finke
f9fb49ad04 Merge pull request #1234 from stahler/patch-2
Update open-excelpackage.md
2022-08-25 13:51:21 -04:00
Wes Stahler
4727bb3b2b Update open-excelpackage.md
Small changes to Example 2
2022-08-24 21:34:46 -04:00
dfinke
ac435fc1e1 bump version 2022-08-24 18:37:24 -04:00
dfinke
340ffc560b Use EZOut to format data form Excel to Mardown tables and Yaml 2022-08-24 18:37:14 -04:00
Doug Finke
069c227391 Merge pull request #1233 from g-pearl/master
Update Bottom Spelling Error
2022-08-24 18:21:38 -04:00
g-pearl
fa4f3a23cd Update Bottom Spelling Error 2022-08-24 08:54:36 -06:00
Doug Finke
f54db0e2d9 Merge pull request #1220 from dfinke/Add-Group-Column-Tests
Added Group Column tests
2022-07-20 07:15:46 -04:00
dfinke
8c1388a799 Added Group Column tests 2022-07-17 11:24:51 -04:00
dfinke
7c473d1fb6 bump version 2022-07-16 13:45:40 -04:00
dfinke
31366057df Add images for changelog 2022-07-16 13:45:34 -04:00
Doug Finke
f102ece700 Merge pull request #1219 from jhoneill/PivotTableUpdates
Pivot table updates
2022-07-16 13:25:17 -04:00
dfinke
950b9ab078 update with examples that were added 2022-07-16 12:19:23 -04:00
Doug Finke
869ab59a8a tweak README 2022-07-16 11:47:33 -04:00
Doug Finke
1e9a73d176 Merge pull request #1214 from dbrennand/feat/vba-pivotable-tabular-repeat-label-no-subtotals
Feat/VBA-PivotTable-Tabular-Repeat-Label-No-Subtotals
2022-07-16 11:30:19 -04:00
James O'Neill
37e6896741 Merge branch 'dfinke:master' into PivotTableUpdates 2022-07-14 20:27:59 +01:00
Doug Finke
c39e6cc24c Merge pull request #1216 from chadmando/fixtypo
Fix typo in help
2022-07-14 14:15:16 -04:00
James O'Neill
5ab9d6f23f Add column to GroupNumeric/Date in PivotTables. 2022-07-14 17:43:55 +01:00
chadmando
81e60be51d Fix typo in help
Open-ExcelPackage Example #2 Line#48
remove 'and'
2022-07-13 15:36:17 -05:00
dfinke
943ca7e6d1 Added -Show 2022-07-13 14:13:22 -04:00
Doug Finke
513ff59ba8 Merge pull request #1208 from kkazala/kkazala/exportformatting
Kkazala/exportformatting
2022-07-13 12:09:55 -04:00
dbrennand
45fc5a2631 fix: add missing -Path parameter 2022-07-13 16:59:18 +01:00
dbrennand
8b30fce81a feat: add VBA example to modify PivotTables
Excel macro example for changing all PivotTables in the workbook to Tabular form, repeats labels and disables Subtotals.
2022-07-13 16:57:22 +01:00
dfinke
0990c0ef09 used $PSScriptRoot instead 2022-07-13 09:50:02 -04:00
Kinga Kazala
724ed6b197 Get-ConditionalFormatting function added 2022-07-13 09:34:30 +02:00
Kinga Kazala
087feedde6 fix: corrected the script to include sheet name, and to add '=' in the ConditionValue 2022-07-13 09:26:19 +02:00
Kinga Kazala
b92ea56fe9 GetConditionalFormatting.xlsx added 2022-07-11 07:58:29 +02:00
Kinga Kazala
c4eed8c25d GetConditionalFormatting.ps1 example added: exports conditional formatting rules in a 'ready to use' format 2022-07-05 16:05:40 +02:00
Kinga Kazala
9051ffc0e5 example update: format both cells, plus format whole row 2022-07-05 15:59:32 +02:00
James O'Neill
5b4857d7a0 New subtotals, tweak module stats example 2022-06-21 16:58:42 +02:00
32 changed files with 647 additions and 20 deletions

133
Add-Subtotals.ps1 Normal file
View File

@@ -0,0 +1,133 @@
Function Add-Subtotals {
param(
[Parameter(Mandatory=$true, Position=0)]
$ChangeColumnName , # = "Location"
[Parameter(Mandatory=$true, Position=1)]
[hashtable]$AggregateColumn , #= @{"Sales" = "SUM" }
[Parameter(Position=2)]
$ExcelPath = ([System.IO.Path]::GetTempFileName() -replace "\.tmp", ".xlsx") ,
[Parameter(Position=3)]
$WorksheetName = "Sheet1",
[Parameter(ValueFromPipeline=$true)]
$InputObject, #$DataToPivot | Sort location, product
[switch]$HideSingleRows,
[switch]$NoSort,
[switch]$NoOutLine,
[switch]$Show
)
begin {
if (-not $PSBoundParameters.ContainsKey('ExcelPath')) {$Show = $true}
$data = @()
$aggFunctions = [ordered]@{
"AVERAGE" = 1; "COUNT" = 2; "COUNTA" = 3 #(non empty cells) f
"MAX" = 4; "MIN" = 5; "PRODUCT" = 6; "STDEV" = 7 # (sample)
"STDEVP" = 8 # (whole population);
"SUM" = 9; "VAR" = 10 # (Variance sample)
"VARP" = 11 # (whole population) #add 100 to ignore hidden cells
}
}
process {
$data += $InputObject
}
end {
if (-not $NoSort) {$data = $data | Sort-Object $changeColumnName}
$Header = $data[0].PSObject.Properties.Name
#region turn each entry in $AggregateColumn "=SUBTOTAL(a,x{0}}:x{1})" where a is the aggregate function number and x is the column letter
$aggFormulas = @{}
foreach ($k in $AggregateColumn.Keys) {
$columnNo = 0 ;
while ($columnNo -lt $header.count -and $header[$columnNo] -ne $k) {$columnNo ++}
if ($columnNo -eq $header.count) {
throw "'$k' isn't a property of the first row of data."; return
}
if ($AggregateColumn[$k] -is [string]) {
$aggfn = $aggFunctions[$AggregateColumn[$k]]
if (-not $aggfn) {
throw "$($AggregateColumn[$k]) is not a valid aggregation function - these are $($aggFunctions.keys -join ', ')" ; return
}
}
else {$aggfn = $AggregateColumn[$k]}
$aggFormulas[$k] = "=SUBTOTAL({0},{1}{{0}}:{1}{{1}})" -f $aggfn , (Get-ExcelColumnName ($columnNo+1) ).ColumnName
}
if ($aggformulas.count -lt 1) {throw "We didn't get any aggregation formulas"}
$aggFormulas | out-string -Stream | Write-Verbose -Verbose
#endregion
$insertedRows = @()
$singleRows = @()
$previousValue = $data[0].$changeColumnName
$currentRow = $lastChangeRow = 2
#region insert subtotals and send to excel:
#each time there is a change in the column we're intetersted in.
#either Add a row with the value and subtotal(s) function(s) if there is more than one row to total
#or note the row if there was only one row with that value (we may hide it later.)
$excel = $data |
ForEach-Object -process {
if ($_.$changeColumnName -ne $previousValue) {
if ($lastChangeRow -lt ($currentrow - 1)) {
$NewObj = @{$changeColumnName = $previousValue}
foreach ($k in $aggFormulas.Keys) {
$newobj[$k] = $aggformulas[$k] -f $lastChangeRow, ($currentRow - 1)
}
$insertedRows += $currentRow
[pscustomobject]$newobj
$currentRow += 1
}
else {$singleRows += $currentRow }
$lastChangeRow = $currentRow
$previousValue = $_.$changeColumnName
}
$_
$currentRow += 1
} -end { # the process block won't output the last row
if ($lastChangeRow -lt ($currentrow - 1)) {
$NewObj = @{$changeColumnName = $previousValue}
foreach ($k in $aggFormulas.Keys) {
$newobj[$k] = $aggformulas[$k] -f $lastChangeRow, ($currentRow - 1)
}
$insertedRows += $currentRow
[pscustomobject]$newobj
}
else {$singleRows += $currentRow }
} | Export-Excel -Path $ExcelPath -PassThru -AutoSize -AutoFilter -AutoNameRange -BoldTopRow -WorksheetName $WorksheetName -Activate -ClearSheet #-MaxAutoSizeRows 10000
#endregion
#Put the subtotal rows in bold optionally hide rows where only one has the value of interest.
$ws = $excel.$WorksheetName
#We kept lists of the total rows Since 1 rows won't get expand/collapse we can hide them.
foreach ($r in $insertedrows) {$ws.Row($r).style.font.bold = $true }
if ($HideSingleRows) {
foreach ($r in $hideRows) { $ws.Row($r).hidden = $true}
}
$range = $ws.Dimension.Address
$ExcelPath = $excel.File.FullName
$SheetIndex = $ws.index
if ($NoOutline) {
Close-ExcelPackage $excel -show:$Show
return
}
else {
Close-ExcelPackage $excel
try { $excelApp = New-Object -ComObject "Excel.Application" }
catch { Write-Warning "Could not start Excel application - which usually means it is not installed." ; return }
try { $excelWorkBook = $excelApp.Workbooks.Open($ExcelPath) }
catch { Write-Warning -Message "Could not Open $ExcelPath." ; return }
$ws = $excelWorkBook.Worksheets.item($SheetIndex)
$null = $ws.Range($range).Select()
$null = $excelapp.ActiveCell.AutoOutline()
$null = $ws.Outline.ShowLevels(1,$null)
$excelWorkBook.Save()
if ($show) {$excelApp.Visible = $true}
else {
[void]$excelWorkBook.close()
$excelapp.Quit()
}
}
}
}

View File

@@ -0,0 +1,21 @@
try { Import-Module $PSScriptRoot\..\..\ImportExcel.psd1 } catch { throw ; return}
# This example is using Excel generated by Highlight-DiffCells.ps1
# The displayed rule should be the same as in the PS script
function Get-ConditionalFormatting {
param (
[string] $xlSourcefile
)
$excel = Open-ExcelPackage -Path $xlSourcefile
$excel.Workbook.Worksheets | ForEach-Object {
$wsNme = $_.Name
$_.ConditionalFormatting | ForEach-Object {
"Add-ConditionalFormatting -Worksheet `$excel[""$wsNme""] -Range '$($_.Address)' -ConditionValue '=$($_.Formula)' -RuleType $($_.Type) "
}
}
}
$xlSourcefile = "$PSScriptRoot\GetConditionalFormatting.xlsx"
Get-ConditionalFormatting -xlSourcefile $xlSourcefile

View File

@@ -1,6 +1,5 @@
try { Import-Module $PSScriptRoot\..\..\ImportExcel.psd1 } catch { throw ; return } try { Import-Module $PSScriptRoot\..\..\ImportExcel.psd1 } catch { throw ; return }
# Get rid of pre-exisiting sheet
$xlSourcefile = "$env:TEMP\ImportExcelExample.xlsx" $xlSourcefile = "$env:TEMP\ImportExcelExample.xlsx"
Write-Verbose -Verbose -Message "Save location: $xlSourcefile" Write-Verbose -Verbose -Message "Save location: $xlSourcefile"
@@ -21,6 +20,7 @@ South,Delaware,712,508
$excel = $data | Export-Excel $xlSourcefile -AutoSize -PassThru $excel = $data | Export-Excel $xlSourcefile -AutoSize -PassThru
Add-ConditionalFormatting -Worksheet $excel.sheet1 -Range "C2:C10" -ConditionValue '=C2=D2' -RuleType Expression -BackgroundColor Cyan Add-ConditionalFormatting -Worksheet $excel.sheet1 -Range "C2:D10" -ConditionValue '=$C2=$D2' -RuleType Expression -BackgroundColor ([System.Drawing.Color]::Thistle) -Bold
Add-ConditionalFormatting -Worksheet $excel.sheet1 -Range "A2:D10" -ConditionValue '=$C2=$D2' -RuleType Expression -BackgroundColor ([System.Drawing.Color]::LavenderBlush)
Close-ExcelPackage $excel -Show Close-ExcelPackage $excel -Show

View File

@@ -0,0 +1,29 @@
<#
Copy a range from WorksheetA to WorksheetB
#>
$data = ConvertFrom-Csv @"
Region,State,Units,Price
West,Texas,927,923.71
North,Tennessee,466,770.67
East,Florida,520,458.68
East,Maine,828,661.24
West,Virginia,465,053.58
North,Missouri,436,235.67
South,Kansas,214,992.47
North,North Dakota,789,640.72
South,Delaware,712,508.55
"@
$xlfile = "./test.xlsx"
Remove-Item $xlfile -ErrorAction SilentlyContinue
$data | Export-Excel $xlfile -WorksheetName WorksheetA
$data | Export-Excel $xlfile -WorksheetName WorksheetB
$excel = Open-ExcelPackage $xlfile
# Copy a range from WorksheetA to WorksheetB
$excel.WorksheetA.Cells["A3:B5"].Copy($excel.WorksheetB.Cells["G3"])
Close-ExcelPackage $excel -Show

View File

@@ -6,15 +6,16 @@
#> #>
param( param(
[Parameter(Mandatory=$true)] $moduleName = "ImportExcel",
$moduleName,
[ValidateSet('Column','Bar','Line','Pie')] [ValidateSet('Column','Bar','Line','Pie')]
$chartType="Line" $chartType="Line"
) )
$galleryUrl = "https://www.powershellgallery.com/packages/$moduleName" $download = Get-HtmlTable "https://www.powershellgallery.com/packages/$moduleName" -FirstDataRow 1 |
$nolegend = '-nolegend' Select-Object @{n="Version";e={$v = $Null ; if ($_.version -is [valuetype]) {[string][version]($_.version.tostring("0.0")) }
if($chartType -eq 'pie') {$nolegend = $null} elseif ($_.version -is [string] -and [version]::TryParse($_.version.trim(),[ref]$v)) {$v}
$code = "$($chartType)Chart (Get-HtmlTable $galleryUrl -FirstDataRow 1 | sort lastupdated -desc) -title 'Download stats for $moduleName' $nolegend" else {$_.Version.trim() -replace "\s+"," " } }},
Downloads, @{n="LastUpdated";e={[datetime]$_.last_updated}} |
Sort-Object lastupdated -Descending
$code | Invoke-Expression & "$($chartType)Chart" $download "Download stats for $moduleName" -nolegend:($chartype -ne 'pie')

View File

@@ -0,0 +1,10 @@
param(
[Alias('FullName')]
[String[]]$Path
)
if ($PSVersionTable.PSVersion.Major -gt 5 -and -not (Get-Command Format-Markdown -ErrorAction SilentlyContinue)) {
throw "This requires EZOut. Install-Module EZOut -AllowClobber -Scope CurrentUser"
}
Import-Excel $Path | Format-Markdown

View File

@@ -0,0 +1,10 @@
param(
[Alias('FullName')]
[String[]]$Path
)
if ($PSVersionTable.PSVersion.Major -gt 5 -and -not (Get-Command Format-YAML -ErrorAction SilentlyContinue)) {
throw "This requires EZOut. Install-Module EZOut -AllowClobber -Scope CurrentUser"
}
Import-Excel $Path | Format-YAML

View File

@@ -0,0 +1,11 @@
"OrderId","Category","Sales","Quantity","Discount"
"1","Cosmetics","744.01","7","0.7"
"2","Grocery","349.13","25","0.3"
"3","Apparels","535.11","88","0.2"
"4","Electronics","524.69","60","0.1"
"5","Electronics","439.1","41","0"
"6","Apparels","56.84","54","0.8"
"7","Electronics","326.66","97","0.7"
"8","Cosmetics","17.25","74","0.6"
"9","Grocery","199.96","39","0.4"
"10","Grocery","731.77","20","0.3"
1 OrderId Category Sales Quantity Discount
2 1 Cosmetics 744.01 7 0.7
3 2 Grocery 349.13 25 0.3
4 3 Apparels 535.11 88 0.2
5 4 Electronics 524.69 60 0.1
6 5 Electronics 439.1 41 0
7 6 Apparels 56.84 54 0.8
8 7 Electronics 326.66 97 0.7
9 8 Cosmetics 17.25 74 0.6
10 9 Grocery 199.96 39 0.4
11 10 Grocery 731.77 20 0.3

Binary file not shown.

View File

@@ -0,0 +1,13 @@
try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return}
#Get rid of pre-exisiting sheet
$xlSourcefile = "$env:TEMP\ImportExcelExample.xlsx"
Write-Verbose -Verbose -Message "Save location: $xlSourcefile"
Remove-Item $xlSourcefile -ErrorAction Ignore
$PivotTableDefinition = New-PivotTableDefinition -Activate -PivotTableName Points `
-PivotRows Driver -PivotColumns Date -PivotData @{Points = "SUM"} -GroupDateColumn Date -GroupDatePart Years, Months
Import-Csv "$PSScriptRoot\First10Races.csv" |
Select-Object Race, @{n = "Date"; e = {[datetime]::ParseExact($_.date, "dd/MM/yyyy", (Get-Culture))}}, FinishPosition, Driver, GridPosition, Team, Points |
Export-Excel $xlSourcefile -Show -AutoSize -PivotTableDefinition $PivotTableDefinition

View File

@@ -0,0 +1,13 @@
try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return}
#Get rid of pre-exisiting sheet
$xlSourcefile = "$env:TEMP\ImportExcelExample.xlsx"
Write-Verbose -Verbose -Message "Save location: $xlSourcefile"
Remove-Item $xlSourcefile -ErrorAction Ignore
$PivotTableDefinition = New-PivotTableDefinition -Activate -PivotTableName Places `
-PivotRows Driver -PivotColumns FinishPosition -PivotData @{Date = "Count"} -GroupNumericColumn FinishPosition -GroupNumericMin 1 -GroupNumericMax 25 -GroupNumericInterval 3
Import-Csv "$PSScriptRoot\First10Races.csv" |
Select-Object Race, @{n = "Date"; e = {[datetime]::ParseExact($_.date, "dd/MM/yyyy", (Get-Culture))}}, FinishPosition, Driver, GridPosition, Team, Points |
Export-Excel $xlSourcefile -Show -AutoSize -PivotTableDefinition $PivotTableDefinition

View File

@@ -0,0 +1,24 @@
function ConvertTo-Excel {
param(
$Path,
[System.Collections.IDictionary]$targetData
)
$column = 1
foreach ($key in $targetData.Keys) {
$cityData[$key] | Export-Excel $xlfile -StartColumn ($column++) -HeaderName $key -AutoSize
}
}
$cityData = [Ordered]@{}
$cityData.City = "New York City", "Paris", "Barcelona", "Rome"
$cityData.Country = "United States", "France", "Spain", "Italy"
$cityData.Population = 8600000, 2141000, 5515000, 2873000
$xlfile = "$PSScriptRoot/test.xlsx"
Remove-Item $xlfile -ErrorAction SilentlyContinue
ConvertTo-Excel $xlfile $cityData
. $xlfile

View File

@@ -0,0 +1,24 @@
try { Import-Module $PSScriptRoot\..\..\ImportExcel.psd1 } catch { throw ; return }
## This exports only the numbers
# 1..10 | Export-excel $PSScriptRoot\test.xlsx -Show
## This exports the numbers and in A1 the text "MyNum"
# 1..10 | Export-excel $PSScriptRoot\test.xlsx -HeaderName MyNum -Show
$xlfile = "$PSScriptRoot/testMultipleColumns.xlsx"
Remove-Item $xlfile -ErrorAction SilentlyContinue
$Regions = 'West', 'North', 'East ', 'East ', 'West ', 'North', 'South', 'North', 'South'
$States = 'Texas', 'Tennessee', 'Florida', 'Maine', 'Virginia', 'Missouri', 'Kansas', 'North Dakota', 'Delaware'
$Units = 927, 466, 520, 828, 465, 436, 214, 789, 712
$Prices = 923.71, 770.67, 458.68, 661.24, 53.58, 235.67, 992.47, 640.72, 508.55
# Export each list (array) as a separate column to the same worksheet and workbook
$Regions | Export-Excel -Path $xlfile -HeaderName Region -StartColumn 1 -AutoSize
$States | Export-Excel -Path $xlfile -HeaderName State -StartColumn 2 -AutoSize
$Units | Export-Excel -Path $xlfile -HeaderName Units -StartColumn 3 -AutoSize
$Prices | Export-Excel -Path $xlfile -HeaderName Prices -StartColumn 4 -AutoSize
# Show the results in Excel
. $xlfile

View File

@@ -0,0 +1,62 @@
<#
Excel VBA macro which changes all PivotTables in the workbook to Tabular form, disables subtotals and repeats item labels.
https://github.com/dfinke/ImportExcel/issues/1196#issuecomment-1156320581
#>
$ExcelFile = "$ENV:TEMP\test.xlsm"
Remove-Item -Path $ExcelFile -ErrorAction SilentlyContinue
$Macro = @"
Private Sub Workbook_Open()
'
' ChangePivotTables Macro
' Runs when the Excel workbook is opened.
'
' Changes all PivotTables in the workbook to Tabular form, repeats labels
' and disables Subtotals.
'
' Declare variables
Dim Ws As Worksheet
Dim Pt As PivotTable
Dim Pf As PivotField
' Disable screen updates
Application.ScreenUpdating = False
' Continue even if an error occurs
On Error Resume Next
For Each Ws In ActiveWorkbook.Worksheets
For Each Pt In Ws.PivotTables
Pt.RowAxisLayout xlTabularRow
Pt.RepeatAllLabels xlRepeatLabels
For Each Pf In Pt.PivotFields
Pf.Subtotals(1) = False
Next
Next
Next
Application.ScreenUpdating = True
End Sub
"@
$Data = ConvertFrom-Csv -InputObject @"
Region,Item,TotalSold
West,screwdriver,98
West,kiwi,19
North,kiwi,47
West,screws,48
West,avocado,52
East,avocado,40
South,drill,61
North,orange,92
South,drill,29
South,saw,36
"@
$ExcelPackage = $Data | Export-Excel -Path $ExcelFile -TableName "Sales" -WorksheetName "Sales" -AutoSize -PassThru
# Add Macro to the ThisWorkbook module
$ExcelPackage.Workbook.CreateVBAProject()
$VBAThisWorkbookModule = $ExcelPackage.Workbook.VbaProject.Modules | Where-Object -FilterScript { $_.Name -eq "ThisWorkbook" }
$VBAThisWorkbookModule.Code = $Macro
# Create PivotTable example
Add-PivotTable -PivotTableName "SalesPivot" -Address $ExcelPackage.Sales.Cells["E1"] -SourceWorksheet $ExcelPackage.Sales `
-SourceRange $ExcelPackage.Sales.Tables[0].Address -PivotRows "Region", "Item" -PivotData @{ "TotalSold" = "Sum" }
Close-ExcelPackage -ExcelPackage $ExcelPackage -Show

View File

@@ -6,7 +6,7 @@
RootModule = 'ImportExcel.psm1' RootModule = 'ImportExcel.psm1'
# Version number of this module. # Version number of this module.
ModuleVersion = '7.7.0' ModuleVersion = '7.8.2'
# ID used to uniquely identify this module # ID used to uniquely identify this module
GUID = '60dd4136-feff-401a-ba27-a84458c57ede' GUID = '60dd4136-feff-401a-ba27-a84458c57ede'

View File

@@ -118,7 +118,7 @@
Write-Warning -Message "The condition will look for the quotes at the start and end." Write-Warning -Message "The condition will look for the quotes at the start and end."
} }
if ($PSBoundParameters.ContainsKey("ConditionValue" ) -and if ($PSBoundParameters.ContainsKey("ConditionValue" ) -and
$RuleType -match "Top|Botom" ) {$rule.Rank = $ConditionValue } $RuleType -match "Top|Bottom" ) {$rule.Rank = $ConditionValue }
if ($PSBoundParameters.ContainsKey("ConditionValue" ) -and if ($PSBoundParameters.ContainsKey("ConditionValue" ) -and
$RuleType -match "StdDev" ) {$rule.StdDev = $ConditionValue } $RuleType -match "StdDev" ) {$rule.StdDev = $ConditionValue }
if ($PSBoundParameters.ContainsKey("ConditionValue" ) -and if ($PSBoundParameters.ContainsKey("ConditionValue" ) -and

View File

@@ -18,8 +18,10 @@
[String]$PivotTotals = "Both", [String]$PivotTotals = "Both",
[Switch]$NoTotalsInPivot, [Switch]$NoTotalsInPivot,
[String]$GroupDateRow, [String]$GroupDateRow,
[String]$GroupDateColumn,
[OfficeOpenXml.Table.PivotTable.eDateGroupBy[]]$GroupDatePart, [OfficeOpenXml.Table.PivotTable.eDateGroupBy[]]$GroupDatePart,
[String]$GroupNumericRow, [String]$GroupNumericRow,
[String]$GroupNumericColumn,
[double]$GroupNumericMin = 0 , [double]$GroupNumericMin = 0 ,
[double]$GroupNumericMax = [Double]::MaxValue , [double]$GroupNumericMax = [Double]::MaxValue ,
[double]$GroupNumericInterval = 100 , [double]$GroupNumericInterval = 100 ,
@@ -139,11 +141,21 @@
if (-not $r ) {Write-Warning -Message "Could not find a Row field named '$GroupNumericRow'; no numeric grouping will be done."} if (-not $r ) {Write-Warning -Message "Could not find a Row field named '$GroupNumericRow'; no numeric grouping will be done."}
else {$r.AddNumericGrouping($GroupNumericMin, $GroupNumericMax, $GroupNumericInterval)} else {$r.AddNumericGrouping($GroupNumericMin, $GroupNumericMax, $GroupNumericInterval)}
} }
elseif ($GroupNumericColumn) {
$c = $pivotTable.ColumnFields.Where( {$_.name -eq $GroupNumericColumn })
if (-not $c ) {Write-Warning -Message "Could not find a Column field named '$GroupNumericColumn'; no numeric grouping will be done."}
else {$c.AddNumericGrouping($GroupNumericMin, $GroupNumericMax, $GroupNumericInterval)}
}
if ($GroupDateRow -and $PSBoundParameters.ContainsKey("GroupDatePart")) { if ($GroupDateRow -and $PSBoundParameters.ContainsKey("GroupDatePart")) {
$r = $pivotTable.RowFields.Where( {$_.name -eq $GroupDateRow }) $r = $pivotTable.RowFields.Where( {$_.name -eq $GroupDateRow })
if (-not $r ) {Write-Warning -Message "Could not find a Row field named '$GroupDateRow'; no date grouping will be done."} if (-not $r ) {Write-Warning -Message "Could not find a Row field named '$GroupDateRow'; no date grouping will be done."}
else {$r.AddDateGrouping($GroupDatePart)} else {$r.AddDateGrouping($GroupDatePart)}
} }
elseif ($GroupDateColumn -and $PSBoundParameters.ContainsKey("GroupDatePart")) {
$c = $pivotTable.ColumnFields.Where( {$_.name -eq $GroupDateColumn })
if (-not $c ) {Write-Warning -Message "Could not find a Column field named '$GroupDateColumn'; no date grouping will be done."}
else {$c.AddDateGrouping($GroupDatePart)}
}
} }
catch {Write-Warning -Message "Failed adding PivotTable '$pivotTableName': $_"} catch {Write-Warning -Message "Failed adding PivotTable '$pivotTableName': $_"}
} }

View File

@@ -13,6 +13,7 @@
[Switch]$Calculate, [Switch]$Calculate,
[Switch]$Show, [Switch]$Show,
[String]$WorksheetName = 'Sheet1', [String]$WorksheetName = 'Sheet1',
[String]$HeaderName,
[Alias("PW")] [Alias("PW")]
[String]$Password, [String]$Password,
[switch]$ClearSheet, [switch]$ClearSheet,
@@ -258,6 +259,11 @@
try { try {
if ($null -eq $InputObject) { $row += 1 } if ($null -eq $InputObject) { $row += 1 }
foreach ($TargetData in $InputObject) { foreach ($TargetData in $InputObject) {
if ($HeaderName -and $TargetData.psobject.TypeNames[0] -match 'System.String|System.Int32|System.Double|System.Char') {
$TargetData = [PSCustomObject]@{ $HeaderName = $TargetData }
}
if ($firstTimeThru) { if ($firstTimeThru) {
$firstTimeThru = $false $firstTimeThru = $false
$isDataTypeValueType = ($null -eq $TargetData) -or ($TargetData.GetType().name -match 'string|timespan|datetime|bool|byte|char|decimal|double|float|int|long|sbyte|short|uint|ulong|ushort|URI|ExcelHyperLink') $isDataTypeValueType = ($null -eq $TargetData) -or ($TargetData.GetType().name -match 'string|timespan|datetime|bool|byte|char|decimal|double|float|int|long|sbyte|short|uint|ulong|ushort|URI|ExcelHyperLink')

View File

@@ -16,8 +16,10 @@ function New-PivotTableDefinition {
[String]$PivotTotals = "Both", [String]$PivotTotals = "Both",
[Switch]$NoTotalsInPivot, [Switch]$NoTotalsInPivot,
[String]$GroupDateRow, [String]$GroupDateRow,
[String]$GroupDateColumn,
[OfficeOpenXml.Table.PivotTable.eDateGroupBy[]]$GroupDatePart, [OfficeOpenXml.Table.PivotTable.eDateGroupBy[]]$GroupDatePart,
[String]$GroupNumericRow, [String]$GroupNumericRow,
[String]$GroupNumericColumn,
[double]$GroupNumericMin = 0 , [double]$GroupNumericMin = 0 ,
[double]$GroupNumericMax = [Double]::MaxValue , [double]$GroupNumericMax = [Double]::MaxValue ,
[double]$GroupNumericInterval = 100 , [double]$GroupNumericInterval = 100 ,

View File

@@ -14,8 +14,8 @@
Automate Excel with PowerShell without having Excel installed. Works on Windows, Linux and MAC. Creating Tables, Pivot Tables, Charts and much more just got a lot easier. Automate Excel with PowerShell without having Excel installed. Works on Windows, Linux and MAC. Creating Tables, Pivot Tables, Charts and much more just got a lot easier.
## Examples ## Examples
Check out [more than 100 examples](Examples/) on ways to make you more productive. Check out the [more than 100 examples](Examples/) on ways to create amazing reports as well as make you more productive with PowerShell and Excel.
# Basic Usage # Basic Usage
## Installation ## Installation

View File

@@ -65,6 +65,11 @@ Plus, wiring the [PowerShell ScriptAnalyzer Excel report](https://github.com/dfi
![](.gitbook/assets/ScriptAnalyzerReport.png) ![](.gitbook/assets/ScriptAnalyzerReport.png)
## What's new for 7.1.4
- Added GroupNumericColumn and GroupDateColumn to New-PivotTableDefinition and Add-PivotTable.
## What's new 7.1.3 ## What's new 7.1.3
- Changed to `ProviderPath`. Thanks [Trevor Walker](https://github.com/sporkabob) - Changed to `ProviderPath`. Thanks [Trevor Walker](https://github.com/sporkabob)

View File

@@ -140,4 +140,72 @@ Describe "Creating small named ranges with hyperlinks" {
$pt.RowFields[1].Grouping.Interval | Should -Be 3 $pt.RowFields[1].Grouping.Interval | Should -Be 3
} }
} }
Context "Adding group date column" -Tag GroupColumnTests {
it "Tests adding a group date column" {
$xlFile = "TestDrive:\Results.xlsx"
Remove-Item $xlFile -ErrorAction Ignore
$PivotTableDefinition = New-PivotTableDefinition -Activate -PivotTableName Points `
-PivotRows Driver -PivotColumns Date -PivotData @{Points = "SUM" } -GroupDateColumn Date -GroupDatePart Years, Months
$excel = Import-Csv "$PSScriptRoot\First10Races.csv" |
Select-Object Race, @{n = "Date"; e = { [datetime]::ParseExact($_.date, "dd/MM/yyyy", (Get-Culture)) } }, FinishPosition, Driver, GridPosition, Team, Points |
Export-Excel $xlFile -AutoSize -PivotTableDefinition $PivotTableDefinition -PassThru
$excel.Workbook.Worksheets.Count | Should -Be 2
$excel.Workbook.Worksheets[1].Name | Should -BeExactly 'Sheet1'
$excel.Workbook.Worksheets[2].Name | Should -BeExactly 'Points'
$excel.Points.PivotTables.Count | Should -Be 1
$pt = $excel.Points.PivotTables[0]
$pt.RowFields.Count | Should -Be 1
$pt.RowFields[0].name | Should -Be "Driver"
$pt.ColumnFields.Count | Should -Be 2
$pt.ColumnFields[0].name | Should -Be "Years"
$pt.ColumnFields[0].Grouping | Should -Not -BeNullOrEmpty
$pt.ColumnFields[0].Grouping.GroupBy | Should -Be "Years"
$pt.ColumnFields[1].name | Should -Be "Date"
$pt.ColumnFields[1].Grouping | Should -Not -BeNullOrEmpty
$pt.ColumnFields[1].Grouping.GroupBy | Should -Be "Months"
Close-ExcelPackage $excel
Remove-Item $xlFile -ErrorAction Ignore
}
}
Context "Adding group numeric column" -Tag GroupColumnTests {
it "Tests adding numeric group column" {
$xlFile = "TestDrive:\Results.xlsx"
Remove-Item $xlFile -ErrorAction Ignore
$PivotTableDefinition = New-PivotTableDefinition -Activate -PivotTableName Places `
-PivotRows Driver -PivotColumns FinishPosition -PivotData @{Date = "Count" } -GroupNumericColumn FinishPosition -GroupNumericMin 1 -GroupNumericMax 25 -GroupNumericInterval 3
$excel = Import-Csv "$PSScriptRoot\First10Races.csv" |
Select-Object Race, @{n = "Date"; e = { [datetime]::ParseExact($_.date, "dd/MM/yyyy", (Get-Culture)) } }, FinishPosition, Driver, GridPosition, Team, Points |
Export-Excel $xlFile -AutoSize -PivotTableDefinition $PivotTableDefinition -PassThru
$excel.Workbook.Worksheets.Count | Should -Be 2
$excel.Workbook.Worksheets[1].Name | Should -BeExactly 'Sheet1'
$excel.Workbook.Worksheets[2].Name | Should -BeExactly 'Places'
$excel.Places.PivotTables.Count | Should -Be 1
$pt = $excel.Places.PivotTables[0]
$pt.RowFields.Count | Should -Be 1
$pt.RowFields[0].name | Should -Be "Driver"
$pt.ColumnFields.Count | Should -Be 1
$pt.ColumnFields[0].name | Should -Be "FinishPosition"
$pt.ColumnFields[0].Grouping | Should -Not -BeNullOrEmpty
$pt.ColumnFields[0].Grouping.Start | Should -Be 1
$pt.ColumnFields[0].Grouping.End | Should -Be 25
$pt.ColumnFields[0].Grouping.Interval | Should -Be 3
Close-ExcelPackage $excel
Remove-Item $xlFile -ErrorAction Ignore
}
}
} }

View File

@@ -0,0 +1,88 @@
if (-not (Get-command Import-Excel -ErrorAction SilentlyContinue)) {
Import-Module $PSScriptRoot\..\ImportExcel.psd1
}
Describe "Test HeaderName parameter" -Tag HeaderName {
It "Should add data as usual" {
$xlfile = "TestDrive:\headername.xlsx"
Remove-Item $xlfile -ErrorAction SilentlyContinue
1..10 | Export-Excel -Path $xlfile
{ Test-Path $xlfile } | Should -BeTrue
$excel = Open-ExcelPackage $xlfile
1..10 | ForEach-Object {
$excel.Sheet1.Cells[$_, 1].Text | Should -BeExactly $_
}
Close-ExcelPackage $excel
Remove-Item $xlfile -ErrorAction SilentlyContinue
}
It "Should add data and the first cell should have the header name" {
$xlfile = "TestDrive:\headername.xlsx"
Remove-Item $xlfile -ErrorAction SilentlyContinue
1..10 | Export-Excel -Path $xlfile -HeaderName MyNum
{ Test-Path $xlfile } | Should -BeTrue
$excel = Open-ExcelPackage $xlfile
$excel.Sheet1.Cells[1, 1].Text | Should -BeExactly "MyNum"
1..10 | ForEach-Object {
$excel.Sheet1.Cells[($_ + 1), 1].Text | Should -BeExactly $_
}
Close-ExcelPackage $excel
Remove-Item $xlfile -ErrorAction SilentlyContinue
}
It "Should ignore the header name" {
$data = ConvertFrom-Csv @"
Region,State,Units,Price
West,Texas,927,923.71
North,Tennessee,466,770.67
East,Florida,520,458.68
East,Maine,828,661.24
West,Virginia,465,053.58
North,Missouri,436,235.67
South,Kansas,214,992.47
North,North Dakota,789,640.72
South,Delaware,712,508.55
"@
$xlfile = "TestDrive:\headername.xlsx"
Remove-Item $xlfile -ErrorAction SilentlyContinue
$data | Export-Excel -Path $xlfile -HeaderName MyNum
{ Test-Path $xlfile } | Should -BeTrue
$excel = Open-ExcelPackage $xlfile
$excel.Sheet1.Cells[1, 1].Text | Should -BeExactly "Region"
$excel.Sheet1.Cells[1, 2].Text | Should -BeExactly "State"
$excel.Sheet1.Cells[1, 3].Text | Should -BeExactly "Units"
$excel.Sheet1.Cells[1, 4].Text | Should -BeExactly "Price"
$excel.Sheet1.Cells[2, 1].Text | Should -BeExactly "West"
$excel.Sheet1.Cells[2, 2].Text | Should -BeExactly "Texas"
$excel.Sheet1.Cells[2, 3].Text | Should -Be 927
$excel.Sheet1.Cells[2, 4].Text | Should -Be 923.71
$excel.Sheet1.Cells[10, 1].Text | Should -BeExactly "South"
$excel.Sheet1.Cells[10, 2].Text | Should -BeExactly "Delaware"
$excel.Sheet1.Cells[10, 3].Text | Should -Be 712
$excel.Sheet1.Cells[10, 4].Text | Should -Be 508.55
Close-ExcelPackage $excel
Remove-Item $xlfile -ErrorAction SilentlyContinue
}
}

View File

@@ -1,13 +1,45 @@
# 7.7.0 # 7.8.2
- Fix a bug with `-UnderLineType parameter is ignored in Set-ExcelColumn` [#1204](https://github.com/dfinke/ImportExcel/issues/1204) - Added `HeaderName` parameter to `Export-Excel`. Allows you to output an object with a property name. Otherwise the data is just the array of values.
```powershell
1..10 | Export-Excel -Path .\test.xlsx -HeaderName MyNum
```
- Added example `CopyFromOneSheetInSameWorkbook`. Shows how to copy a range of data from WorksheetA to WorksheetB
- Added example `HeaderName`. Shows how to use the new `-HeaderName` parameter
- Added example `HeaderName`. Shows how to use the new `-HeaderName` parameter
- Added example `ConvertDictionaryOfArraysToExcel` example. Takes a dictionary of arrays and converts it Rows and Columns of data in Excel.
# 7.8.1
- Fixed conditional formatting so it recognizes 'Top and Bottom' as a rule type. Thanks [g-pearl](https://github.com/g-pearl)
* Update open-excelpackage.md. Thanks [stahler](https://github.com/stahler)
- Added Group Column tests
# 7.8.0
Thanks [James O'Neill](https://github.com/jhoneill)
- Updated example Get-ModuleStats that extracts module statistics on the PowerShell Gallery.
- Added GroupNumericColumn and GroupDateColumn to New-PivotTableDefinition and Add-PivotTable.
|GroupNumericColumn|GroupDateColumn|
|:---:|:---:|
|![](images/GroupNumericColumn.png)|![](images/GroupDateColumn.png)|
# Example added # Example added
Thank you [@kkazala](https://github.com/kkazala) Thank you [@kkazala](https://github.com/kkazala)
- Added an example reading a sheet, extracting the `ConditionalFormatting` and generating the PowerShell statements so you can re-create them.
- Added an example showing `ConditionalFormatting` using the `RuleType` `Expression` with a formula - Added an example showing `ConditionalFormatting` using the `RuleType` `Expression` with a formula
- [Highlight-DiffCells.ps1](https://github.dev/kkazala/ImportExcel/blob/b53881fd023c052da1acc7812511da223bb2e40c/Examples/ConditionalFormatting/Highlight-DiffCells.ps1) - [Highlight-DiffCells.ps1](https://github.dev/kkazala/ImportExcel/blob/b53881fd023c052da1acc7812511da223bb2e40c/Examples/ConditionalFormatting/Highlight-DiffCells.ps1)
# 7.7.0
- Fix a bug with `-UnderLineType parameter is ignored in Set-ExcelColumn` [#1204](https://github.com/dfinke/ImportExcel/issues/1204)
# 7.6.0 # 7.6.0
- **_[Under investigation]_** Fix -StartRow and -StartColumn being ignored. - **_[Under investigation]_** Fix -StartRow and -StartColumn being ignored.

BIN
images/GroupDateColumn.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

View File

@@ -331,6 +331,22 @@ Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -GroupDateColumn
The name of a Column field which should be grouped by parts of the date/time \(ignored if GroupDateRow is not specified\)
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -GroupDatePart ### -GroupDatePart
The Part\(s\) of the date to use in the grouping \(ignored if GroupDateRow is not specified\) The Part\(s\) of the date to use in the grouping \(ignored if GroupDateRow is not specified\)
@@ -364,6 +380,22 @@ Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -GroupNumericColumn
The name of a Column field which should be grouped by Number \(e.g. 0-99, 100-199, 200-299 \)
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -GroupNumericMin ### -GroupNumericMin
The starting point for grouping The starting point for grouping

View File

@@ -225,6 +225,22 @@ Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -GroupDateColumn
The name of a column field which should be grouped by parts of the date/time \(ignored if GroupDatePart is not specified\)
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -GroupDatePart ### -GroupDatePart
The Part\(s\) of the date to use in the grouping \(ignored if GroupDateRow is not specified\) The Part\(s\) of the date to use in the grouping \(ignored if GroupDateRow is not specified\)
@@ -234,7 +250,6 @@ Type: eDateGroupBy[]
Parameter Sets: (All) Parameter Sets: (All)
Aliases: Aliases:
Accepted values: Years, Quarters, Months, Days, Hours, Minutes, Seconds Accepted values: Years, Quarters, Months, Days, Hours, Minutes, Seconds
Required: False Required: False
Position: Named Position: Named
Default value: None Default value: None
@@ -250,7 +265,6 @@ The name of a row field which should be grouped by Number \(e.g 0-99, 100-199, 2
Type: String Type: String
Parameter Sets: (All) Parameter Sets: (All)
Aliases: Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: None Default value: None
@@ -258,6 +272,23 @@ Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -GroupNumericColumn
The name of a column field which should be grouped by Number \(e.g 0-99, 100-199, 200-299 \)
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -GroupNumericMin ### -GroupNumericMin
The starting point for grouping The starting point for grouping

View File

@@ -39,13 +39,13 @@ This will create a new file in the temp folder if it doesn't already exist. It t
### EXAMPLE 2 ### EXAMPLE 2
```text ```text
PS\> $excela= Open-ExcelPackage -path "$xlPath" -Password $password PS\> $excel= Open-ExcelPackage -path "$xlPath" -Password $password
PS\> $sheet1 = $excel.Workbook.Worksheetsa"sheet1" ] PS\> $sheet1 = $excel.Workbook.Worksheets["sheet1"]
PS\> Set-ExcelRange -Range $sheet1.Cells ["E1:S1048576" ], $sheet1.Cells ["V1:V1048576" ] -NFormat ( [cultureinfo ]::CurrentCulture.DateTimeFormat.ShortDatePattern) PS\> Set-ExcelRange -Range $sheet1.Cells ["E1:S1048576" ], $sheet1.Cells ["V1:V1048576" ] -NFormat ( [cultureinfo ]::CurrentCulture.DateTimeFormat.ShortDatePattern)
PS\> Close-ExcelPackage $excel -Show PS\> Close-ExcelPackage $excel -Show
``` ```
This will open the password protected file at $xlPath using the password stored in $Password. Sheet1 is selected and formatting applied to two blocks of the sheet; then the file is and saved and loaded into Excel. This will open the password protected file at $xlPath using the password stored in $Password. Sheet1 is selected and formatting applied to two blocks of the sheet; then the file is saved and loaded into Excel.
## PARAMETERS ## PARAMETERS