From 6f482198192a494579fc7e8af9a3ad8e7cc80404 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sun, 22 Dec 2019 14:52:06 +0000 Subject: [PATCH 01/12] assume IncludePivot when implied by other params --- Public/Export-Excel.ps1 | 5 +++-- Public/New-PivotTableDefinition.ps1 | 3 +++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/Public/Export-Excel.ps1 b/Public/Export-Excel.ps1 index 09fc486..b1653ae 100644 --- a/Public/Export-Excel.ps1 +++ b/Public/Export-Excel.ps1 @@ -442,7 +442,7 @@ Add-PivotTable -ExcelPackage $pkg -PivotTableName $item.key @Params } } - if ($IncludePivotTable -or $IncludePivotChart) { + if ($IncludePivotTable -or $IncludePivotChart -or $PivotData) { $params = @{ 'SourceRange' = $dataRange } @@ -461,7 +461,8 @@ if ($NoTotalsInPivot) {$params.PivotTotals = "None" } Elseif ($PivotTotals) {$params.PivotTotals = $PivotTotals} if ($PivotDataToColumn) {$params.PivotDataToColumn = $true} - if ($IncludePivotChart) { + if ($IncludePivotChart -or + $PSBoundParameters.ContainsKey('ChartType')) { $params.IncludePivotChart = $true $Params.ChartType = $ChartType if ($ShowCategory) {$params.ShowCategory = $true} diff --git a/Public/New-PivotTableDefinition.ps1 b/Public/New-PivotTableDefinition.ps1 index ce813c7..6916bc5 100644 --- a/Public/New-PivotTableDefinition.ps1 +++ b/Public/New-PivotTableDefinition.ps1 @@ -62,6 +62,9 @@ function New-PivotTableDefinition { $parameters.Remove('NoTotalsInPivot') $parameters["PivotTotals"] = "None" } + if ($PSBoundParameters.ContainsKey('ChartType') -and -not $PSBoundParameters.ContainsKey('IncludePivotChart')) { + $parameters['IncludePivotChart'] = $true + } $parameters.Remove('PivotTableName') if ($PivotChartDefinition) { $parameters.PivotChartDefinition.XRange = $null From 118330ea479532c87a05dff6448da00019a88a75 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sun, 22 Dec 2019 16:39:38 +0000 Subject: [PATCH 02/12] Make primary name "PivotTableChartType" (with alias chartType) in Export-Excel --- Public/Export-Excel.ps1 | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Public/Export-Excel.ps1 b/Public/Export-Excel.ps1 index b1653ae..5900aac 100644 --- a/Public/Export-Excel.ps1 +++ b/Public/Export-Excel.ps1 @@ -22,6 +22,7 @@ [Switch]$TitleBold, [Int]$TitleSize = 22, $TitleBackgroundColor, + [parameter(DontShow=$true)] [Switch]$IncludePivotTable, [String]$PivotTableName, [String[]]$PivotRows, @@ -31,7 +32,8 @@ [Switch]$PivotDataToColumn, [Hashtable]$PivotTableDefinition, [Switch]$IncludePivotChart, - [OfficeOpenXml.Drawing.Chart.eChartType]$ChartType = 'Pie', + [Alias('ChartType')] + [OfficeOpenXml.Drawing.Chart.eChartType]$PivotChartType = 'Pie', [Switch]$NoLegend, [Switch]$ShowCategory, [Switch]$ShowPercent, @@ -462,9 +464,9 @@ Elseif ($PivotTotals) {$params.PivotTotals = $PivotTotals} if ($PivotDataToColumn) {$params.PivotDataToColumn = $true} if ($IncludePivotChart -or - $PSBoundParameters.ContainsKey('ChartType')) { + $PSBoundParameters.ContainsKey('PivotChartType')) { $params.IncludePivotChart = $true - $Params.ChartType = $ChartType + $Params.ChartType = $PivotChartType if ($ShowCategory) {$params.ShowCategory = $true} if ($ShowPercent) {$params.ShowPercent = $true} if ($NoLegend) {$params.NoLegend = $true} From 97611fc57c9438632f66b48229b0157f44859a7c Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sun, 22 Dec 2019 17:53:05 +0000 Subject: [PATCH 03/12] Add -AsDate support to import-Excel and ConvertFrom-Excel sheet. Help upate --- Public/ConvertFrom-ExcelSheet.md | 140 ------- Public/ConvertFrom-ExcelSheet.ps1 | 7 +- Public/Import-Excel.ps1 | 25 +- __tests__/ConvertFrom-ExcelSheet.Tests.ps1 | 15 +- en/ImportExcel-help.xml | 424 +++++++++++++++++++++ mdHelp/buildHelp.ps1 | 4 + mdHelp/en/ConvertFrom-ExcelSheet.md | 15 + mdHelp/en/Import-Excel.md | 15 + 8 files changed, 492 insertions(+), 153 deletions(-) delete mode 100644 Public/ConvertFrom-ExcelSheet.md create mode 100644 mdHelp/buildHelp.ps1 diff --git a/Public/ConvertFrom-ExcelSheet.md b/Public/ConvertFrom-ExcelSheet.md deleted file mode 100644 index b91972c..0000000 --- a/Public/ConvertFrom-ExcelSheet.md +++ /dev/null @@ -1,140 +0,0 @@ ---- -external help file: ImportExcel-help.xml -Module Name: ImportExcel -online version: -schema: 2.0.0 ---- - -# ConvertFrom-ExcelSheet - -## SYNOPSIS -Reads an Excel file an converts the data to a delimited text file. - -## SYNTAX - -``` -ConvertFrom-ExcelSheet [-Path] [[-OutputPath] ] [[-SheetName] ] [[-Encoding] ] - [[-Extension] ] [[-Delimiter] ] [] -``` - -## DESCRIPTION -{{ Fill in the Description }} - -## EXAMPLES - -### EXAMPLE 1 -``` -ConvertFrom-ExcelSheet .\TestSheets.xlsx .\data -``` - -Reads each sheet in TestSheets.xlsx and outputs it to the data directory as the sheet name with the extension .txt. - -### EXAMPLE 2 -``` -ConvertFrom-ExcelSheet .\TestSheets.xlsx .\data sheet?0 -``` - -Reads and outputs sheets like Sheet10 and Sheet20 form TestSheets.xlsx and outputs it to the data directory as the sheet name with the extension .txt. - -## PARAMETERS - -### -Path -{{ Fill Path Description }} - -```yaml -Type: String -Parameter Sets: (All) -Aliases: FullName - -Required: True -Position: 1 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -OutputPath -{{ Fill OutputPath Description }} - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 2 -Default value: .\ -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -SheetName -{{ Fill SheetName Description }} - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 3 -Default value: * -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Encoding -{{ Fill Encoding Description }} - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 4 -Default value: UTF8 -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Extension -{{ Fill Extension Description }} - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 5 -Default value: .csv -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Delimiter -{{ Fill Delimiter Description }} - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 6 -Default value: ; -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -## OUTPUTS - -## NOTES - -## RELATED LINKS diff --git a/Public/ConvertFrom-ExcelSheet.ps1 b/Public/ConvertFrom-ExcelSheet.ps1 index db054f4..95a46df 100644 --- a/Public/ConvertFrom-ExcelSheet.ps1 +++ b/Public/ConvertFrom-ExcelSheet.ps1 @@ -15,7 +15,8 @@ function ConvertFrom-ExcelSheet { $Property = "*", $ExcludeProperty = @(), [switch]$Append, - [string[]]$AsText = @() + [string[]]$AsText = @(), + [string[]]$AsDate = @() ) $Path = (Resolve-Path $Path).Path @@ -25,7 +26,7 @@ function ConvertFrom-ExcelSheet { $targetSheets = $workbook.Worksheets | Where-Object {$_.Name -Like $SheetName} $csvParams = @{NoTypeInformation = $true} + $PSBoundParameters - foreach ($p in 'OutputPath', 'SheetName', 'Extension', 'Property','ExcludeProperty', 'AsText') { + foreach ($p in 'OutputPath', 'SheetName', 'Extension', 'Property','ExcludeProperty', 'AsText','AsDate') { $csvParams.Remove($p) } @@ -34,7 +35,7 @@ function ConvertFrom-ExcelSheet { $csvParams.Path = "$OutputPath\$($Sheet.Name)$Extension" - Import-Excel -ExcelPackage $xl -Sheet $($sheet.Name) -AsText:$AsText | + Import-Excel -ExcelPackage $xl -Sheet $($sheet.Name) -AsText:$AsText -AsDate:$AsDate | Select-Object -Property $Property | Export-Csv @csvparams } diff --git a/Public/Import-Excel.ps1 b/Public/Import-Excel.ps1 index 11a856b..0afc8db 100644 --- a/Public/Import-Excel.ps1 +++ b/Public/Import-Excel.ps1 @@ -33,6 +33,7 @@ [Int]$EndColumn , [Switch]$DataOnly, [string[]]$AsText, + [string[]]$AsDate, [ValidateNotNullOrEmpty()] [String]$Password ) @@ -160,25 +161,39 @@ } else { #region Create one object per row - if ($AsText) { + if ($AsText -or $AsDate) { <#join items in AsText together with ~~~ . Escape any regex special characters... # which turns "*" into "\*" make it ".*". Convert ~~~ to $|^ and top and tail with ^%; So if we get "Week", "[Time]" and "*date*" ; make the expression ^week$|^\[Time\]$|^.*Date.*$ $make a regex for this which is case insensitive (option 1) and compiled (option 8) #> - $TextColExpression = "^" + [regex]::Escape($AsText -join "~~~").replace("\*", ".*").replace("~~~", "$|^") + "$" + $TextColExpression = '' + if ($AsText) { + $TextColExpression += '(?^' + [regex]::Escape($AsText -join '~~~').replace('\*', '.*').replace('~~~', '$|^') + '$)' + } + if ($AsText -and $AsDate) { + $TextColExpression += "|" + } + if ($AsDate) { + $TextColExpression += '(?^' + [regex]::Escape($AsDate -join '~~~').replace('\*', '.*').replace('~~~', '$|^') + '$)' + } $TextColRegEx = New-Object -TypeName regex -ArgumentList $TextColExpression , 9 } + else {$TextColRegEx = $null} foreach ($R in $Rows) { #Disabled write-verbose for speed # Write-Verbose "Import row '$R'" $NewRow = [Ordered]@{ } if ($TextColRegEx) { foreach ($P in $PropertyNames) { - if ($TextColRegEx.IsMatch($P.Value)) { - $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Text + $MatchTest = $TextColRegEx.Match($P.value) + if ($MatchTest.groups.name -eq "astext") { + $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Text } - else { $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Value } + elseif ($MatchTest.groups.name -eq "asdate" -and $Worksheet.Cells[$R, $P.Column].Value -is [System.ValueType]) { + $NewRow[$P.Value] = [datetime]::FromOADate(($Worksheet.Cells[$R, $P.Column].Value)) + } + else { $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Value } } } else { diff --git a/__tests__/ConvertFrom-ExcelSheet.Tests.ps1 b/__tests__/ConvertFrom-ExcelSheet.Tests.ps1 index 5065a33..dfc5498 100644 --- a/__tests__/ConvertFrom-ExcelSheet.Tests.ps1 +++ b/__tests__/ConvertFrom-ExcelSheet.Tests.ps1 @@ -12,25 +12,30 @@ Describe 'ConvertFrom-ExcelSheet / Export-ExcelSheet' { ConvertFrom-ExcelSheet -Path $dataPath -OutputPath $Outpath -AsText "GridPosition" -Property driver, @{n="date"; e={[datetime]::FromOADate($_.Date).tostring("#MM/dd/yyyy#")}} , FinishPosition, GridPosition $ThirdText = Get-Content (Join-path -Path $Outpath -ChildPath "First10Races.csv") + ConvertFrom-ExcelSheet -Path $dataPath -OutputPath $Outpath -AsDate "date" + $FourthText = Get-Content (Join-path -Path $Outpath -ChildPath "First10Races.csv") } Context "Exporting to CSV" { it "Exported the expected columns to a CSV file " { $firstText[0] | should be '"Race","Date","FinishPosition","Driver","GridPosition","Team","Points"' $SecondText[0] | should be '"Race","Date","FinishPosition","Driver","GridPosition","Team","Points"' $ThirdText[0] | should be '"Driver","date","FinishPosition","GridPosition"' + $FourthText[0] | should be '"Race","Date","FinishPosition","Driver","GridPosition","Team","Points"' } - it "Applied ASText and Properties correctly " { + it "Applied AsText, AsDate and Properties correctly " { $firstText[1] | should match '^"\w+","\d{5}","\d{1,2}","\w+ \w+","[1-9]\d?","\w+","\d{1,2}"$' $date = $firstText[1] -replace '^.*(\d{5}).*$', '$1' $date = [datetime]::FromOADate($date).toString("D") - $secondText[1] | should belike "*$date*" - $secondText[1] | should match '"0\d","\w+","\d{1,2}"$' - $ThirdText[1] | should match '^"\w+ \w+","#\d\d/\d\d/\d{4}#","\d","0\d"$' + $secondText[1] | should belike "*$date*" + $secondText[1] | should match '"0\d","\w+","\d{1,2}"$' + $ThirdText[1] | should match '^"\w+ \w+","#\d\d/\d\d/\d{4}#","\d","0\d"$' + $FourthText[1] | should match '^"\w+","[012]\d' } } Context "Export aliased to ConvertFrom" { - it "Applied ASText and Properties correctly " { + it "Definded the alias name with " { (Get-Alias Export-ExcelSheet).source | should be "ImportExcel" + (Get-Alias Export-ExcelSheet).Definition | should be "ConvertFrom-ExcelSheet" } } } \ No newline at end of file diff --git a/en/ImportExcel-help.xml b/en/ImportExcel-help.xml index a7eb2b6..a738fe4 100644 --- a/en/ImportExcel-help.xml +++ b/en/ImportExcel-help.xml @@ -6576,6 +6576,346 @@ Boston,2/18/2018,1000 + + + ConvertFrom-ExcelSheet + ConvertFrom + ExcelSheet + + Exports Sheets from Excel Workbooks to CSV files. + + + + This command provides a convenient way to run Import-Excel @ImportParameters | Select-Object @selectParameters | export-Csv @ ExportParameters It can take the parameters -AsText , as used in Import-Excel, )Properties & -ExcludeProperties as used in Select-Object and -Append, -Delimiter and -Encoding as used in Export-CSV + + + + ConvertFrom-ExcelSheet + + Path + + The path to the .XLSX file which will be exported. + + String + + String + + + None + + + OutputPath + + The directory where the output file(s) will be created. The file name(s) will match the name of the workbook page which contained the data. + + String + + String + + + None + + + SheetName + + The name of a sheet to export, or a regular expression which is used to identify sheets + + String + + String + + + None + + + Encoding + + Sets the text encoding for the output data file; UTF8 bu default + + Encoding + + Encoding + + + None + + + Extension + + Sets the file extension for the exported data, defaults to CSV + + + .txt + .log + .csv + + String + + String + + + None + + + Delimiter + + Selects , or ; as the delimeter for the exported data - if not specified , is used by default. + + + ; + + + + String + + String + + + None + + + Property + + Specifies the properties to select. Wildcards are permitted - the default is "*". The value of the Property parameter can be a new calculated property, and follows the same pattern as Select-Item + + Object + + Object + + + None + + + ExcludeProperty + + Specifies the properties that to exclude from the export. Wildcards are permitted. This parameter is effective only when the command also includes the Property parameter. + + Object + + Object + + + None + + + AsText + + AsText allows selected columns to be returned as the text displayed in their cells, instead of their value. (* is supported as a wildcard.) + + String[] + + String[] + + + None + + + AsDate + + Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.) + + String[] + + String[] + + + None + + + Append + + Use this parameter to have the export add output to the end of the file. Without this parameter, the command replaces the file contents without warning. + + + SwitchParameter + + + False + + + + + + Append + + Use this parameter to have the export add output to the end of the file. Without this parameter, the command replaces the file contents without warning. + + SwitchParameter + + SwitchParameter + + + False + + + AsText + + AsText allows selected columns to be returned as the text displayed in their cells, instead of their value. (* is supported as a wildcard.) + + String[] + + String[] + + + None + + + AsDate + + Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.) + + String[] + + String[] + + + None + + + Delimiter + + Selects , or ; as the delimeter for the exported data - if not specified , is used by default. + + String + + String + + + None + + + Encoding + + Sets the text encoding for the output data file; UTF8 bu default + + Encoding + + Encoding + + + None + + + ExcludeProperty + + Specifies the properties that to exclude from the export. Wildcards are permitted. This parameter is effective only when the command also includes the Property parameter. + + Object + + Object + + + None + + + Extension + + Sets the file extension for the exported data, defaults to CSV + + String + + String + + + None + + + OutputPath + + The directory where the output file(s) will be created. The file name(s) will match the name of the workbook page which contained the data. + + String + + String + + + None + + + Path + + The path to the .XLSX file which will be exported. + + String + + String + + + None + + + Property + + Specifies the properties to select. Wildcards are permitted - the default is "*". The value of the Property parameter can be a new calculated property, and follows the same pattern as Select-Item + + Object + + Object + + + None + + + SheetName + + The name of a sheet to export, or a regular expression which is used to identify sheets + + String + + String + + + None + + + + + + None + + + + + + + + + + System.Object + + + + + + + + + + + + + + -------------------------- Example 1 -------------------------- + PS C:\> ConvertFrom-ExcelSheet Path .\__tests__\First10Races.xlsx -OutputPath .. -AsText GridPosition,date + + First10Races.xlsx contains information about Motor races. The race date and grid (starting) position are stored with custom formats. The command specifies the path to the file, and the directory to create the output file, and specifies that the columns "GridPosition" and "Date" should be treated as text to preserve their formatting + + + + -------------------------- Example 2 -------------------------- + PS C:\> ConvertFrom-ExcelSheet Path .\__tests__\First10Races.xlsx -OutputPath .. -AsText "GridPosition" -Property driver, @{n="date"; e={[datetime]::FromOADate($_.Date).tostring("#MM/dd/yyyy#")}} , FinishPosition, GridPosition + + This uses the same file as example 1. Because the race date has a custom format, it imports as a number, The requirement is to create a CSV file with the Driver, a specially formatted Date, FinishPostion and GridPostion (keeping its custom formatting). The command specifies the path to the file, and the directory to create the output file, specifies that the column "GridPosition" should be treated as text instead of a number, and the output properties should be Driver, a calculated "date" field, FinishPosition and GridPsition. FromOADate converts the dates used by Excel (Days since Jan 1 1900) to a datetime object. + + + + + + Online Version: + https://github.com/dfinke/ImportExcel + + + ConvertFrom-ExcelToSQLInsert @@ -10499,6 +10839,18 @@ PS\> Export-Excel -ExcelPackage $excel -WorksheetName "Processes" -IncludePiv None + + AsDate + + Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.) + + String[] + + String[] + + + None + Password @@ -10624,6 +10976,18 @@ PS\> Export-Excel -ExcelPackage $excel -WorksheetName "Processes" -IncludePiv None + + AsDate + + Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.) + + String[] + + String[] + + + None + Password @@ -10735,6 +11099,18 @@ PS\> Export-Excel -ExcelPackage $excel -WorksheetName "Processes" -IncludePiv None + + AsDate + + Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.) + + String[] + + String[] + + + None + Password @@ -10859,6 +11235,18 @@ PS\> Export-Excel -ExcelPackage $excel -WorksheetName "Processes" -IncludePiv None + + AsDate + + Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.) + + String[] + + String[] + + + None + Password @@ -10985,6 +11373,18 @@ PS\> Export-Excel -ExcelPackage $excel -WorksheetName "Processes" -IncludePiv None + + AsDate + + Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.) + + String[] + + String[] + + + None + Password @@ -11097,6 +11497,18 @@ PS\> Export-Excel -ExcelPackage $excel -WorksheetName "Processes" -IncludePiv None + + AsDate + + Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.) + + String[] + + String[] + + + None + Password @@ -11249,6 +11661,18 @@ PS\> Export-Excel -ExcelPackage $excel -WorksheetName "Processes" -IncludePiv None + + AsDate + + Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.) + + String[] + + String[] + + + None + Password diff --git a/mdHelp/buildHelp.ps1 b/mdHelp/buildHelp.ps1 new file mode 100644 index 0000000..55abfbb --- /dev/null +++ b/mdHelp/buildHelp.ps1 @@ -0,0 +1,4 @@ +Import-Module platyPS +Get-ChildItem $PSScriptRoot -Directory | ForEach-Object { + New-ExternalHelp -Path $_.FullName -OutputPath (Join-Path $PSScriptRoot "..\$($_.Name)") -Force -Verbose +} \ No newline at end of file diff --git a/mdHelp/en/ConvertFrom-ExcelSheet.md b/mdHelp/en/ConvertFrom-ExcelSheet.md index ed25289..c0c2b8a 100644 --- a/mdHelp/en/ConvertFrom-ExcelSheet.md +++ b/mdHelp/en/ConvertFrom-ExcelSheet.md @@ -76,6 +76,21 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -AsDate +Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.) + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 8 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -Delimiter Selects , or ; as the delimeter for the exported data - if not specified , is used by default. diff --git a/mdHelp/en/Import-Excel.md b/mdHelp/en/Import-Excel.md index 159f13d..18e64b1 100644 --- a/mdHelp/en/Import-Excel.md +++ b/mdHelp/en/Import-Excel.md @@ -395,6 +395,21 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -AsDate +Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.) + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -Password Accepts a string that will be used to open a password protected Excel file. From 08fbfc35a3247ed5e4ba79ed77b7505b776a4074 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sat, 28 Dec 2019 21:16:01 +0000 Subject: [PATCH 04/12] Add Pester example. Make Hide and Hidden aliases --- Examples/Pester-To-XLSx.ps1 | 133 ++++++++++++++++++++++++++++++++++++ Public/New-ExcelStyle.ps1 | 1 + Public/Set-ExcelColumn.ps1 | 1 + Public/Set-ExcelRange.ps1 | 1 + Public/Set-ExcelRow.ps1 | 1 + 5 files changed, 137 insertions(+) create mode 100644 Examples/Pester-To-XLSx.ps1 diff --git a/Examples/Pester-To-XLSx.ps1 b/Examples/Pester-To-XLSx.ps1 new file mode 100644 index 0000000..c4ec038 --- /dev/null +++ b/Examples/Pester-To-XLSx.ps1 @@ -0,0 +1,133 @@ + + +[CmdletBinding(DefaultParameterSetName = 'Default')] +param( + [Parameter(Position=0)] + [string]$XLFile, + + [Parameter(ParameterSetName='Default',Position=1)] + [Alias('Path', 'relative_path')] + [object[]]$Script = '.', + + [Parameter(ParameterSetName='Existing',Mandatory=$true)] + [switch] + $UseExisting, + + [Parameter(ParameterSetName='Default', Position=2)] + [Parameter(ParameterSetName='Existing',Position=2, Mandatory=$true)] + [string]$OutputFile, + + [Parameter(ParameterSetName='Default')] + [Alias("Name")] + [string[]]$TestName, + + [Parameter(ParameterSetName='Default')] + [switch]$EnableExit, + + [Parameter(ParameterSetName='Default')] + [Alias('Tags')] + [string[]]$Tag, + [string[]]$ExcludeTag, + + [Parameter(ParameterSetName='Default')] + [Switch]$Strict, + + [String]$WorkSheetName = 'PesterResults', + + [switch]$Show +) + +$InvokePesterParams = @{OutputFormat = 'NUnitXml'} + $PSBoundParameters +if (-not $InvokePesterParams['OutputFile']) { + $InvokePesterParams['OutputFile'] = Join-Path -ChildPath 'Pester.xml'-Path ([environment]::GetFolderPath([System.Environment+SpecialFolder]::MyDocuments)) +} +if ($InvokePesterParams['Show'] ) {} +if ($InvokePesterParams['XLFile']) {$InvokePesterParams.Remove('XLFile')} +else {$XLFile = $InvokePesterParams['OutputFile'] -replace '.xml$','.xlsx'} +if (-not $UseExisting) { + $InvokePesterParams.Remove('UseExisting') + $InvokePesterParams.Remove('Show') + $InvokePesterParams.Remove('WorkSheetName') + Invoke-Pester @InvokePesterParams +} +if (-not (Test-Path -Path $InvokePesterParams['OutputFile'])) { + throw "Could not output file $($InvokePesterParams['OutputFile'])"; return +} + +$resultXML = ([xml](Get-Content $InvokePesterParams['OutputFile'])).'test-results' +$startDate = [datetime]$resultXML.date +$startTime = $resultXML.time +$machine = $resultXML.environment.'machine-name' +#$user = $resultXML.environment.'user-domain' + '\' + $resultXML.environment.user +$os = $resultXML.environment.platform -replace '\|.*$'," $($resultXML.environment.'os-version')" +<#hierarchy goes + root, [date], start [time], [Name] (always "Pester"), test results broken down as [total],[errors],[failures],[not-run] etc. + Environment (user & machine info) + Culture-Info (current, and currentUi culture) + Test-Suite [name] = "Pester" [result], [time] to execute, etc. + Results + Test-Suite [name] = filename,[result], [Time] to Execute etc + Results + Test-Suite [Name] = Describe block Name, [result], [Time] to execute etc.. + Results + Test-Suite [Name] = Context block name [result], [Time] to execute etc. + Results + Test-Case [name] = Describe.Context.It block names [description]= it block name, result], [Time] to execute etc + +#> +$testResults = foreach ($test in $resultXML.'test-suite'.results.'test-suite') { + $testPs1File = $test.name + #Test if there are context blocks in the hierarchy OR if we go straight from Describe to test-case + if ($test.results.'test-suite'.results.'test-suite' -ne $null) { + foreach ($suite in $test.results.'test-suite') { + $Describe = $suite.description + foreach ($subsuite in $suite.results.'test-suite') { + $Context = $subsuite.description + $subsuite.results.'test-case'| ForEach-Object { + New-Object -TypeName psobject -Property ([ordered]@{ + Machine = $machine ; OS = $os + Date = $startDate ; Time = $startTime + Executed = $_.executed ; Result = $_.result ; Duration = $_.time + File = $testPs1File; Group = $Describe ; SubGroup = $Context + Test =($_.Description -replace '\s{2,}', ' ') + FullDesc = '=Group&" "&SubGroup&" "&Test'}) + } + } + } + } + else { + $test.results.'test-suite' | ForEach-Object { + $Describe = $_.description + $_.results.'test-case'| ForEach-Object { + New-Object -TypeName psobject -Property ([ordered]@{ + Machine = $machine ; OS = $os + Date = $startDate ; Time = $startTime + Executed = $_.executed ; Result = $_.result ; Duration = $_.time + File = $testPs1File; Group = $Describe ; SubGroup = $null + Test =($_.Description -replace '\s{2,}', ' ') + FullDesc = '=Group&" "&Test'}) + } + } + } +} + +$excel = $testResults | Export-Excel -Path $xlFile -WorkSheetname $WorkSheetName -ClearSheet -PassThru -BoldTopRow -FreezeTopRow -AutoSize -AutoFilter -AutoNameRange +$ws = $excel.Workbook.Worksheets["PesterResults"] + +<# Worksheet should look like ... + |A |B |C D |E |F |G |H |I |J |K |L + 1|Machine |OS |Date Time |Executed |Result |Duration |File |Group |SubGroup |Test |FullDescription + 2|Flatfish |Name_Version |[run started] |Boolean |Success |In seconds |xx.ps1 |Describe |Context |It |Desc_Context_It +#> + +#Display Date as a date, not a date time +Set-Column -Worksheet $ws -Column 3 -NumberFormat 'Short Date' # -AutoSize + +#Hide columns G to K (the file and the parts of the description, and the duration)5 +(7..10) + 5 | ForEach-Object {Set-ExcelColumn -Worksheet $ws -Column $_ -Hide } + +#Use conditional formatting to make Failures red, and Successes green (skipped remains black ) ... and save +$endRow = $ws.Dimension.End.Row +Add-ConditionalFormatting -WorkSheet $ws -range "f2:f$endrow" -RuleType ContainsText -ConditionValue "Failure" -BackgroundPattern None -ForegroundColor Red -Bold +Add-ConditionalFormatting -WorkSheet $ws -range "f2:f$endRow" -RuleType ContainsText -ConditionValue "Success" -BackgroundPattern None -ForeGroundColor Green +Close-ExcelPackage -ExcelPackage $excel -Show:$show diff --git a/Public/New-ExcelStyle.ps1 b/Public/New-ExcelStyle.ps1 index 2bb2cde..c64df40 100644 --- a/Public/New-ExcelStyle.ps1 +++ b/Public/New-ExcelStyle.ps1 @@ -39,6 +39,7 @@ function New-ExcelStyle { [Switch]$AutoSize, [float]$Width, [float]$Height, + [Alias('Hide')] [Switch]$Hidden, [Switch]$Locked, [Switch]$Merge diff --git a/Public/Set-ExcelColumn.ps1 b/Public/Set-ExcelColumn.ps1 index feb9d4e..b4f9391 100644 --- a/Public/Set-ExcelColumn.ps1 +++ b/Public/Set-ExcelColumn.ps1 @@ -43,6 +43,7 @@ [Switch]$AutoSize, [float]$Width, [Switch]$AutoNameRange, + [Alias('Hidden')] [Switch]$Hide, [Switch]$Specified, [Switch]$PassThru diff --git a/Public/Set-ExcelRange.ps1 b/Public/Set-ExcelRange.ps1 index ae80b3e..37046d7 100644 --- a/Public/Set-ExcelRange.ps1 +++ b/Public/Set-ExcelRange.ps1 @@ -42,6 +42,7 @@ [Switch]$AutoSize, [float]$Width, [float]$Height, + [Alias('Hide')] [Switch]$Hidden, [Switch]$Locked, [Switch]$Merge diff --git a/Public/Set-ExcelRow.ps1 b/Public/Set-ExcelRow.ps1 index c2c454b..253487f 100644 --- a/Public/Set-ExcelRow.ps1 +++ b/Public/Set-ExcelRow.ps1 @@ -45,6 +45,7 @@ [ValidateRange(-90, 90)] [int]$TextRotation , [float]$Height, + [Alias('Hidden')] [Switch]$Hide, [Switch]$ReturnRange, [Switch]$PassThru From 7bfb28d10f0d7fe0bb0e1929d16d920b2524b394 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sun, 29 Dec 2019 17:18:24 +0000 Subject: [PATCH 05/12] Update Pester Syntax from V3 to V4 (V5 won't support the old version) --- Examples/TestRestAPI/PSExcelPester.psm1 | 2 +- Examples/TestRestAPI/TestAPIReadXls.ps1 | 2 +- __tests__/AddTrendlinesToAChart.tests.ps1 | 4 +- __tests__/Compare-WorkSheet.tests.ps1 | 290 +++---- __tests__/ConvertFrom-ExcelSheet.Tests.ps1 | 22 +- .../ConvertFromExcelToSQLInsert.tests.ps1 | 4 +- __tests__/Copy-ExcelWorksheet.Tests.ps1 | 64 +- __tests__/Export-Excel.Tests.ps1 | 738 +++++++++--------- __tests__/ExtraLongCmd.tests.ps1 | 52 +- __tests__/First10Races.tests.ps1 | 104 +-- __tests__/FunctionAlias.tests.ps1 | 10 +- __tests__/Get-ExcelColumnName.Test.ps1 | 12 +- __tests__/ImportExcelHeaderName.tests.ps1 | 158 ++-- __tests__/ImportExcelTests/Simple.tests.ps1 | 38 +- __tests__/InputItemParameter.tests.ps1 | 134 ++-- __tests__/Join-Worksheet.tests.ps1 | 82 +- __tests__/PasswordProtection.tests.ps1 | 8 +- __tests__/Path.tests.ps1 | 14 +- __tests__/ProtectWorksheet.tests.ps1 | 10 +- __tests__/RangePassing.ps1 | 102 +-- __tests__/Remove-WorkSheet.tests.ps1 | 32 +- .../Set-Row_Set-Column-SetFormat.tests.ps1 | 240 +++--- __tests__/Validation.tests.ps1 | 36 +- 23 files changed, 1079 insertions(+), 1079 deletions(-) diff --git a/Examples/TestRestAPI/PSExcelPester.psm1 b/Examples/TestRestAPI/PSExcelPester.psm1 index 7c95a32..9456c62 100644 --- a/Examples/TestRestAPI/PSExcelPester.psm1 +++ b/Examples/TestRestAPI/PSExcelPester.psm1 @@ -29,7 +29,7 @@ function ConvertTo-PesterTest { `$target.psobject.Properties.name | ForEach-Object {`$p=@{}} {`$p.`$_=`$(`$target.`$_)} - Invoke-RestMethod @p | Should Be '$($record.ExpectedResult)' + Invoke-RestMethod @p | Should -Be '$($record.ExpectedResult)' } "@ diff --git a/Examples/TestRestAPI/TestAPIReadXls.ps1 b/Examples/TestRestAPI/TestAPIReadXls.ps1 index 4aebc8c..42c7360 100644 --- a/Examples/TestRestAPI/TestAPIReadXls.ps1 +++ b/Examples/TestRestAPI/TestAPIReadXls.ps1 @@ -30,7 +30,7 @@ function Test-APIReadXls { `$target.psobject.Properties.name | ForEach-Object {`$p=@{}} {`$p.`$_=`$(`$target.`$_)} - Invoke-RestMethod @p | Should Be '$($record.ExpectedResult)' + Invoke-RestMethod @p | Should -Be '$($record.ExpectedResult)' } "@ diff --git a/__tests__/AddTrendlinesToAChart.tests.ps1 b/__tests__/AddTrendlinesToAChart.tests.ps1 index 16c98de..212b3e6 100644 --- a/__tests__/AddTrendlinesToAChart.tests.ps1 +++ b/__tests__/AddTrendlinesToAChart.tests.ps1 @@ -32,7 +32,7 @@ South,avocado,73 $excel = Open-ExcelPackage -Path $xlfile $ws = $excel.Workbook.Worksheets["Sheet1"] - $ws.Drawings[0].Series.TrendLines.Type | Should Be 'Linear' + $ws.Drawings[0].Series.TrendLines.Type | Should -Be 'Linear' Close-ExcelPackage $excel } @@ -45,7 +45,7 @@ South,avocado,73 $excel = Open-ExcelPackage -Path $xlfile $ws = $excel.Workbook.Worksheets["Sheet1"] - $ws.Drawings[0].Series.TrendLines.Type | Should Be 'MovingAvgerage' + $ws.Drawings[0].Series.TrendLines.Type | Should -Be 'MovingAvgerage' Close-ExcelPackage $excel } diff --git a/__tests__/Compare-WorkSheet.tests.ps1 b/__tests__/Compare-WorkSheet.tests.ps1 index c4154b2..cb72a75 100644 --- a/__tests__/Compare-WorkSheet.tests.ps1 +++ b/__tests__/Compare-WorkSheet.tests.ps1 @@ -31,29 +31,29 @@ Describe "Compare Worksheet" { } Context "Simple comparison output" { it "Found the right number of differences " { - $comp | should not beNullOrEmpty - $comp.Count | should be 4 + $comp | Should -Not -BeNullOrEmpty + $comp.Count | Should -Be 4 } it "Found the data row with a changed property " { - $comp | should not beNullOrEmpty - $comp[0]._Side | should not be $comp[1]._Side - $comp[0]._Row | should be 4 - $comp[1]._Row | should be 4 - $comp[1].Name | should be $comp[0].Name - $comp[0].DisplayName | should be $row4Displayname - $comp[1].DisplayName | should be "Changed from the orginal" + $comp | Should -Not -BeNullOrEmpty + $comp[0]._Side | Should -Not -Be $comp[1]._Side + $comp[0]._Row | Should -Be 4 + $comp[1]._Row | Should -Be 4 + $comp[1].Name | Should -Be $comp[0].Name + $comp[0].DisplayName | Should -Be $row4Displayname + $comp[1].DisplayName | Should -Be "Changed from the orginal" } it "Found the inserted data row " { - $comp | should not beNullOrEmpty - $comp[2]._Side | should be '=>' - $comp[2]._Row | should be 5 - $comp[2].Name | should be "Dummy" + $comp | Should -Not -BeNullOrEmpty + $comp[2]._Side | Should -Be '=>' + $comp[2]._Row | Should -Be 5 + $comp[2].Name | Should -Be "Dummy" } it "Found the deleted data row " { - $comp | should not beNullOrEmpty - $comp[3]._Side | should be '<=' - $comp[3]._Row | should be 6 - $comp[3].Name | should be $row6Name + $comp | Should -Not -BeNullOrEmpty + $comp[3]._Side | Should -Be '<=' + $comp[3]._Row | Should -Be 6 + $comp[3].Name | Should -Be $row6Name } } @@ -75,16 +75,16 @@ Describe "Compare Worksheet" { $s2Sheet = $xl2.Workbook.Worksheets[1] } it "Set the background on the right rows " { - $s1Sheet.Cells["4:4"].Style.Fill.BackgroundColor.Rgb | should be "FF90EE90" - $s1Sheet.Cells["6:6"].Style.Fill.BackgroundColor.Rgb | should be "FF90EE90" - $s2Sheet.Cells["4:4"].Style.Fill.BackgroundColor.Rgb | should be "FF90EE90" - $s2Sheet.Cells["5:5"].Style.Fill.BackgroundColor.Rgb | should be "FF90EE90" + $s1Sheet.Cells["4:4"].Style.Fill.BackgroundColor.Rgb | Should -Be "FF90EE90" + $s1Sheet.Cells["6:6"].Style.Fill.BackgroundColor.Rgb | Should -Be "FF90EE90" + $s2Sheet.Cells["4:4"].Style.Fill.BackgroundColor.Rgb | Should -Be "FF90EE90" + $s2Sheet.Cells["5:5"].Style.Fill.BackgroundColor.Rgb | Should -Be "FF90EE90" } it "Didn't set other cells " { - $s1Sheet.Cells["3:3"].Style.Fill.BackgroundColor.Rgb | should not be "FF90EE90" - $s1Sheet.Cells["F4"].Style.Font.Color.Rgb | should beNullOrEmpty - $s2Sheet.Cells["F4"].Style.Font.Color.Rgb | should beNullOrEmpty - $s2Sheet.Cells["3:3"].Style.Fill.BackgroundColor.Rgb | should not be "FF90EE90" + $s1Sheet.Cells["3:3"].Style.Fill.BackgroundColor.Rgb | Should -Not -Be "FF90EE90" + $s1Sheet.Cells["F4"].Style.Font.Color.Rgb | Should -BeNullOrEmpty + $s2Sheet.Cells["F4"].Style.Font.Color.Rgb | Should -BeNullOrEmpty + $s2Sheet.Cells["3:3"].Style.Fill.BackgroundColor.Rgb | Should -Not -Be "FF90EE90" } AfterAll { Close-ExcelPackage -ExcelPackage $xl1 -NoSave @@ -101,18 +101,18 @@ Describe "Compare Worksheet" { $s2Sheet = $xl2.Workbook.Worksheets[1] } it "Added foreground colour to the right cells " { - $s1Sheet.Cells["4:4"].Style.Fill.BackgroundColor.Rgb | should be "FF90EE90" - $s1Sheet.Cells["6:6"].Style.Fill.BackgroundColor.Rgb | should be "FF90EE90" - $s2Sheet.Cells["4:4"].Style.Fill.BackgroundColor.Rgb | should be "FF90EE90" - $s2Sheet.Cells["5:5"].Style.Fill.BackgroundColor.Rgb | should be "FF90EE90" - # $s1Sheet.Cells["F4"].Style.Font.Color.Rgb | should be "FF8B0000" - $s2Sheet.Cells["F4"].Style.Font.Color.Rgb | should be "FF8B0000" + $s1Sheet.Cells["4:4"].Style.Fill.BackgroundColor.Rgb | Should -Be "FF90EE90" + $s1Sheet.Cells["6:6"].Style.Fill.BackgroundColor.Rgb | Should -Be "FF90EE90" + $s2Sheet.Cells["4:4"].Style.Fill.BackgroundColor.Rgb | Should -Be "FF90EE90" + $s2Sheet.Cells["5:5"].Style.Fill.BackgroundColor.Rgb | Should -Be "FF90EE90" + # $s1Sheet.Cells["F4"].Style.Font.Color.Rgb | Should -Be "FF8B0000" + $s2Sheet.Cells["F4"].Style.Font.Color.Rgb | Should -Be "FF8B0000" } it "Didn't set the foreground on other cells " { - $s1Sheet.Cells["F5"].Style.Font.Color.Rgb | should beNullOrEmpty - $s2Sheet.Cells["F5"].Style.Font.Color.Rgb | should beNullOrEmpty - $s1Sheet.Cells["G4"].Style.Font.Color.Rgb | should beNullOrEmpty - $s2Sheet.Cells["G4"].Style.Font.Color.Rgb | should beNullOrEmpty + $s1Sheet.Cells["F5"].Style.Font.Color.Rgb | Should -BeNullOrEmpty + $s2Sheet.Cells["F5"].Style.Font.Color.Rgb | Should -BeNullOrEmpty + $s1Sheet.Cells["G4"].Style.Font.Color.Rgb | Should -BeNullOrEmpty + $s2Sheet.Cells["G4"].Style.Font.Color.Rgb | Should -BeNullOrEmpty } AfterAll { @@ -146,46 +146,46 @@ Describe "Compare Worksheet" { $s2Sheet = $xl2.Workbook.Worksheets["server2"] } it "Found the right number of differences " { - $comp | should not beNullOrEmpty - $comp.Count | should be 4 + $comp | Should -Not -BeNullOrEmpty + $comp.Count | Should -Be 4 } it "Found the data row with a changed property " { - $comp | should not beNullOrEmpty - $comp[0]._Side | should not be $comp[1]._Side - $comp[0]._Row | should be 4 - $comp[1]._Row | should be 4 - $comp[1].ServiceName | should be $comp[0].ServiceName - $comp[0].DisplayName | should be $row4Displayname - $comp[1].DisplayName | should be "Changed from the orginal" + $comp | Should -Not -BeNullOrEmpty + $comp[0]._Side | Should -Not -Be $comp[1]._Side + $comp[0]._Row | Should -Be 4 + $comp[1]._Row | Should -Be 4 + $comp[1].ServiceName | Should -Be $comp[0].ServiceName + $comp[0].DisplayName | Should -Be $row4Displayname + $comp[1].DisplayName | Should -Be "Changed from the orginal" } it "Found the inserted data row " { - $comp | should not beNullOrEmpty - $comp[2]._Side | should be '=>' - $comp[2]._Row | should be 5 - $comp[2].ServiceName | should be "Dummy" + $comp | Should -Not -BeNullOrEmpty + $comp[2]._Side | Should -Be '=>' + $comp[2]._Row | Should -Be 5 + $comp[2].ServiceName | Should -Be "Dummy" } it "Found the deleted data row " { - $comp | should not beNullOrEmpty - $comp[3]._Side | should be '<=' - $comp[3]._Row | should be 6 - $comp[3].ServiceName | should be $row6Name + $comp | Should -Not -BeNullOrEmpty + $comp[3]._Side | Should -Be '<=' + $comp[3]._Row | Should -Be 6 + $comp[3].ServiceName | Should -Be $row6Name } it "Set the background on the right rows " { - $s1Sheet.Cells["4:4"].Style.Fill.BackgroundColor.Rgb | should be "FFFFFFFF" - $s1Sheet.Cells["6:6"].Style.Fill.BackgroundColor.Rgb | Should be "FFFFFFFF" - $s2Sheet.Cells["4:4"].Style.Fill.BackgroundColor.Rgb | Should be "FFFFFFFF" - $s2Sheet.Cells["5:5"].Style.Fill.BackgroundColor.Rgb | Should be "FFFFFFFF" + $s1Sheet.Cells["4:4"].Style.Fill.BackgroundColor.Rgb | Should -Be "FFFFFFFF" + $s1Sheet.Cells["6:6"].Style.Fill.BackgroundColor.Rgb | Should -Be "FFFFFFFF" + $s2Sheet.Cells["4:4"].Style.Fill.BackgroundColor.Rgb | Should -Be "FFFFFFFF" + $s2Sheet.Cells["5:5"].Style.Fill.BackgroundColor.Rgb | Should -Be "FFFFFFFF" - $s1Sheet.Cells["E4"].Style.Font.Color.Rgb | Should be "FFFF0000" - $s2Sheet.Cells["E4"].Style.Font.Color.Rgb | Should be "FFFF0000" + $s1Sheet.Cells["E4"].Style.Font.Color.Rgb | Should -Be "FFFF0000" + $s2Sheet.Cells["E4"].Style.Font.Color.Rgb | Should -Be "FFFF0000" } it "Didn't set other cells " { - $s1Sheet.Cells["3:3"].Style.Fill.BackgroundColor.Rgb | Should not be "FFFFFFFF" - $s2Sheet.Cells["3:3"].Style.Fill.BackgroundColor.Rgb | Should not be "FFFFFFFF" - $s1Sheet.Cells["E5"].Style.Font.Color.Rgb | Should beNullOrEmpty - $s2Sheet.Cells["E5"].Style.Font.Color.Rgb | Should beNullOrEmpty - $s1Sheet.Cells["F4"].Style.Font.Color.Rgb | Should beNullOrEmpty - $s2Sheet.Cells["F4"].Style.Font.Color.Rgb | Should beNullOrEmpty + $s1Sheet.Cells["3:3"].Style.Fill.BackgroundColor.Rgb | Should -Not -Be "FFFFFFFF" + $s2Sheet.Cells["3:3"].Style.Fill.BackgroundColor.Rgb | Should -Not -Be "FFFFFFFF" + $s1Sheet.Cells["E5"].Style.Font.Color.Rgb | Should -BeNullOrEmpty + $s2Sheet.Cells["E5"].Style.Font.Color.Rgb | Should -BeNullOrEmpty + $s1Sheet.Cells["F4"].Style.Font.Color.Rgb | Should -BeNullOrEmpty + $s2Sheet.Cells["F4"].Style.Font.Color.Rgb | Should -BeNullOrEmpty } AfterAll { Close-ExcelPackage -ExcelPackage $xl1 -NoSave # -Show @@ -219,44 +219,44 @@ Describe "Merge Worksheet" { } Context "Merge with 3 properties" { it "Created a worksheet with the correct headings " { - $ws | should not beNullOrEmpty - $ws.Cells[ 1,1].Value | Should be "name" - $ws.Cells[ 1,2].Value | Should be "DisplayName" - $ws.Cells[ 1,3].Value | Should be "StartType" - $ws.Cells[ 1,4].Value | Should be "server2 DisplayName" - $ws.Cells[ 1,5].Value | Should be "server2 StartType" + $ws | Should -Not -BeNullOrEmpty + $ws.Cells[ 1,1].Value | Should -Be "name" + $ws.Cells[ 1,2].Value | Should -Be "DisplayName" + $ws.Cells[ 1,3].Value | Should -Be "StartType" + $ws.Cells[ 1,4].Value | Should -Be "server2 DisplayName" + $ws.Cells[ 1,5].Value | Should -Be "server2 StartType" } it "Joined the two sheets correctly " { - $ws.Cells[ 2,2].Value | Should be $ws.Cells[ 2,4].Value - $ws.Cells[ 2,3].Value | Should be $ws.Cells[ 2,5].Value - $ws.cells[ 4,4].value | Should be "Changed from the orginal" - $ws.cells[ 5,1].value | Should be "Dummy" - $ws.cells[ 5,2].value | Should beNullOrEmpty - $ws.cells[ 5,3].value | Should beNullOrEmpty - $ws.cells[ 5,4].value | Should be "Dummy Service" - $ws.cells[ 7,4].value | Should beNullOrEmpty - $ws.cells[ 7,5].value | Should beNullOrEmpty - $ws.Cells[12,2].Value | Should be $ws.Cells[12,4].Value - $ws.Cells[12,3].Value | Should be $ws.Cells[12,5].Value + $ws.Cells[ 2,2].Value | Should -Be $ws.Cells[ 2,4].Value + $ws.Cells[ 2,3].Value | Should -Be $ws.Cells[ 2,5].Value + $ws.cells[ 4,4].value | Should -Be "Changed from the orginal" + $ws.cells[ 5,1].value | Should -Be "Dummy" + $ws.cells[ 5,2].value | Should -BeNullOrEmpty + $ws.cells[ 5,3].value | Should -BeNullOrEmpty + $ws.cells[ 5,4].value | Should -Be "Dummy Service" + $ws.cells[ 7,4].value | Should -BeNullOrEmpty + $ws.cells[ 7,5].value | Should -BeNullOrEmpty + $ws.Cells[12,2].Value | Should -Be $ws.Cells[12,4].Value + $ws.Cells[12,3].Value | Should -Be $ws.Cells[12,5].Value } it "Highlighted the keys in the added / deleted / changed rows " { - $ws.cells[4,1].Style.font.color.rgb | Should be "FF8b0000" - $ws.cells[5,1].Style.font.color.rgb | Should be "FF8b0000" - $ws.cells[7,1].Style.font.color.rgb | Should be "FF8b0000" + $ws.cells[4,1].Style.font.color.rgb | Should -Be "FF8b0000" + $ws.cells[5,1].Style.font.color.rgb | Should -Be "FF8b0000" + $ws.cells[7,1].Style.font.color.rgb | Should -Be "FF8b0000" } it "Set the background for the added / deleted / changed rows " { - $ws.cells["A3:E3"].style.Fill.BackgroundColor.Rgb | Should beNullOrEmpty - $ws.cells["A4:E4"].style.Fill.BackgroundColor.Rgb | Should be "FFFFA500" - $ws.cells["A5" ].style.Fill.BackgroundColor.Rgb | Should be "FF98FB98" - $ws.cells["B5:C5"].style.Fill.BackgroundColor.rgb | Should beNullOrEmpty - $ws.cells["D5:E5"].style.Fill.BackgroundColor.Rgb | Should be "FF98FB98" - $ws.cells["A7:C7"].style.Fill.BackgroundColor.Rgb | Should be "FFFFB6C1" - $ws.cells["D7:E7"].style.Fill.BackgroundColor.rgb | Should beNullOrEmpty + $ws.cells["A3:E3"].style.Fill.BackgroundColor.Rgb | Should -BeNullOrEmpty + $ws.cells["A4:E4"].style.Fill.BackgroundColor.Rgb | Should -Be "FFFFA500" + $ws.cells["A5" ].style.Fill.BackgroundColor.Rgb | Should -Be "FF98FB98" + $ws.cells["B5:C5"].style.Fill.BackgroundColor.rgb | Should -BeNullOrEmpty + $ws.cells["D5:E5"].style.Fill.BackgroundColor.Rgb | Should -Be "FF98FB98" + $ws.cells["A7:C7"].style.Fill.BackgroundColor.Rgb | Should -Be "FFFFB6C1" + $ws.cells["D7:E7"].style.Fill.BackgroundColor.rgb | Should -BeNullOrEmpty } } Context "Wider data set" { it "Coped with columns beyond Z in the Output sheet " { - { Merge-Worksheet -Referencefile "TestDrive:\server1.xlsx" -Differencefile "TestDrive:\server2.xlsx" -OutputFile "TestDrive:\combined2.xlsx" } | Should not throw + { Merge-Worksheet -Referencefile "TestDrive:\server1.xlsx" -Differencefile "TestDrive:\server2.xlsx" -OutputFile "TestDrive:\combined2.xlsx" } | Should -Not -Throw } } } @@ -296,64 +296,64 @@ Describe "Merge Multiple sheets" { } it "Created a worksheet with the correct headings " { - $ws | Should not beNullOrEmpty - $ws.Cells[ 1,2 ].Value | Should be "name" - $ws.Cells[ 1,3 ].Value | Should be "server1 DisplayName" - $ws.Cells[ 1,4 ].Value | Should be "server1 StartType" - $ws.Cells[ 1,5 ].Value | Should be "server2 DisplayName" - $ws.Cells[ 1,6 ].Value | Should be "server2 StartType" - $ws.Column(7).hidden | Should be $true - $ws.Cells[ 1,8].Value | Should be "server2 Row" - $ws.Cells[ 1,9 ].Value | Should be "server3 DisplayName" - $ws.Cells[ 1,10].Value | Should be "server3 StartType" - $ws.Column(11).hidden | Should be $true - $ws.Cells[ 1,12].Value | Should be "server3 Row" + $ws | Should -Not -BeNullOrEmpty + $ws.Cells[ 1,2 ].Value | Should -Be "name" + $ws.Cells[ 1,3 ].Value | Should -Be "server1 DisplayName" + $ws.Cells[ 1,4 ].Value | Should -Be "server1 StartType" + $ws.Cells[ 1,5 ].Value | Should -Be "server2 DisplayName" + $ws.Cells[ 1,6 ].Value | Should -Be "server2 StartType" + $ws.Column(7).hidden | Should -Be $true + $ws.Cells[ 1,8].Value | Should -Be "server2 Row" + $ws.Cells[ 1,9 ].Value | Should -Be "server3 DisplayName" + $ws.Cells[ 1,10].Value | Should -Be "server3 StartType" + $ws.Column(11).hidden | Should -Be $true + $ws.Cells[ 1,12].Value | Should -Be "server3 Row" } it "Joined the three sheets correctly " { - $ws.Cells[ 2,3 ].Value | Should be $ws.Cells[ 2,5 ].Value - $ws.Cells[ 2,4 ].Value | Should be $ws.Cells[ 2,6 ].Value - $ws.Cells[ 2,5 ].Value | Should be $ws.Cells[ 2,9 ].Value - $ws.Cells[ 2,6 ].Value | Should be $ws.Cells[ 2,10].Value - $ws.cells[ 4,5 ].value | Should be "Changed from the orginal" - $ws.cells[ 4,9 ].value | Should be $ws.Cells[ 4,3 ].Value - $ws.cells[ 5,2 ].value | Should be "Dummy" - $ws.cells[ 5,3 ].value | Should beNullOrEmpty - $ws.cells[ 5,4 ].value | Should beNullOrEmpty - $ws.cells[ 5,5 ].value | Should be "Dummy Service" - $ws.cells[ 5,8 ].value | Should be ($ws.cells[ 4,1].value +1) - $ws.cells[ 5,9 ].value | Should be $ws.cells[ 5,5 ].value - $ws.cells[ 7,5 ].value | Should beNullOrEmpty - $ws.cells[ 7,6 ].value | Should beNullOrEmpty - $ws.cells[ 7,9 ].value | Should beNullOrEmpty - $ws.cells[ 7,10].value | Should beNullOrEmpty - $ws.cells[ 8,3 ].value | Should beNullOrEmpty - $ws.cells[ 8,4 ].value | Should beNullOrEmpty - $ws.cells[ 8,5 ].value | Should beNullOrEmpty - $ws.cells[ 8,6 ].value | Should beNullOrEmpty - $ws.cells[11,9 ].value | Should beNullOrEmpty - $ws.cells[11,10].value | Should beNullOrEmpty - $ws.Cells[12,3 ].Value | Should be $ws.Cells[12,5].Value - $ws.Cells[12,4 ].Value | Should be $ws.Cells[12,6].Value - $ws.Cells[12,9 ].Value | Should be $ws.Cells[12,5].Value - $ws.Cells[12,10].Value | Should be $ws.Cells[12,6].Value + $ws.Cells[ 2,3 ].Value | Should -Be $ws.Cells[ 2,5 ].Value + $ws.Cells[ 2,4 ].Value | Should -Be $ws.Cells[ 2,6 ].Value + $ws.Cells[ 2,5 ].Value | Should -Be $ws.Cells[ 2,9 ].Value + $ws.Cells[ 2,6 ].Value | Should -Be $ws.Cells[ 2,10].Value + $ws.cells[ 4,5 ].value | Should -Be "Changed from the orginal" + $ws.cells[ 4,9 ].value | Should -Be $ws.Cells[ 4,3 ].Value + $ws.cells[ 5,2 ].value | Should -Be "Dummy" + $ws.cells[ 5,3 ].value | Should -BeNullOrEmpty + $ws.cells[ 5,4 ].value | Should -BeNullOrEmpty + $ws.cells[ 5,5 ].value | Should -Be "Dummy Service" + $ws.cells[ 5,8 ].value | Should -Be ($ws.cells[ 4,1].value +1) + $ws.cells[ 5,9 ].value | Should -Be $ws.cells[ 5,5 ].value + $ws.cells[ 7,5 ].value | Should -BeNullOrEmpty + $ws.cells[ 7,6 ].value | Should -BeNullOrEmpty + $ws.cells[ 7,9 ].value | Should -BeNullOrEmpty + $ws.cells[ 7,10].value | Should -BeNullOrEmpty + $ws.cells[ 8,3 ].value | Should -BeNullOrEmpty + $ws.cells[ 8,4 ].value | Should -BeNullOrEmpty + $ws.cells[ 8,5 ].value | Should -BeNullOrEmpty + $ws.cells[ 8,6 ].value | Should -BeNullOrEmpty + $ws.cells[11,9 ].value | Should -BeNullOrEmpty + $ws.cells[11,10].value | Should -BeNullOrEmpty + $ws.Cells[12,3 ].Value | Should -Be $ws.Cells[12,5].Value + $ws.Cells[12,4 ].Value | Should -Be $ws.Cells[12,6].Value + $ws.Cells[12,9 ].Value | Should -Be $ws.Cells[12,5].Value + $ws.Cells[12,10].Value | Should -Be $ws.Cells[12,6].Value } it "Created Conditional formatting rules " { $cf=$ws.ConditionalFormatting - $cf.Count | Should be 17 - $cf[16].Address.Address | Should be 'B2:B1048576' - $cf[16].Type | Should be 'Expression' - $cf[16].Formula | Should be 'OR(G2<>"Same",K2<>"Same")' - $cf[16].Style.Font.Color.Color.Name | Should be "FFFF0000" - $cf[14].Address.Address | Should be 'D2:D1048576' - $cf[14].Type | Should be 'Expression' - $cf[14].Formula | Should be 'OR(G2="Added",K2="Added")' - $cf[14].Style.Fill.BackgroundColor.Color.Name | Should be 'ffffb6c1' - $cf[14].Style.Fill.PatternType.ToString() | Should be 'Solid' - $cf[ 0].Address.Address | Should be 'F1:F1048576' - $cf[ 0].Type | Should be 'Expression' - $cf[ 0].Formula | Should be 'G1="Added"' - $cf[ 0].Style.Fill.BackgroundColor.Color.Name | Should be 'ffffa500' - $cf[ 0].Style.Fill.PatternType.ToString() | Should be 'Solid' + $cf.Count | Should -Be 17 + $cf[16].Address.Address | Should -Be 'B2:B1048576' + $cf[16].Type | Should -Be 'Expression' + $cf[16].Formula | Should -Be 'OR(G2<>"Same",K2<>"Same")' + $cf[16].Style.Font.Color.Color.Name | Should -Be "FFFF0000" + $cf[14].Address.Address | Should -Be 'D2:D1048576' + $cf[14].Type | Should -Be 'Expression' + $cf[14].Formula | Should -Be 'OR(G2="Added",K2="Added")' + $cf[14].Style.Fill.BackgroundColor.Color.Name | Should -Be 'ffffb6c1' + $cf[14].Style.Fill.PatternType.ToString() | Should -Be 'Solid' + $cf[ 0].Address.Address | Should -Be 'F1:F1048576' + $cf[ 0].Type | Should -Be 'Expression' + $cf[ 0].Formula | Should -Be 'G1="Added"' + $cf[ 0].Style.Fill.BackgroundColor.Color.Name | Should -Be 'ffffa500' + $cf[ 0].Style.Fill.PatternType.ToString() | Should -Be 'Solid' } } } \ No newline at end of file diff --git a/__tests__/ConvertFrom-ExcelSheet.Tests.ps1 b/__tests__/ConvertFrom-ExcelSheet.Tests.ps1 index dfc5498..3702d87 100644 --- a/__tests__/ConvertFrom-ExcelSheet.Tests.ps1 +++ b/__tests__/ConvertFrom-ExcelSheet.Tests.ps1 @@ -17,25 +17,25 @@ Describe 'ConvertFrom-ExcelSheet / Export-ExcelSheet' { } Context "Exporting to CSV" { it "Exported the expected columns to a CSV file " { - $firstText[0] | should be '"Race","Date","FinishPosition","Driver","GridPosition","Team","Points"' - $SecondText[0] | should be '"Race","Date","FinishPosition","Driver","GridPosition","Team","Points"' - $ThirdText[0] | should be '"Driver","date","FinishPosition","GridPosition"' - $FourthText[0] | should be '"Race","Date","FinishPosition","Driver","GridPosition","Team","Points"' + $firstText[0] | Should -Be '"Race","Date","FinishPosition","Driver","GridPosition","Team","Points"' + $SecondText[0] | Should -Be '"Race","Date","FinishPosition","Driver","GridPosition","Team","Points"' + $ThirdText[0] | Should -Be '"Driver","date","FinishPosition","GridPosition"' + $FourthText[0] | Should -Be '"Race","Date","FinishPosition","Driver","GridPosition","Team","Points"' } it "Applied AsText, AsDate and Properties correctly " { - $firstText[1] | should match '^"\w+","\d{5}","\d{1,2}","\w+ \w+","[1-9]\d?","\w+","\d{1,2}"$' + $firstText[1] | Should -Match '^"\w+","\d{5}","\d{1,2}","\w+ \w+","[1-9]\d?","\w+","\d{1,2}"$' $date = $firstText[1] -replace '^.*(\d{5}).*$', '$1' $date = [datetime]::FromOADate($date).toString("D") - $secondText[1] | should belike "*$date*" - $secondText[1] | should match '"0\d","\w+","\d{1,2}"$' - $ThirdText[1] | should match '^"\w+ \w+","#\d\d/\d\d/\d{4}#","\d","0\d"$' - $FourthText[1] | should match '^"\w+","[012]\d' + $secondText[1] | Should -Belike "*$date*" + $secondText[1] | Should -Match '"0\d","\w+","\d{1,2}"$' + $ThirdText[1] | Should -Match '^"\w+ \w+","#\d\d/\d\d/\d{4}#","\d","0\d"$' + $FourthText[1] | Should -Match '^"\w+","[012]\d' } } Context "Export aliased to ConvertFrom" { it "Definded the alias name with " { - (Get-Alias Export-ExcelSheet).source | should be "ImportExcel" - (Get-Alias Export-ExcelSheet).Definition | should be "ConvertFrom-ExcelSheet" + (Get-Alias Export-ExcelSheet).source | Should -Be "ImportExcel" + (Get-Alias Export-ExcelSheet).Definition | Should -Be "ConvertFrom-ExcelSheet" } } } \ No newline at end of file diff --git a/__tests__/ConvertFromExcelToSQLInsert.tests.ps1 b/__tests__/ConvertFromExcelToSQLInsert.tests.ps1 index 7729f53..08859ed 100644 --- a/__tests__/ConvertFromExcelToSQLInsert.tests.ps1 +++ b/__tests__/ConvertFromExcelToSQLInsert.tests.ps1 @@ -22,7 +22,7 @@ Describe "ConvertFrom-ExcelToSQLInsert" { $actual = ConvertFrom-ExcelToSQLInsert -Path $xlFile Sheet1 - $actual | should be $expected + $actual | Should -Be $expected } It "Should have NULL".PadRight(90) { @@ -30,6 +30,6 @@ Describe "ConvertFrom-ExcelToSQLInsert" { $actual = ConvertFrom-ExcelToSQLInsert -Path $xlFile Sheet1 -ConvertEmptyStringsToNull - $actual | should be $expected + $actual | Should -Be $expected } } \ No newline at end of file diff --git a/__tests__/Copy-ExcelWorksheet.Tests.ps1 b/__tests__/Copy-ExcelWorksheet.Tests.ps1 index 3ebcf4c..4d0d9d0 100644 --- a/__tests__/Copy-ExcelWorksheet.Tests.ps1 +++ b/__tests__/Copy-ExcelWorksheet.Tests.ps1 @@ -41,9 +41,9 @@ Describe "Copy-Worksheet" { $ws = $excel.Workbook.Worksheets["Processes"] } it "Inserted a worksheet " { - $Excel.Workbook.Worksheets.count | Should be 2 - $ws | Should not benullorEmpty - $ws.Dimension.Address | should be $ProcRange + $Excel.Workbook.Worksheets.count | Should -Be 2 + $ws | Should -Not -BenullorEmpty + $ws.Dimension.Address | Should -Be $ProcRange } } Context "Mixed types using a package object" { @@ -54,38 +54,38 @@ Describe "Copy-Worksheet" { $ws = $Excel.Workbook.Worksheets[3] } it "Copied a worksheet, giving the expected name, number of rows and number of columns " { - $Excel.Workbook.Worksheets.count | Should be 3 - $ws | Should not benullorEmpty - $ws.Name | Should be "CopyOfMixedTypes" - $ws.Dimension.Columns | Should be 22 - $ws.Dimension.Rows | Should be 2 + $Excel.Workbook.Worksheets.count | Should -Be 3 + $ws | Should -Not -BenullorEmpty + $ws.Name | Should -Be "CopyOfMixedTypes" + $ws.Dimension.Columns | Should -Be 22 + $ws.Dimension.Rows | Should -Be 2 } it "Copied the expected data into the worksheet " { - $ws.Cells[2, 1].Value.Gettype().name | Should be 'DateTime' - $ws.Cells[2, 2].Formula | Should be 'SUM(F2:G2)' - $ws.Cells[2, 5].Value.GetType().name | Should be 'String' - $ws.Cells[2, 6].Value.GetType().name | Should be 'String' - $ws.Cells[2, 18].Value.GetType().name | Should be 'String' - ($ws.Cells[2, 11].Value -is [valuetype] ) | Should be $true - ($ws.Cells[2, 12].Value -is [valuetype] ) | Should be $true - ($ws.Cells[2, 13].Value -is [valuetype] ) | Should be $true - $ws.Cells[2, 11].Value | Should beLessThan 0 - $ws.Cells[2, 12].Value | Should beLessThan 0 - $ws.Cells[2, 13].Value | Should beLessThan 0 + $ws.Cells[2, 1].Value.Gettype().name | Should -Be 'DateTime' + $ws.Cells[2, 2].Formula | Should -Be 'SUM(F2:G2)' + $ws.Cells[2, 5].Value.GetType().name | Should -Be 'String' + $ws.Cells[2, 6].Value.GetType().name | Should -Be 'String' + $ws.Cells[2, 18].Value.GetType().name | Should -Be 'String' + ($ws.Cells[2, 11].Value -is [valuetype] ) | Should -Be $true + ($ws.Cells[2, 12].Value -is [valuetype] ) | Should -Be $true + ($ws.Cells[2, 13].Value -is [valuetype] ) | Should -Be $true + $ws.Cells[2, 11].Value | Should -BeLessThan 0 + $ws.Cells[2, 12].Value | Should -BeLessThan 0 + $ws.Cells[2, 13].Value | Should -BeLessThan 0 if ((Get-Culture).NumberFormat.NumberGroupSeparator -EQ ",") { - ($ws.Cells[2, 8].Value -is [valuetype] ) | Should be $true - $ws.Cells[2, 9].Value.GetType().name | Should be 'String' + ($ws.Cells[2, 8].Value -is [valuetype] ) | Should -Be $true + $ws.Cells[2, 9].Value.GetType().name | Should -Be 'String' } elseif ((Get-Culture).NumberFormat.NumberGroupSeparator -EQ ".") { - ($ws.Cells[2, 9].Value -is [valuetype] ) | Should be $true - $ws.Cells[2, 8].Value.GetType().name | Should be 'String' + ($ws.Cells[2, 9].Value -is [valuetype] ) | Should -Be $true + $ws.Cells[2, 8].Value.GetType().name | Should -Be 'String' } - ($ws.Cells[2, 14].Value -is [valuetype] ) | Should be $true - $ws.Cells[2, 15].Value.GetType().name | Should be 'String' - $ws.Cells[2, 16].Value.GetType().name | Should be 'String' - $ws.Cells[2, 17].Value.GetType().name | Should be 'String' - ($ws.Cells[2, 19].Value -is [valuetype] ) | Should be $true - ($ws.Cells[2, 20].Value -is [valuetype] ) | Should be $true + ($ws.Cells[2, 14].Value -is [valuetype] ) | Should -Be $true + $ws.Cells[2, 15].Value.GetType().name | Should -Be 'String' + $ws.Cells[2, 16].Value.GetType().name | Should -Be 'String' + $ws.Cells[2, 17].Value.GetType().name | Should -Be 'String' + ($ws.Cells[2, 19].Value -is [valuetype] ) | Should -Be $true + ($ws.Cells[2, 20].Value -is [valuetype] ) | Should -Be $true } } @@ -113,7 +113,7 @@ Describe "Copy-Worksheet" { $targetSheets | ForEach-Object { Remove-Worksheet -FullName $xlfile -WorksheetName $_ } - (Get-ExcelSheetInfo -Path $xlfile ).Count | Should Be 3 + (Get-ExcelSheetInfo -Path $xlfile ).Count | Should -Be 3 } } @@ -136,8 +136,8 @@ Describe "Copy-Worksheet" { } it "Should copy sheets piped into the command " { $excel = Open-ExcelPackage $xlfileArchive - $excel.Workbook.Worksheets.Count | should be 5 - $excel.Workbook.Worksheets['1.3.2019'].Cells['A1'].Value | should be 'Hello World' + $excel.Workbook.Worksheets.Count | should -be 5 + $excel.Workbook.Worksheets['1.3.2019'].Cells['A1'].Value | should -be 'Hello World' } } } \ No newline at end of file diff --git a/__tests__/Export-Excel.Tests.ps1 b/__tests__/Export-Excel.Tests.ps1 index aaeae93..07f66f7 100644 --- a/__tests__/Export-Excel.Tests.ps1 +++ b/__tests__/Export-Excel.Tests.ps1 @@ -28,11 +28,11 @@ Describe ExportExcel { $Processes | Export-Excel $path #-show it "Created a new file " { - Test-Path -Path $path -ErrorAction SilentlyContinue | Should be $true + Test-Path -Path $path -ErrorAction SilentlyContinue | Should -Be $true } # it "Started Excel to display the file " { - # Get-process -Name Excel, xlim -ErrorAction SilentlyContinue | Should not beNullOrEmpty + # Get-process -Name Excel, xlim -ErrorAction SilentlyContinue | Should -Not -BeNullOrEmpty # } #Start-Sleep -Seconds 5 ; @@ -41,42 +41,42 @@ Describe ExportExcel { #TODO Need to test opening pre-existing file with no -create switch (and graceful failure when file does not exist) somewhere else $Excel = Open-ExcelPackage -Path $path -KillExcel it "Killed Excel when Open-Excelpackage was told to " { - Get-process -Name Excel, xlim -ErrorAction SilentlyContinue | Should beNullOrEmpty + Get-process -Name Excel, xlim -ErrorAction SilentlyContinue | Should -BeNullOrEmpty } it "Created 1 worksheet, named 'Sheet1' " { - $Excel.Workbook.Worksheets.count | Should be 1 - $Excel.Workbook.Worksheets["Sheet1"] | Should not beNullOrEmpty + $Excel.Workbook.Worksheets.count | Should -Be 1 + $Excel.Workbook.Worksheets["Sheet1"] | Should -Not -BeNullOrEmpty } it "Added a 'Sheet1' property to the Package object " { - $Excel.Sheet1 | Should not beNullOrEmpty + $Excel.Sheet1 | Should -Not -BeNullOrEmpty } $ws = $Excel.Workbook.Worksheets[1] it "Created the worksheet with the expected name, number of rows and number of columns " { - $ws.Name | Should be "sheet1" - $ws.Dimension.Columns | Should be $propertyNames.Count - $ws.Dimension.Rows | Should be ($rowcount + 1) + $ws.Name | Should -Be "sheet1" + $ws.Dimension.Columns | Should -Be $propertyNames.Count + $ws.Dimension.Rows | Should -Be ($rowcount + 1) } $headingNames = $ws.cells["1:1"].Value it "Created the worksheet with the correct header names " { foreach ($p in $propertyNames) { - $headingnames -contains $p | Should be $true + $headingnames -contains $p | Should -Be $true } } it "Formatted the process StartTime field as 'localized Date-Time' " { $STHeader = $ws.cells["1:1"].where( {$_.Value -eq "StartTime"})[0] $STCell = $STHeader.Address -replace '1$', '2' - $ws.cells[$stcell].Style.Numberformat.NumFmtID | Should be 22 + $ws.cells[$stcell].Style.Numberformat.NumFmtID | Should -Be 22 } it "Formatted the process ID field as 'General' " { $IDHeader = $ws.cells["1:1"].where( {$_.Value -eq "ID"})[0] $IDCell = $IDHeader.Address -replace '1$', '2' - $ws.cells[$IDcell].Style.Numberformat.NumFmtID | Should be 0 + $ws.cells[$IDcell].Style.Numberformat.NumFmtID | Should -Be 0 } } @@ -93,15 +93,15 @@ Describe ExportExcel { $Excel = Open-ExcelPackage -Path $path $ws = $Excel.Workbook.Worksheets[1] it "Created a new file with Alias & Script Properties removed. " { - $ws.Name | Should be "sheet1" - $ws.Dimension.Columns | Should be $propertyNames.Count - $ws.Dimension.Rows | Should be ($rowcount + 1 ) # +1 for the header. + $ws.Name | Should -Be "sheet1" + $ws.Dimension.Columns | Should -Be $propertyNames.Count + $ws.Dimension.Rows | Should -Be ($rowcount + 1 ) # +1 for the header. } it "Created a Range - even though the name given was invalid. " { - $ws.Names["No_spaces"] | Should not beNullOrEmpty - $ws.Names["No_spaces"].End.Column | Should be $propertyNames.Count - $ws.names["No_spaces"].End.Row | Should be ($rowcount + 1 ) # +1 for the header. - $warnVar.Count | Should be 1 + $ws.Names["No_spaces"] | Should -Not -BeNullOrEmpty + $ws.Names["No_spaces"].End.Column | Should -Be $propertyNames.Count + $ws.names["No_spaces"].End.Row | Should -Be ($rowcount + 1 ) # +1 for the header. + $warnVar.Count | Should -Be 1 } #This time use clearsheet instead of deleting the file test -Exclude properties, including wildcards. $Processes | Export-Excel $path -ClearSheet -NoAliasOrScriptPropeties -ExcludeProperty SafeHandle, threads, modules, MainModule, StartInfo, MachineName, MainWindow*, M*workingSet @@ -109,9 +109,9 @@ Describe ExportExcel { $Excel = Open-ExcelPackage -Path $path $ws = $Excel.Workbook.Worksheets[1] it "Created a new file with further properties excluded and cleared the old sheet " { - $ws.Name | Should be "sheet1" - $ws.Dimension.Columns | Should be ($propertyNames.Count - 10) - $ws.Dimension.Rows | Should be ($rowcount + 1) # +1 for the header + $ws.Name | Should -Be "sheet1" + $ws.Dimension.Columns | Should -Be ($propertyNames.Count - 10) + $ws.Dimension.Rows | Should -Be ($rowcount + 1) # +1 for the header } $propertyNames = $Processes[0].psStandardmembers.DefaultDisplayPropertySet.ReferencedPropertyNames @@ -122,9 +122,9 @@ Describe ExportExcel { $Excel = Open-ExcelPackage -Path $path $ws = $Excel.Workbook.Worksheets[1] it "Created a new file with just the members of the Display Property Set " { - $ws.Name | Should be "sheet1" - $ws.Dimension.Columns | Should be $propertyNames.Count - $ws.Dimension.Rows | Should be ($rowcount + 1) + $ws.Name | Should -Be "sheet1" + $ws.Dimension.Columns | Should -Be $propertyNames.Count + $ws.Dimension.Rows | Should -Be ($rowcount + 1) } } @@ -135,34 +135,34 @@ Describe ExportExcel { #testing -ReturnRange switch and applying number format to Formulas as well as values. $returnedRange = @($null, -1, 0, 34, 777, "", -0.5, 119, -0.1, 234, 788,"=A9+A10") | Export-Excel -NumberFormat '[Blue]$#,##0.00;[Red]-$#,##0.00' -Path $path -ReturnRange it "Created a new file and returned the expected range " { - Test-Path -Path $path -ErrorAction SilentlyContinue | Should be $true - $returnedRange | Should be "A1:A12" + Test-Path -Path $path -ErrorAction SilentlyContinue | Should -Be $true + $returnedRange | Should -Be "A1:A12" } $Excel = Open-ExcelPackage -Path $path it "Created 1 worksheet " { - $Excel.Workbook.Worksheets.count | Should be 1 + $Excel.Workbook.Worksheets.count | Should -Be 1 } $ws = $Excel.Workbook.Worksheets[1] it "Created the worksheet with the expected name, number of rows and number of columns " { - $ws.Name | Should be "sheet1" - $ws.Dimension.Columns | Should be 1 - $ws.Dimension.End.Row | Should be 12 + $ws.Name | Should -Be "sheet1" + $ws.Dimension.Columns | Should -Be 1 + $ws.Dimension.End.Row | Should -Be 12 } it "Set the default style for the sheet as expected " { - $ws.cells.Style.Numberformat.Format | Should be '[Blue]$#,##0.00;[Red]-$#,##0.00' + $ws.cells.Style.Numberformat.Format | Should -Be '[Blue]$#,##0.00;[Red]-$#,##0.00' } it "Set the default style and set values for Cells as expected, handling null,0 and '' " { - $ws.cells[1, 1].Style.Numberformat.Format | Should be '[Blue]$#,##0.00;[Red]-$#,##0.00' - $ws.cells[1, 1].Value | Should beNullorEmpty - $ws.cells[2, 1].Value | Should be -1 - $ws.cells[3, 1].Value | Should be 0 - $ws.cells[5, 1].Value | Should be 777 - $ws.cells[6, 1].Value | Should be "" - $ws.cells[4, 1].Style.Numberformat.Format | Should be '[Blue]$#,##0.00;[Red]-$#,##0.00' + $ws.cells[1, 1].Style.Numberformat.Format | Should -Be '[Blue]$#,##0.00;[Red]-$#,##0.00' + $ws.cells[1, 1].Value | Should -BeNullorEmpty + $ws.cells[2, 1].Value | Should -Be -1 + $ws.cells[3, 1].Value | Should -Be 0 + $ws.cells[5, 1].Value | Should -Be 777 + $ws.cells[6, 1].Value | Should -Be "" + $ws.cells[4, 1].Style.Numberformat.Format | Should -Be '[Blue]$#,##0.00;[Red]-$#,##0.00' } } @@ -178,13 +178,13 @@ Describe ExportExcel { $ws = $excel.Workbook.Worksheets[1] } it "Set the worksheet default number format correctly " { - $ws.Cells.Style.Numberformat.Format | Should be "0.00" + $ws.Cells.Style.Numberformat.Format | Should -Be "0.00" } it "Set number formats on specific blocks of cells " { - $ws.Cells["A2" ].Style.Numberformat.Format | Should be "0.00" - $ws.Cells["c19"].Style.Numberformat.Format | Should be "0.00" - $ws.Cells["A20"].Style.Numberformat.Format | Should be "0.00%" - $ws.Cells["C6" ].Style.Numberformat.Format | Should be (Expand-NumberFormat "currency") + $ws.Cells["A2" ].Style.Numberformat.Format | Should -Be "0.00" + $ws.Cells["c19"].Style.Numberformat.Format | Should -Be "0.00" + $ws.Cells["A20"].Style.Numberformat.Format | Should -Be "0.00%" + $ws.Cells["C6" ].Style.Numberformat.Format | Should -Be (Expand-NumberFormat "currency") } } @@ -226,84 +226,84 @@ Describe ExportExcel { TimeSpan = [datetime]::Now.Subtract([datetime]::Today) } | Export-Excel -NoNumberConversion IPAddress, StrLeadZero, StrAltPhone2 -Path $path -Calculate -WarningVariable $warnVar it "Created a new file " { - Test-Path -Path $path -ErrorAction SilentlyContinue | Should be $true + Test-Path -Path $path -ErrorAction SilentlyContinue | Should -Be $true } $Excel = Open-ExcelPackage -Path $path it "Created 1 worksheet with no warnings " { - $Excel.Workbook.Worksheets.count | Should be 1 - $warnVar | Should beNullorEmpty + $Excel.Workbook.Worksheets.count | Should -Be 1 + $warnVar | Should -BeNullorEmpty } $ws = $Excel.Workbook.Worksheets[1] it "Created the worksheet with the expected name, number of rows and number of columns " { - $ws.Name | Should be "sheet1" - $ws.Dimension.Columns | Should be 27 - $ws.Dimension.Rows | Should be 2 + $ws.Name | Should -Be "sheet1" + $ws.Dimension.Columns | Should -Be 27 + $ws.Dimension.Rows | Should -Be 2 } it "Set a date in Cell A2 " { - $ws.Cells[2, 1].Value.Gettype().name | Should be 'DateTime' + $ws.Cells[2, 1].Value.Gettype().name | Should -Be 'DateTime' } it "Set a formula in Cell B2 " { - $ws.Cells[2, 2].Formula | Should be 'SUM(S2:T2)' + $ws.Cells[2, 2].Formula | Should -Be 'SUM(S2:T2)' } it "Forced a successful calculation of the Value in Cell B2 " { - $ws.Cells[2, 2].Value | Should be 246 + $ws.Cells[2, 2].Value | Should -Be 246 } it "Set strings in Cells E2, F2 and R2 (no number conversion) " { - $ws.Cells[2, 5].Value.GetType().name | Should be 'String' - $ws.Cells[2, 6].Value.GetType().name | Should be 'String' - $ws.Cells[2, 18].Value.GetType().name | Should be 'String' + $ws.Cells[2, 5].Value.GetType().name | Should -Be 'String' + $ws.Cells[2, 6].Value.GetType().name | Should -Be 'String' + $ws.Cells[2, 18].Value.GetType().name | Should -Be 'String' } it "Set numbers in Cells K2,L2,M2 (diferent Negative integer formats) " { - ($ws.Cells[2, 11].Value -is [valuetype] ) | Should be $true - ($ws.Cells[2, 12].Value -is [valuetype] ) | Should be $true - ($ws.Cells[2, 13].Value -is [valuetype] ) | Should be $true - $ws.Cells[2, 11].Value | Should beLessThan 0 - $ws.Cells[2, 12].Value | Should beLessThan 0 - $ws.Cells[2, 13].Value | Should beLessThan 0 + ($ws.Cells[2, 11].Value -is [valuetype] ) | Should -Be $true + ($ws.Cells[2, 12].Value -is [valuetype] ) | Should -Be $true + ($ws.Cells[2, 13].Value -is [valuetype] ) | Should -Be $true + $ws.Cells[2, 11].Value | Should -BeLessThan 0 + $ws.Cells[2, 12].Value | Should -BeLessThan 0 + $ws.Cells[2, 13].Value | Should -BeLessThan 0 } it "Set external hyperlinks in Cells U2 and V2 " { - $ws.Cells[2, 21].Hyperlink | Should be "https://github.com/dfinke/ImportExcel" - $ws.Cells[2, 22].Hyperlink | Should be "https://github.com/dfinke/ImportExcel" + $ws.Cells[2, 21].Hyperlink | Should -Be "https://github.com/dfinke/ImportExcel" + $ws.Cells[2, 22].Hyperlink | Should -Be "https://github.com/dfinke/ImportExcel" } it "Set internal hyperlinks in Cells W2 and X2 " { - $ws.Cells[2, 23].Hyperlink.Scheme | Should be "xl" - $ws.Cells[2, 23].Hyperlink.ReferenceAddress | Should be "sheet1!A1" - $ws.Cells[2, 23].Hyperlink.Display | Should be "sheet1" - $ws.Cells[2, 24].Hyperlink.Scheme | Should be "xl" - $ws.Cells[2, 24].Hyperlink.ReferenceAddress | Should be "sheet1!c5" - $ws.Cells[2, 24].Hyperlink.Display | Should be "sheet1!c5" - $ws.Cells[2, 25].Hyperlink.ReferenceAddress | Should be "sheet1!E2" - $ws.Cells[2, 25].Hyperlink.Display | Should be "Display Text" + $ws.Cells[2, 23].Hyperlink.Scheme | Should -Be "xl" + $ws.Cells[2, 23].Hyperlink.ReferenceAddress | Should -Be "sheet1!A1" + $ws.Cells[2, 23].Hyperlink.Display | Should -Be "sheet1" + $ws.Cells[2, 24].Hyperlink.Scheme | Should -Be "xl" + $ws.Cells[2, 24].Hyperlink.ReferenceAddress | Should -Be "sheet1!c5" + $ws.Cells[2, 24].Hyperlink.Display | Should -Be "sheet1!c5" + $ws.Cells[2, 25].Hyperlink.ReferenceAddress | Should -Be "sheet1!E2" + $ws.Cells[2, 25].Hyperlink.Display | Should -Be "Display Text" } it "Processed thousands according to local settings (Cells H2 and I2) " { if ((Get-Culture).NumberFormat.NumberGroupSeparator -EQ ",") { - ($ws.Cells[2, 8].Value -is [valuetype] ) | Should be $true - $ws.Cells[2, 9].Value.GetType().name | Should be 'String' + ($ws.Cells[2, 8].Value -is [valuetype] ) | Should -Be $true + $ws.Cells[2, 9].Value.GetType().name | Should -Be 'String' } elseif ((Get-Culture).NumberFormat.NumberGroupSeparator -EQ ".") { - ($ws.Cells[2, 9].Value -is [valuetype] ) | Should be $true - $ws.Cells[2, 8].Value.GetType().name | Should be 'String' + ($ws.Cells[2, 9].Value -is [valuetype] ) | Should -Be $true + $ws.Cells[2, 8].Value.GetType().name | Should -Be 'String' } } it "Processed local currency as a number and other currency as a string (N2 & O2) " { - ($ws.Cells[2, 14].Value -is [valuetype] ) | Should be $true - $ws.Cells[2, 15].Value.GetType().name | Should be 'String' + ($ws.Cells[2, 14].Value -is [valuetype] ) | Should -Be $true + $ws.Cells[2, 15].Value.GetType().name | Should -Be 'String' } it "Processed numbers with spaces between digits as strings (P2 & Q2) " { - $ws.Cells[2, 16].Value.GetType().name | Should be 'String' - $ws.Cells[2, 17].Value.GetType().name | Should be 'String' + $ws.Cells[2, 16].Value.GetType().name | Should -Be 'String' + $ws.Cells[2, 17].Value.GetType().name | Should -Be 'String' } it "Processed numbers leading or trailing speaces as Numbers (S2 & T2) " { - ($ws.Cells[2, 19].Value -is [valuetype] ) | Should be $true - ($ws.Cells[2, 20].Value -is [valuetype] ) | Should be $true + ($ws.Cells[2, 19].Value -is [valuetype] ) | Should -Be $true + ($ws.Cells[2, 20].Value -is [valuetype] ) | Should -Be $true } it "Converted a nested object to a string (Y2) " { - $ws.Cells[2, 26].Value | Should match '^System\.Diagnostics\.Process\s+\(.*\)$' + $ws.Cells[2, 26].Value | Should -Match '^System\.Diagnostics\.Process\s+\(.*\)$' } it "Processed a timespan object (Z2) " { - $ws.cells[2, 27].Value.ToOADate() | Should beGreaterThan 0 - $ws.cells[2, 27].Value.ToOADate() | Should beLessThan 1 - $ws.cells[2, 27].Style.Numberformat.Format | Should be '[h]:mm:ss' + $ws.cells[2, 27].Value.ToOADate() | Should -BeGreaterThan 0 + $ws.cells[2, 27].Value.ToOADate() | Should -BeLessThan 1 + $ws.cells[2, 27].Style.Numberformat.Format | Should -Be '[h]:mm:ss' } } @@ -329,40 +329,40 @@ Describe ExportExcel { Link = [uri]"https://github.com/dfinke/ImportExcel" } | Export-Excel -NoNumberConversion IPAddress, Number1 -Path $path -NoHeader it "Created a new file " { - Test-Path -Path $path -ErrorAction SilentlyContinue | Should be $true + Test-Path -Path $path -ErrorAction SilentlyContinue | Should -Be $true } $Excel = Open-ExcelPackage -Path $path it "Created 1 worksheet " { - $Excel.Workbook.Worksheets.count | Should be 1 + $Excel.Workbook.Worksheets.count | Should -Be 1 } $ws = $Excel.Workbook.Worksheets[1] it "Created the worksheet with the expected name, number of rows and number of columns " { - $ws.Name | Should be "sheet1" - $ws.Dimension.Columns | Should be 14 - $ws.Dimension.Rows | Should be 1 + $ws.Name | Should -Be "sheet1" + $ws.Dimension.Columns | Should -Be 14 + $ws.Dimension.Rows | Should -Be 1 } it "Set a date in Cell A1 " { - $ws.Cells[1, 1].Value.Gettype().name | Should be 'DateTime' + $ws.Cells[1, 1].Value.Gettype().name | Should -Be 'DateTime' } it "Set a formula in Cell B1 " { - $ws.Cells[1, 2].Formula | Should be 'SUM(F1:G1)' + $ws.Cells[1, 2].Formula | Should -Be 'SUM(F1:G1)' } it "Set strings in Cells E1 and F1 " { - $ws.Cells[1, 5].Value.GetType().name | Should be 'String' - $ws.Cells[1, 6].Value.GetType().name | Should be 'String' + $ws.Cells[1, 5].Value.GetType().name | Should -Be 'String' + $ws.Cells[1, 6].Value.GetType().name | Should -Be 'String' } it "Set a number in Cell I1 " { - ($ws.Cells[1, 9].Value -is [valuetype] ) | Should be $true + ($ws.Cells[1, 9].Value -is [valuetype] ) | Should -Be $true } it "Set a hyperlink in Cell N1 " { - $ws.Cells[1, 14].Hyperlink | Should be "https://github.com/dfinke/ImportExcel" + $ws.Cells[1, 14].Hyperlink | Should -Be "https://github.com/dfinke/ImportExcel" } } @@ -376,7 +376,7 @@ Describe ExportExcel { 489, 668, 299, 777, 860, 151, 119, 497, 234, 788 | Export-Excel -Path $path -ConditionalText $ct it "Created a new file " { - Test-Path -Path $path -ErrorAction SilentlyContinue | Should be $true + Test-Path -Path $path -ErrorAction SilentlyContinue | Should -Be $true } #ToDo need to test applying conitional formatting to a pre-existing worksheet and removing = from formula @@ -384,16 +384,16 @@ Describe ExportExcel { $ws = $Excel.Workbook.Worksheets[1] it "Added one block of conditional formating for the data range " { - $ws.ConditionalFormatting.Count | Should be 1 - $ws.ConditionalFormatting[0].Address | Should be ($ws.Dimension.Address) + $ws.ConditionalFormatting.Count | Should -Be 1 + $ws.ConditionalFormatting[0].Address | Should -Be ($ws.Dimension.Address) } $cf = $ws.ConditionalFormatting[0] it "Set the conditional formatting properties correctly " { - $cf.Formula | Should be $ct.Text - $cf.Type.ToString() | Should be $ct.ConditionalType - #$cf.Style.Fill.BackgroundColor | Should be $ct.BackgroundColor - # $cf.Style.Font.Color | Should be $ct.ConditionalTextColor - have to compare r.g.b + $cf.Formula | Should -Be $ct.Text + $cf.Type.ToString() | Should -Be $ct.ConditionalType + #$cf.Style.Fill.BackgroundColor | Should -Be $ct.BackgroundColor + # $cf.Style.Font.Color | Should -Be $ct.ConditionalTextColor - have to compare r.g.b } } @@ -411,15 +411,15 @@ Describe ExportExcel { Context "#Example 6 # Adding multiple conditional formats using short form syntax. " { it "Added two blocks of conditional formating for the data range " { - $ws.ConditionalFormatting.Count | Should be 2 - $ws.ConditionalFormatting[0].Address | Should be ($ws.Dimension.Address) - $ws.ConditionalFormatting[1].Address | Should be ($ws.Dimension.Address) + $ws.ConditionalFormatting.Count | Should -Be 2 + $ws.ConditionalFormatting[0].Address | Should -Be ($ws.Dimension.Address) + $ws.ConditionalFormatting[1].Address | Should -Be ($ws.Dimension.Address) } it "Set the conditional formatting properties correctly " { - $ws.ConditionalFormatting[0].Text | Should be "Stop" - $ws.ConditionalFormatting[1].Text | Should be "Running" - $ws.ConditionalFormatting[0].Type | Should be "ContainsText" - $ws.ConditionalFormatting[1].Type | Should be "ContainsText" + $ws.ConditionalFormatting[0].Text | Should -Be "Stop" + $ws.ConditionalFormatting[1].Text | Should -Be "Running" + $ws.ConditionalFormatting[0].Type | Should -Be "ContainsText" + $ws.ConditionalFormatting[1].Type | Should -Be "ContainsText" #Add RGB Comparison } } @@ -450,14 +450,14 @@ Describe ExportExcel { #test Update-FirstObjectProperties $newarray = $Array | Update-FirstObjectProperties it "Outputs as many objects as it input " { - $newarray.Count | Should be $Array.Count + $newarray.Count | Should -Be $Array.Count } it "Added properties to item 0 " { - $newarray[0].psobject.Properties.name.Count | Should be 4 - $newarray[0].Member1 | Should be 'First' - $newarray[0].Member2 | Should be 'Second' - $newarray[0].Member3 | Should beNullOrEmpty - $newarray[0].Member4 | Should beNullOrEmpty + $newarray[0].psobject.Properties.name.Count | Should -Be 4 + $newarray[0].Member1 | Should -Be 'First' + $newarray[0].Member2 | Should -Be 'Second' + $newarray[0].Member3 | Should -BeNullOrEmpty + $newarray[0].Member4 | Should -BeNullOrEmpty } } @@ -472,25 +472,25 @@ Describe ExportExcel { $PTws = $Excel.Workbook.Worksheets["ProcessesPivotTable"] $wCount = $Excel.Workbook.Worksheets.Count it "Added the named sheet and pivot table to the workbook " { - $excel.ProcessesPivotTable | Should not beNullOrEmpty - $PTws | Should not beNullOrEmpty - $PTws.PivotTables.Count | Should be 1 - $Excel.Workbook.Worksheets["Processes"] | Should not beNullOrEmpty - $Excel.Workbook.Worksheets.Count | Should beGreaterThan 2 - $excel.Workbook.Worksheets["Processes"].Dimension.rows | Should be 21 #20 data + 1 header + $excel.ProcessesPivotTable | Should -Not -BeNullOrEmpty + $PTws | Should -Not -BeNullOrEmpty + $PTws.PivotTables.Count | Should -Be 1 + $Excel.Workbook.Worksheets["Processes"] | Should -Not -BeNullOrEmpty + $Excel.Workbook.Worksheets.Count | Should -BeGreaterThan 2 + $excel.Workbook.Worksheets["Processes"].Dimension.rows | Should -Be 21 #20 data + 1 header } it "Selected the Pivottable page " { Set-ItResult -Pending -Because "Bug in EPPLus 4.5" - $PTws.View.TabSelected | Should be $true + $PTws.View.TabSelected | Should -Be $true } $pt = $PTws.PivotTables[0] it "Built the expected Pivot table " { - $pt.RowFields.Count | Should be 1 - $pt.RowFields[0].Name | Should be "Company" - $pt.DataFields.Count | Should be 1 - $pt.DataFields[0].Function | Should be "Count" - $pt.DataFields[0].Field.Name | Should be "PM" - $PTws.Drawings.Count | Should be 0 + $pt.RowFields.Count | Should -Be 1 + $pt.RowFields[0].Name | Should -Be "Company" + $pt.DataFields.Count | Should -Be 1 + $pt.DataFields[0].Function | Should -Be "Count" + $pt.DataFields[0].Field.Name | Should -Be "PM" + $PTws.Drawings.Count | Should -Be 0 } #test adding pivot chart using the already open sheet $warnvar = $null @@ -498,12 +498,12 @@ Describe ExportExcel { $Excel = Open-ExcelPackage $path it "Added a chart to the pivot table without rebuilding " { $ws = $Excel.Workbook.Worksheets["ProcessesPivotTable"] - $Excel.Workbook.Worksheets.Count | Should be $wCount - $ws.Drawings.count | Should be 1 - $ws.Drawings[0].ChartType.ToString() | Should be "PieExploded3D" + $Excel.Workbook.Worksheets.Count | Should -Be $wCount + $ws.Drawings.count | Should -Be 1 + $ws.Drawings[0].ChartType.ToString() | Should -Be "PieExploded3D" } it "Generated a message on re-processing the Pivot table " { - $warnVar | Should not beNullOrEmpty + $warnVar | Should -Not -BeNullOrEmpty } #Test appending data extends pivot chart (with a warning) . $warnVar = $null @@ -511,13 +511,13 @@ Describe ExportExcel { $Excel = Open-ExcelPackage $path $pt = $Excel.Workbook.Worksheets["ProcessesPivotTable"].PivotTables[0] it "Appended to the Worksheet and Extended the Pivot table " { - $Excel.Workbook.Worksheets.Count | Should be $wCount - $excel.Workbook.Worksheets["Processes"].Dimension.rows | Should be 41 #appended 20 rows to the previous total + $Excel.Workbook.Worksheets.Count | Should -Be $wCount + $excel.Workbook.Worksheets["Processes"].Dimension.rows | Should -Be 41 #appended 20 rows to the previous total $pt.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref | Should be "A1:E41" } it "Generated a message on extending the Pivot table " { - $warnVar | Should not beNullOrEmpty + $warnVar | Should -Not -BeNullOrEmpty } } @@ -537,21 +537,21 @@ Describe ExportExcel { $Excel = Open-ExcelPackage $path it "Got the Sheets in the right order " { - $excel.Workbook.Worksheets[1].Name | Should be "Another" - $excel.Workbook.Worksheets[2].Name | Should be "NewSheet" - $excel.Workbook.Worksheets[3].Name | Should be "Onelast" - $excel.Workbook.Worksheets[4].Name | Should be "ProcessesPivotTable" - $excel.Workbook.Worksheets[5].Name | Should be "Processes" - $excel.Workbook.Worksheets[6].Name | Should be "NearDone" - $excel.Workbook.Worksheets[7].Name | Should be "Sheet1" + $excel.Workbook.Worksheets[1].Name | Should -Be "Another" + $excel.Workbook.Worksheets[2].Name | Should -Be "NewSheet" + $excel.Workbook.Worksheets[3].Name | Should -Be "Onelast" + $excel.Workbook.Worksheets[4].Name | Should -Be "ProcessesPivotTable" + $excel.Workbook.Worksheets[5].Name | Should -Be "Processes" + $excel.Workbook.Worksheets[6].Name | Should -Be "NearDone" + $excel.Workbook.Worksheets[7].Name | Should -Be "Sheet1" } it "Cloned 'Sheet1' to 'NewSheet' " { $newWs = $excel.Workbook.Worksheets["NewSheet"] - $newWs.Dimension.Address | Should be ($excel.Workbook.Worksheets["Sheet1"].Dimension.Address) - $newWs.ConditionalFormatting.Count | Should be ($excel.Workbook.Worksheets["Sheet1"].ConditionalFormatting.Count) - $newWs.ConditionalFormatting[0].Address.Address | Should be ($excel.Workbook.Worksheets["Sheet1"].ConditionalFormatting[0].Address.Address) - $newWs.ConditionalFormatting[0].Formula | Should be ($excel.Workbook.Worksheets["Sheet1"].ConditionalFormatting[0].Formula) + $newWs.Dimension.Address | Should -Be ($excel.Workbook.Worksheets["Sheet1"].Dimension.Address) + $newWs.ConditionalFormatting.Count | Should -Be ($excel.Workbook.Worksheets["Sheet1"].ConditionalFormatting.Count) + $newWs.ConditionalFormatting[0].Address.Address | Should -Be ($excel.Workbook.Worksheets["Sheet1"].ConditionalFormatting[0].Address.Address) + $newWs.ConditionalFormatting[0].Formula | Should -Be ($excel.Workbook.Worksheets["Sheet1"].ConditionalFormatting[0].Formula) } } @@ -568,41 +568,41 @@ Describe ExportExcel { $dataWs = $Excel.Workbook.Worksheets["withOffset"] $pt = $Excel.Workbook.Worksheets["PTOffset"].PivotTables[0] it "Created and appended to a sheet offset from the top left corner " { - $dataWs.Cells[1, 1].Value | Should beNullOrEmpty - $dataWs.Cells[2, 2].Value | Should beNullOrEmpty - $dataWs.Cells[3, 3].Value | Should not beNullOrEmpty - $dataWs.Cells[3, 3].Style.Font.Bold | Should be $true - $dataWs.Dimension.End.Row | Should be 23 - $dataWs.names[0].Start.row | Should be 4 # StartRow + 1 - $dataWs.names[0].End.row | Should be $dataWs.Dimension.End.Row - $dataWs.names[0].Name | Should be 'Name' - $dataWs.names.Count | Should be 7 # Name, cpu, pm, handles & company + Named Range "Procs" + xl one for autofilter - $dataWs.cells[$dataws.Dimension].AutoFilter | Should be true + $dataWs.Cells[1, 1].Value | Should -BeNullOrEmpty + $dataWs.Cells[2, 2].Value | Should -BeNullOrEmpty + $dataWs.Cells[3, 3].Value | Should -Not -BeNullOrEmpty + $dataWs.Cells[3, 3].Style.Font.Bold | Should -Be $true + $dataWs.Dimension.End.Row | Should -Be 23 + $dataWs.names[0].Start.row | Should -Be 4 # StartRow + 1 + $dataWs.names[0].End.row | Should -Be $dataWs.Dimension.End.Row + $dataWs.names[0].Name | Should -Be 'Name' + $dataWs.names.Count | Should -Be 7 # Name, cpu, pm, handles & company + Named Range "Procs" + xl one for autofilter + $dataWs.cells[$dataws.Dimension].AutoFilter | Should -Be true } it "Applied and auto-extended an autofilter " { - $dataWs.Names["_xlnm._FilterDatabase"].Start.Row | Should be 3 #offset - $dataWs.Names["_xlnm._FilterDatabase"].Start.Column | Should be 3 - $dataWs.Names["_xlnm._FilterDatabase"].Rows | Should be 21 #2 x 10 data + 1 header - $dataWs.Names["_xlnm._FilterDatabase"].Columns | Should be 5 #Name, cpu, pm, handles & company - $dataWs.Names["_xlnm._FilterDatabase"].AutoFilter | Should be $true + $dataWs.Names["_xlnm._FilterDatabase"].Start.Row | Should -Be 3 #offset + $dataWs.Names["_xlnm._FilterDatabase"].Start.Column | Should -Be 3 + $dataWs.Names["_xlnm._FilterDatabase"].Rows | Should -Be 21 #2 x 10 data + 1 header + $dataWs.Names["_xlnm._FilterDatabase"].Columns | Should -Be 5 #Name, cpu, pm, handles & company + $dataWs.Names["_xlnm._FilterDatabase"].AutoFilter | Should -Be $true } it "Created and auto-extended the named ranges " { - $dataWs.names["procs"].rows | Should be 21 - $dataWs.names["procs"].Columns | Should be 5 - $dataWs.Names["CPU"].Rows | Should be 20 - $dataWs.Names["CPU"].Columns | Should be 1 + $dataWs.names["procs"].rows | Should -Be 21 + $dataWs.names["procs"].Columns | Should -Be 5 + $dataWs.Names["CPU"].Rows | Should -Be 20 + $dataWs.Names["CPU"].Columns | Should -Be 1 } it "Created and extended the pivot table " { $pt.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref | Should be "C3:G23" - $pt.ColumGrandTotals | Should be $false - $pt.RowGrandTotals | Should be $false - $pt.Fields["Company"].IsRowField | Should be $true - $pt.Fields["PM"].IsDataField | Should be $true - $pt.Fields["Name"].IsPageField | Should be $true + $pt.ColumGrandTotals | Should -Be $false + $pt.RowGrandTotals | Should -Be $false + $pt.Fields["Company"].IsRowField | Should -Be $true + $pt.Fields["PM"].IsDataField | Should -Be $true + $pt.Fields["Name"].IsPageField | Should -Be $true } it "Generated a message on extending the Pivot table " { - $warnVar | Should not beNullOrEmpty + $warnVar | Should -Not -BeNullOrEmpty } } @@ -616,13 +616,13 @@ Describe ExportExcel { $dataWs = $Excel.Workbook.Worksheets["NoOffset"] #table should be 20 rows + header after extending the data. CPU range should be 1x20 it "Created a new sheet and auto-extended a table and explicitly extended named ranges " { - $dataWs.Tables["ProcTab"].Address.Address | Should be "A1:E21" - $dataWs.Names["CPU"].Rows | Should be 20 - $dataWs.Names["CPU"].Columns | Should be 1 + $dataWs.Tables["ProcTab"].Address.Address | Should -Be "A1:E21" + $dataWs.Names["CPU"].Rows | Should -Be 20 + $dataWs.Names["CPU"].Columns | Should -Be 1 } it "Set the expected number formats " { - $dataWs.cells["C2"].Style.Numberformat.Format | Should be "General" - $dataWs.cells["C12"].Style.Numberformat.Format | Should be "0.00" + $dataWs.cells["C2"].Style.Numberformat.Format | Should -Be "General" + $dataWs.cells["C12"].Style.Numberformat.Format | Should -Be "0.00" } #Test extneding autofilter and range when explicitly specified in the append $excel = Get-Process | Select-Object -first 10 -Property Name, cpu, pm, handles, company | Export-Excel -ExcelPackage $excel -RangeName procs -AutoFilter -WorkSheetname NoOffset -ClearSheet -PassThru @@ -631,11 +631,11 @@ Describe ExportExcel { $dataWs = $Excel.Workbook.Worksheets["NoOffset"] it "Created a new sheet and explicitly extended named range and autofilter " { - $dataWs.names["procs"].rows | Should be 21 - $dataWs.names["procs"].Columns | Should be 5 - $dataWs.Names["_xlnm._FilterDatabase"].Rows | Should be 21 #2 x 10 data + 1 header - $dataWs.Names["_xlnm._FilterDatabase"].Columns | Should be 5 #Name, cpu, pm, handles & company - $dataWs.Names["_xlnm._FilterDatabase"].AutoFilter | Should be $true + $dataWs.names["procs"].rows | Should -Be 21 + $dataWs.names["procs"].Columns | Should -Be 5 + $dataWs.Names["_xlnm._FilterDatabase"].Rows | Should -Be 21 #2 x 10 data + 1 header + $dataWs.Names["_xlnm._FilterDatabase"].Columns | Should -Be 5 #Name, cpu, pm, handles & company + $dataWs.Names["_xlnm._FilterDatabase"].AutoFilter | Should -Be $true } } @@ -647,13 +647,13 @@ Describe ExportExcel { $ptDef += New-PivotTableDefinition -PivotTableName "PT2" -SourceWorkSheet 'Sheet2' -PivotRows "Company" -PivotData @{'Company' = 'Count'} -PivotTotalS Rows -IncludePivotChart -ChartType PieExploded3D -ShowPercent -WarningAction SilentlyContinue it "Built a pivot definition using New-PivotTableDefinition " { - $ptDef.PT1.SourceWorkSheet | Should be 'Sheet1' - $ptDef.PT1.PivotRows | Should be 'Status' - $ptDef.PT1.PivotData.Status | Should be 'Count' - $ptDef.PT1.PivotFilter | Should be 'StartType' - $ptDef.PT1.IncludePivotChart | Should be $true - $ptDef.PT1.ChartType.tostring() | Should be 'BarClustered3D' - $ptDef.PT1.PivotTotals | Should be 'Columns' + $ptDef.PT1.SourceWorkSheet | Should -Be 'Sheet1' + $ptDef.PT1.PivotRows | Should -Be 'Status' + $ptDef.PT1.PivotData.Status | Should -Be 'Count' + $ptDef.PT1.PivotFilter | Should -Be 'StartType' + $ptDef.PT1.IncludePivotChart | Should -Be $true + $ptDef.PT1.ChartType.tostring() | Should -Be 'BarClustered3D' + $ptDef.PT1.PivotTotals | Should -Be 'Columns' } Remove-Item -Path $path #Catch warning @@ -667,26 +667,26 @@ Describe ExportExcel { if ($isWindows) { it "Set Column widths (with autosize) " { - $ws1.Column(2).Width | Should not be $ws1.DefaultColWidth - $ws2.Column(1).width | Should not be $ws2.DefaultColWidth + $ws1.Column(2).Width | Should -Not -Be $ws1.DefaultColWidth + $ws2.Column(1).width | Should -Not -Be $ws2.DefaultColWidth } } it "Added tables to both sheets (handling illegal chars) and a title in sheet 2 " { - $warnvar.count | Should beGreaterThan 0 - $ws1.tables.Count | Should be 1 - $ws2.tables.Count | Should be 1 - $ws1.Tables[0].Address.Start.Row | Should be 1 - $ws2.Tables[0].Address.Start.Row | Should be 2 #Title in row 1 - $ws1.Tables[0].Address.End.Address | Should be $ws1.Dimension.End.Address - $ws2.Tables[0].Address.End.Address | Should be $ws2.Dimension.End.Address - $ws2.Tables[0].Name | Should be "Processes" - $ws2.Tables[0].StyleName | Should be "TableStyleLight1" - $ws2.Cells["A1"].Value | Should be "Processes" - $ws2.Cells["A1"].Style.Font.Bold | Should be $true - $ws2.Cells["A1"].Style.Font.Size | Should be 22 - $ws2.Cells["A1"].Style.Fill.PatternType.tostring() | Should be "solid" - $ws2.Cells["A1"].Style.Fill.BackgroundColor.Rgb | Should be "fff0f8ff" + $warnvar.count | Should -BeGreaterThan 0 + $ws1.tables.Count | Should -Be 1 + $ws2.tables.Count | Should -Be 1 + $ws1.Tables[0].Address.Start.Row | Should -Be 1 + $ws2.Tables[0].Address.Start.Row | Should -Be 2 #Title in row 1 + $ws1.Tables[0].Address.End.Address | Should -Be $ws1.Dimension.End.Address + $ws2.Tables[0].Address.End.Address | Should -Be $ws2.Dimension.End.Address + $ws2.Tables[0].Name | Should -Be "Processes" + $ws2.Tables[0].StyleName | Should -Be "TableStyleLight1" + $ws2.Cells["A1"].Value | Should -Be "Processes" + $ws2.Cells["A1"].Style.Font.Bold | Should -Be $true + $ws2.Cells["A1"].Style.Font.Size | Should -Be 22 + $ws2.Cells["A1"].Style.Fill.PatternType.tostring() | Should -Be "solid" + $ws2.Cells["A1"].Style.Fill.BackgroundColor.Rgb | Should -Be "fff0f8ff" } $ptsheet1 = $Excel.Workbook.Worksheets["Pt1"] @@ -702,23 +702,23 @@ Describe ExportExcel { Should be "Processes" } it "Set the other pivot tables and chart options from the definitions. " { - $pt1.PageFields[0].Name | Should be 'StartType' - $pt1.RowFields[0].Name | Should be 'Status' - $pt1.DataFields[0].Field.name | Should be 'Status' - $pt1.DataFields[0].Function | Should be 'Count' - $pt1.ColumGrandTotals | Should be $true - $pt1.RowGrandTotals | Should be $false - $pt2.ColumGrandTotals | Should be $false - $pt2.RowGrandTotals | Should be $true - $pc1.ChartType | Should be 'BarClustered3D' - $pc1.From.Column | Should be 0 #chart 1 at 0,10 chart 2 at 4,0 (default) - $pc2.From.Column | Should be 4 - $pc1.From.Row | Should be 10 - $pc2.From.Row | Should be 0 - $pc1.Legend.Font | Should beNullOrEmpty #Best check for legend removed. - $pc2.Legend.Font | Should not beNullOrEmpty - $pc1.Title.Text | Should be 'Services by status' - $pc2.DataLabel.ShowPercent | Should be $true + $pt1.PageFields[0].Name | Should -Be 'StartType' + $pt1.RowFields[0].Name | Should -Be 'Status' + $pt1.DataFields[0].Field.name | Should -Be 'Status' + $pt1.DataFields[0].Function | Should -Be 'Count' + $pt1.ColumGrandTotals | Should -Be $true + $pt1.RowGrandTotals | Should -Be $false + $pt2.ColumGrandTotals | Should -Be $false + $pt2.RowGrandTotals | Should -Be $true + $pc1.ChartType | Should -Be 'BarClustered3D' + $pc1.From.Column | Should -Be 0 #chart 1 at 0,10 chart 2 at 4,0 (default) + $pc2.From.Column | Should -Be 4 + $pc1.From.Row | Should -Be 10 + $pc2.From.Row | Should -Be 0 + $pc1.Legend.Font | Should -BeNullOrEmpty #Best check for legend removed. + $pc2.Legend.Font | Should -Not -BeNullOrEmpty + $pc1.Title.Text | Should -Be 'Services by status' + $pc2.DataLabel.ShowPercent | Should -Be $true } } @@ -747,59 +747,59 @@ Describe ExportExcel { $excel = Open-ExcelPackage $path $sheet = $excel.Workbook.Worksheets["Processes"] it "Returned the rule when calling Add-ConditionalFormatting -passthru " { - $rule | Should not beNullOrEmpty - $rule.getType().fullname | Should be "OfficeOpenXml.ConditionalFormatting.ExcelConditionalFormattingTopPercent" - $rule.Style.Font.Strike | Should be true + $rule | Should -Not -BeNullOrEmpty + $rule.getType().fullname | Should -Be "OfficeOpenXml.ConditionalFormatting.ExcelConditionalFormattingTopPercent" + $rule.Style.Font.Strike | Should -Be true } it "Applied the formating " { - $sheet | Should not beNullOrEmpty + $sheet | Should -Not -BeNullOrEmpty if ($isWindows) { - $sheet.Column(1).width | Should not be $sheet.DefaultColWidth - $sheet.Column(7).width | Should not be $sheet.DefaultColWidth + $sheet.Column(1).width | Should -Not -Be $sheet.DefaultColWidth + $sheet.Column(7).width | Should -Not -Be $sheet.DefaultColWidth } - $sheet.Column(1).style.font.bold | Should be $true - $sheet.Column(2).style.wraptext | Should be $true - $sheet.Column(2).width | Should be 29 - $sheet.Column(3).style.horizontalalignment | Should be 'right' - $sheet.Column(4).style.horizontalalignment | Should be 'right' - $sheet.Cells["A1"].Style.HorizontalAlignment | Should be 'Center' - $sheet.Cells['E2'].Style.HorizontalAlignment | Should be 'right' - $sheet.Cells['A1'].Style.Font.Bold | Should be $true - $sheet.Cells['D2'].Style.Font.Bold | Should be $true - $sheet.Cells['E2'].style.numberformat.format | Should be '#,###' - $sheet.Column(3).style.numberformat.format | Should be '#,###' - $sheet.Column(4).style.numberformat.format | Should be '#,##0.0' - $sheet.ConditionalFormatting.Count | Should be 3 - $sheet.ConditionalFormatting[0].type | Should be 'Databar' - $sheet.ConditionalFormatting[0].Color.name | Should be 'ffff0000' - $sheet.ConditionalFormatting[0].Address.Address | Should be 'D2:D1048576' - $sheet.ConditionalFormatting[1].Style.Font.Strike | Should be $true - $sheet.ConditionalFormatting[1].type | Should be "TopPercent" - $sheet.ConditionalFormatting[2].type | Should be 'GreaterThan' - $sheet.ConditionalFormatting[2].Formula | Should be '104857600' - $sheet.ConditionalFormatting[2].Style.Font.Color.Color.Name | Should be 'ffff0000' + $sheet.Column(1).style.font.bold | Should -Be $true + $sheet.Column(2).style.wraptext | Should -Be $true + $sheet.Column(2).width | Should -Be 29 + $sheet.Column(3).style.horizontalalignment | Should -Be 'right' + $sheet.Column(4).style.horizontalalignment | Should -Be 'right' + $sheet.Cells["A1"].Style.HorizontalAlignment | Should -Be 'Center' + $sheet.Cells['E2'].Style.HorizontalAlignment | Should -Be 'right' + $sheet.Cells['A1'].Style.Font.Bold | Should -Be $true + $sheet.Cells['D2'].Style.Font.Bold | Should -Be $true + $sheet.Cells['E2'].style.numberformat.format | Should -Be '#,###' + $sheet.Column(3).style.numberformat.format | Should -Be '#,###' + $sheet.Column(4).style.numberformat.format | Should -Be '#,##0.0' + $sheet.ConditionalFormatting.Count | Should -Be 3 + $sheet.ConditionalFormatting[0].type | Should -Be 'Databar' + $sheet.ConditionalFormatting[0].Color.name | Should -Be 'ffff0000' + $sheet.ConditionalFormatting[0].Address.Address | Should -Be 'D2:D1048576' + $sheet.ConditionalFormatting[1].Style.Font.Strike | Should -Be $true + $sheet.ConditionalFormatting[1].type | Should -Be "TopPercent" + $sheet.ConditionalFormatting[2].type | Should -Be 'GreaterThan' + $sheet.ConditionalFormatting[2].Formula | Should -Be '104857600' + $sheet.ConditionalFormatting[2].Style.Font.Color.Color.Name | Should -Be 'ffff0000' } it "Created the named ranges " { - $sheet.Names.Count | Should be 7 - $sheet.Names[0].Start.Column | Should be 1 - $sheet.Names[0].Start.Row | Should be 2 - $sheet.Names[0].End.Row | Should be $sheet.Dimension.End.Row - $sheet.Names[0].Name | Should be $sheet.Cells['A1'].Value - $sheet.Names[6].Start.Column | Should be 7 - $sheet.Names[6].Start.Row | Should be 2 - $sheet.Names[6].End.Row | Should be $sheet.Dimension.End.Row - $sheet.Names[6].Name | Should be $sheet.Cells['G1'].Value + $sheet.Names.Count | Should -Be 7 + $sheet.Names[0].Start.Column | Should -Be 1 + $sheet.Names[0].Start.Row | Should -Be 2 + $sheet.Names[0].End.Row | Should -Be $sheet.Dimension.End.Row + $sheet.Names[0].Name | Should -Be $sheet.Cells['A1'].Value + $sheet.Names[6].Start.Column | Should -Be 7 + $sheet.Names[6].Start.Row | Should -Be 2 + $sheet.Names[6].End.Row | Should -Be $sheet.Dimension.End.Row + $sheet.Names[6].Name | Should -Be $sheet.Cells['G1'].Value } it "Froze the panes " { - $sheet.view.Panes.Count | Should be 3 + $sheet.view.Panes.Count | Should -Be 3 } $ptsheet1 = $Excel.Workbook.Worksheets["Pt_procs"] it "Created the pivot table " { - $ptsheet1 | Should not beNullOrEmpty - $ptsheet1.PivotTables[0].DataFields[0].Field.Name | Should be "Name" - $ptsheet1.PivotTables[0].DataFields[0].Function | Should be "Count" - $ptsheet1.PivotTables[0].RowFields[0].Name | Should be "Company" + $ptsheet1 | Should -Not -BeNullOrEmpty + $ptsheet1.PivotTables[0].DataFields[0].Field.Name | Should -Be "Name" + $ptsheet1.PivotTables[0].DataFields[0].Function | Should -Be "Count" + $ptsheet1.PivotTables[0].RowFields[0].Name | Should -Be "Company" $ptsheet1.PivotTables[0].CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref | Should be $sheet.Dimension.address } @@ -813,52 +813,52 @@ Describe ExportExcel { $ParamChk1 = (Get-command Add-ExcelChart ).Parameters.Keys.where({-not (Get-command New-ExcelChartDefinition).Parameters.ContainsKey($_) }) | Sort-Object $ParamChk2 = (Get-command New-ExcelChartDefinition).Parameters.Keys.where({-not (Get-command Add-ExcelChart ).Parameters.ContainsKey($_) }) it "Found the same parameters for Add-ExcelChart and New-ExcelChartDefinintion " { - $ParamChk1.count | Should be 3 - $ParamChk1[0] | Should be "PassThru" - $ParamChk1[1] | Should be "PivotTable" - $ParamChk1[2] | Should be "Worksheet" - $ParamChk2.count | Should be 1 - $ParamChk2[0] | Should be "Header" + $ParamChk1.count | Should -Be 3 + $ParamChk1[0] | Should -Be "PassThru" + $ParamChk1[1] | Should -Be "PivotTable" + $ParamChk1[2] | Should -Be "Worksheet" + $ParamChk2.count | Should -Be 1 + $ParamChk2[0] | Should -Be "Header" } #Test Invoke-Sum $data = Invoke-Sum (Get-Process) Company Handles, PM, VirtualMemorySize it "Used Invoke-Sum to create a data set " { - $data | Should not beNullOrEmpty - $data.count | Should beGreaterThan 1 - $data[1].Name | Should not beNullOrEmpty - $data[1].Handles | Should not beNullOrEmpty - $data[1].PM | Should not beNullOrEmpty - $data[1].VirtualMemorySize | Should not beNullOrEmpty + $data | Should -Not -BeNullOrEmpty + $data.count | Should -BeGreaterThan 1 + $data[1].Name | Should -Not -BeNullOrEmpty + $data[1].Handles | Should -Not -BeNullOrEmpty + $data[1].PM | Should -Not -BeNullOrEmpty + $data[1].VirtualMemorySize | Should -Not -BeNullOrEmpty } $c = New-ExcelChartDefinition -Title Stats -ChartType LineMarkersStacked -XRange "Processes[Name]" -YRange "Processes[PM]", "Processes[VirtualMemorySize]" -SeriesHeader 'PM', 'VMSize' it "Created the Excel chart definition " { - $c | Should not beNullOrEmpty - $c.ChartType.gettype().name | Should be "eChartType" - $c.ChartType.tostring() | Should be "LineMarkersStacked" - $c.yrange -is [array] | Should be $true - $c.yrange.count | Should be 2 - $c.yrange[0] | Should be "Processes[PM]" - $c.yrange[1] | Should be "Processes[VirtualMemorySize]" - $c.xrange | Should be "Processes[Name]" - $c.Title | Should be "Stats" - $c.Nolegend | Should not be $true - $c.ShowCategory | Should not be $true - $c.ShowPercent | Should not be $true + $c | Should -Not -BeNullOrEmpty + $c.ChartType.gettype().name | Should -Be "eChartType" + $c.ChartType.tostring() | Should -Be "LineMarkersStacked" + $c.yrange -is [array] | Should -Be $true + $c.yrange.count | Should -Be 2 + $c.yrange[0] | Should -Be "Processes[PM]" + $c.yrange[1] | Should -Be "Processes[VirtualMemorySize]" + $c.xrange | Should -Be "Processes[Name]" + $c.Title | Should -Be "Stats" + $c.Nolegend | Should -Not -Be $true + $c.ShowCategory | Should -Not -Be $true + $c.ShowPercent | Should -Not -Be $true } #Test creating a chart using -ExcelChartDefinition. $data | Export-Excel $path -AutoSize -TableName Processes -ExcelChartDefinition $c $excel = Open-ExcelPackage -Path $path $drawings = $excel.Workbook.Worksheets[1].drawings it "Used the Excel chart definition with Export-Excel " { - $drawings.count | Should be 1 - $drawings[0].ChartType | Should be "LineMarkersStacked" - $drawings[0].Series.count | Should be 2 - $drawings[0].Series[0].Series | Should be "'Sheet1'!Processes[PM]" - $drawings[0].Series[0].XSeries | Should be "'Sheet1'!Processes[Name]" - $drawings[0].Series[1].Series | Should be "'Sheet1'!Processes[VirtualMemorySize]" - $drawings[0].Series[1].XSeries | Should be "'Sheet1'!Processes[Name]" - $drawings[0].Title.text | Should be "Stats" + $drawings.count | Should -Be 1 + $drawings[0].ChartType | Should -Be "LineMarkersStacked" + $drawings[0].Series.count | Should -Be 2 + $drawings[0].Series[0].Series | Should -Be "'Sheet1'!Processes[PM]" + $drawings[0].Series[0].XSeries | Should -Be "'Sheet1'!Processes[Name]" + $drawings[0].Series[1].Series | Should -Be "'Sheet1'!Processes[VirtualMemorySize]" + $drawings[0].Series[1].XSeries | Should -Be "'Sheet1'!Processes[Name]" + $drawings[0].Title.text | Should -Be "Stats" } Close-ExcelPackage $excel } @@ -876,31 +876,31 @@ Describe ExportExcel { $ws = $Excel.Workbook.Worksheets["Sinx"] $d = $ws.Drawings[0] It "Controled the axes and title and legend of the chart " { - $d.XAxis.MaxValue | Should be 361 - $d.XAxis.MajorUnit | Should be 30 - $d.XAxis.MinorUnit | Should be 10 - $d.XAxis.Title.Text | Should be "degrees" - $d.XAxis.Title.Font.bold | Should be $true - $d.XAxis.Title.Font.Size | Should be 12 - $d.XAxis.MajorUnit | Should be 30 - $d.XAxis.MinorUnit | Should be 10 - $d.XAxis.MinValue | Should be 0 - $d.XAxis.MaxValue | Should be 361 - $d.YAxis.Format | Should be "0.00" - $d.Title.Text | Should be "Graph of Sine X" - $d.Title.Font.Bold | Should be $true - $d.Title.Font.Size | Should be 14 - $d.yAxis.MajorUnit | Should be 0.25 - $d.yAxis.MaxValue | Should be 1.25 - $d.yaxis.MinValue | Should be -1.25 - $d.Legend.Position.ToString() | Should be "Bottom" - $d.Legend.Font.Bold | Should be $true - $d.Legend.Font.Size | Should be 8 - $d.ChartType.tostring() | Should be "line" - $d.From.Column | Should be 2 + $d.XAxis.MaxValue | Should -Be 361 + $d.XAxis.MajorUnit | Should -Be 30 + $d.XAxis.MinorUnit | Should -Be 10 + $d.XAxis.Title.Text | Should -Be "degrees" + $d.XAxis.Title.Font.bold | Should -Be $true + $d.XAxis.Title.Font.Size | Should -Be 12 + $d.XAxis.MajorUnit | Should -Be 30 + $d.XAxis.MinorUnit | Should -Be 10 + $d.XAxis.MinValue | Should -Be 0 + $d.XAxis.MaxValue | Should -Be 361 + $d.YAxis.Format | Should -Be "0.00" + $d.Title.Text | Should -Be "Graph of Sine X" + $d.Title.Font.Bold | Should -Be $true + $d.Title.Font.Size | Should -Be 14 + $d.yAxis.MajorUnit | Should -Be 0.25 + $d.yAxis.MaxValue | Should -Be 1.25 + $d.yaxis.MinValue | Should -Be -1.25 + $d.Legend.Position.ToString() | Should -Be "Bottom" + $d.Legend.Font.Bold | Should -Be $true + $d.Legend.Font.Size | Should -Be 8 + $d.ChartType.tostring() | Should -Be "line" + $d.From.Column | Should -Be 2 } It "Appplied conditional formatting to the data " { - $ws.ConditionalFormatting[0].Formula | Should be "B1" + $ws.ConditionalFormatting[0].Formula | Should -Be "B1" } Close-ExcelPackage -ExcelPackage $excel -nosave } @@ -914,11 +914,11 @@ Describe ExportExcel { $ws = $excel.Sheet1 $d = $ws.Drawings[0] it "Created the chart " { - $d.Title.text | Should beNullOrEmpty - $d.ChartType | Should be "line" - $d.Series[0].Header | Should be "Sinx" - $d.Series[0].xSeries | Should be "'Sheet1'!A2:A362" - $d.Series[0].Series | Should be "'Sheet1'!B2:B362" + $d.Title.text | Should -BeNullOrEmpty + $d.ChartType | Should -Be "line" + $d.Series[0].Header | Should -Be "Sinx" + $d.Series[0].xSeries | Should -Be "'Sheet1'!A2:A362" + $d.Series[0].Series | Should -Be "'Sheet1'!B2:B362" } } @@ -932,14 +932,14 @@ Describe ExportExcel { $Cf = New-ConditionalFormattingIconSet -Range ($range -replace "^.*:","B2:") -ConditionalFormat ThreeIconSet -Reverse -IconType Flags $ct = New-ConditionalText -Text "Microsoft" -ConditionalTextColor ([System.Drawing.Color]::Red) -BackgroundColor([System.Drawing.Color]::AliceBlue) -ConditionalType ContainsText it "Created the Conditional formatting rules " { - $cf.Formatter | Should be "ThreeIconSet" - $cf.IconType | Should be "Flags" - $cf.Range | Should be ($range -replace "^.*:","B2:") - $cf.Reverse | Should be $true - $ct.BackgroundColor.Name | Should be "AliceBlue" - $ct.ConditionalTextColor.Name | Should be "Red" - $ct.ConditionalType | Should be "ContainsText" - $ct.Text | Should be "Microsoft" + $cf.Formatter | Should -Be "ThreeIconSet" + $cf.IconType | Should -Be "Flags" + $cf.Range | Should -Be ($range -replace "^.*:","B2:") + $cf.Reverse | Should -Be $true + $ct.BackgroundColor.Name | Should -Be "AliceBlue" + $ct.ConditionalTextColor.Name | Should -Be "Red" + $ct.ConditionalType | Should -Be "ContainsText" + $ct.Text | Should -Be "Microsoft" } #Test -ConditionalFormat & -ConditionalText Export-Excel -Path $path -ConditionalFormat $cf -ConditionalText $ct @@ -948,15 +948,15 @@ Describe ExportExcel { $chart = $excel.Workbook.Worksheets["sheet1"].Drawings[0] $cFmt = $excel.Workbook.Worksheets["sheet1"].ConditionalFormatting it "Created the chart with the right series " { - $chart.ChartType | Should be "PieExploded3D" - $chart.series.series | Should be "'Sheet1'!B1:B$rows" #would be B2 and A2 if we had a header. - $chart.series.Xseries | Should be "'Sheet1'!A1:A$rows" - $chart.DataLabel.ShowPercent | Should be $true + $chart.ChartType | Should -Be "PieExploded3D" + $chart.series.series | Should -Be "'Sheet1'!B1:B$rows" #would be B2 and A2 if we had a header. + $chart.series.Xseries | Should -Be "'Sheet1'!A1:A$rows" + $chart.DataLabel.ShowPercent | Should -Be $true } it "Created two Conditional formatting rules " { - $cFmt.Count | Should be $true - $cFmt.Where({$_.type -eq "ContainsText"}) | Should not beNullOrEmpty - $cFmt.Where({$_.type -eq "ThreeIconSet"}) | Should not beNullOrEmpty + $cFmt.Count | Should -Be $true + $cFmt.Where({$_.type -eq "ContainsText"}) | Should -Not -BeNullOrEmpty + $cFmt.Where({$_.type -eq "ThreeIconSet"}) | Should -Not -BeNullOrEmpty } } @@ -986,18 +986,18 @@ Describe ExportExcel { $excel = Open-ExcelPackage -Path $path $ws = $excel.Workbook.Worksheets[1] it "Created 3 tables " { - $ws.tables.count | Should be 3 + $ws.tables.count | Should -Be 3 } it "Created the FileSize table in the right place with the right size and style " { - $ws.Tables["FileSize"].Address.Address | Should be "G2:H16" #Insert at row 2, Column 7, 14 rows x 2 columns of data - $ws.Tables["FileSize"].StyleName | Should be "TableStyleMedium2" + $ws.Tables["FileSize"].Address.Address | Should -Be "G2:H16" #Insert at row 2, Column 7, 14 rows x 2 columns of data + $ws.Tables["FileSize"].StyleName | Should -Be "TableStyleMedium2" } it "Created the ExtSize table in the right place with the right size and style " { - $ws.Tables["ExtSize"].Address.Address | Should be "A2:B14" #tile, then 12 rows x 2 columns of data - $ws.Tables["ExtSize"].StyleName | Should be "TableStyleMedium6" + $ws.Tables["ExtSize"].Address.Address | should -be "A2:B14" #tile, then 12 rows x 2 columns of data + $ws.Tables["ExtSize"].StyleName | should -be "TableStyleMedium6" } it "Created the ExtCount table in the right place with the right size " { - $ws.Tables["ExtCount"].Address.Address | Should be "D2:E12" #title, then 10 rows x 2 columns of data + $ws.Tables["ExtCount"].Address.Address | Should -Be "D2:E12" #title, then 10 rows x 2 columns of data } } @@ -1010,15 +1010,15 @@ Describe ExportExcel { $ExcelPackage = $Processes | Export-Excel -Path $Path -PassThru $Worksheet = $ExcelPackage.Workbook.Worksheets[1] - $ExcelPackage.File | Should Be $Path - $Worksheet.Cells['A1'].Value | Should Be 'Name' - $Worksheet.Tables | Should BeNullOrEmpty - $Worksheet.AutoFilterAddress | Should BeNullOrEmpty + $ExcelPackage.File | Should -Be $Path + $Worksheet.Cells['A1'].Value | Should -Be 'Name' + $Worksheet.Tables | Should -BeNullOrEmpty + $Worksheet.AutoFilterAddress | Should -BeNullOrEmpty } it "throws when the ExcelPackage is specified with either -path or -Now".PadRight(87) { $ExcelPackage = Export-Excel -Path $Path -PassThru - {Export-Excel -ExcelPackage $ExcelPackage -Path $Path} | Should Throw 'Parameter set cannot be resolved using the specified named parameters' - {Export-Excel -ExcelPackage $ExcelPackage -Now} | Should Throw 'Parameter set cannot be resolved using the specified named parameters' + {Export-Excel -ExcelPackage $ExcelPackage -Path $Path} | Should -Throw 'Parameter set cannot be resolved using the specified named parameters' + {Export-Excel -ExcelPackage $ExcelPackage -Now} | Should -Throw 'Parameter set cannot be resolved using the specified named parameters' $Processes | Export-Excel -ExcelPackage $ExcelPackage Remove-Item -Path $Path @@ -1027,36 +1027,36 @@ Describe ExportExcel { $ExcelPackage = Export-Excel -Path $Path -PassThru -TableName 'Data' -AutoFilter $Worksheet = $ExcelPackage.Workbook.Worksheets[1] - $Worksheet.Tables[0].Name | Should Be 'Data' - $Worksheet.AutoFilterAddress | Should BeNullOrEmpty + $Worksheet.Tables[0].Name | Should -Be 'Data' + $Worksheet.AutoFilterAddress | Should -BeNullOrEmpty } it "Default Set with Path and TableName with generated name".PadRight(87) { $ExcelPackage = $Processes | Export-Excel -Path $Path -PassThru -TableName '' $Worksheet = $ExcelPackage.Workbook.Worksheets[1] - $ExcelPackage.File | Should Be $Path - $Worksheet.Tables[0].Name | Should Be 'Table1' + $ExcelPackage.File | Should -Be $Path + $Worksheet.Tables[0].Name | Should -Be 'Table1' } it "Now will use temp Path, set TableName with generated name and AutoSize".PadRight(87) { $ExcelPackage = $Processes | Export-Excel -Now -PassThru $Worksheet = $ExcelPackage.Workbook.Worksheets[1] - $ExcelPackage.File.FullName | Should BeLike ([IO.Path]::GetTempPath() + '*') - $Worksheet.Tables[0].Name | Should Be 'Table1' - $Worksheet.AutoFilterAddress | Should BeNullOrEmpty + $ExcelPackage.File.FullName | Should -BeLike ([IO.Path]::GetTempPath() + '*') + $Worksheet.Tables[0].Name | Should -Be 'Table1' + $Worksheet.AutoFilterAddress | Should -BeNullOrEmpty if ($isWindows) { - $Worksheet.Column(5).Width | Should BeGreaterThan 9.5 + $Worksheet.Column(5).Width | Should -BeGreaterThan 9.5 } } it "Now allows override of Path and TableName".PadRight(87) { $ExcelPackage = $Processes | Export-Excel -Now -PassThru -Path $Path -TableName:$false $Worksheet = $ExcelPackage.Workbook.Worksheets[1] - $ExcelPackage.File | Should Be $Path - $Worksheet.Tables | Should BeNullOrEmpty - $Worksheet.AutoFilterAddress | Should BeNullOrEmpty + $ExcelPackage.File | Should -Be $Path + $Worksheet.Tables | Should -BeNullOrEmpty + $Worksheet.AutoFilterAddress | Should -BeNullOrEmpty if ($isWindows) { - $Worksheet.Column(5).Width | Should BeGreaterThan 9.5 + $Worksheet.Column(5).Width | Should -BeGreaterThan 9.5 } } <# Mock looks unreliable need to check @@ -1074,18 +1074,18 @@ Describe ExportExcel { $ExcelPackage = $Processes | Export-Excel -Now -PassThru -AutoSize:$false -AutoFilter $Worksheet = $ExcelPackage.Workbook.Worksheets[1] - $Worksheet.Tables | Should BeNullOrEmpty - $Worksheet.AutoFilterAddress | Should Not BeNullOrEmpty - [math]::Round($Worksheet.Column(5).Width, 2) | Should Be 9.14 + $Worksheet.Tables | Should -BeNullOrEmpty + $Worksheet.AutoFilterAddress | Should -Not -BeNullOrEmpty + [math]::Round($Worksheet.Column(5).Width, 2) | Should -Be 9.14 } it "Now allows to set TableName".PadRight(87) { $ExcelPackage = $Processes | Export-Excel -Now -PassThru -TableName 'Data' $Worksheet = $ExcelPackage.Workbook.Worksheets[1] - $Worksheet.Tables[0].Name | Should Be 'Data' - $Worksheet.AutoFilterAddress | Should BeNullOrEmpty + $Worksheet.Tables[0].Name | Should -Be 'Data' + $Worksheet.AutoFilterAddress | Should -BeNullOrEmpty if ($isWindows) { - $Worksheet.Column(5).Width | Should BeGreaterThan 9.5 + $Worksheet.Column(5).Width | Should -BeGreaterThan 9.5 } } } diff --git a/__tests__/ExtraLongCmd.tests.ps1 b/__tests__/ExtraLongCmd.tests.ps1 index 8f5eeaa..155c4d7 100644 --- a/__tests__/ExtraLongCmd.tests.ps1 +++ b/__tests__/ExtraLongCmd.tests.ps1 @@ -22,45 +22,45 @@ Apple, New York, 1200,700 $ws2 = $excel.Workbook.Worksheets[2] Context "Data Page" { It "Inserted the data and created the table " { - $ws1.Tables[0] | Should not beNullOrEmpty - $ws1.Tables[0].Address.Address | Should be "A1:D7" - $ws1.Tables[0].StyleName | Should be "TableStyleMedium13" + $ws1.Tables[0] | Should -Not -BeNullOrEmpty + $ws1.Tables[0].Address.Address | Should -Be "A1:D7" + $ws1.Tables[0].StyleName | Should -Be "TableStyleMedium13" } It "Applied conditional formatting " { - $ws1.ConditionalFormatting[0] | Should not beNullOrEmpty - $ws1.ConditionalFormatting[0].type.ToString() | Should be "DataBar" - $ws1.ConditionalFormatting[0].Color.G | Should beGreaterThan 100 - $ws1.ConditionalFormatting[0].Color.R | Should beLessThan 100 - $ws1.ConditionalFormatting[0].Address.Address | Should be "C2:C7" + $ws1.ConditionalFormatting[0] | Should -Not -BeNullOrEmpty + $ws1.ConditionalFormatting[0].type.ToString() | Should -Be "DataBar" + $ws1.ConditionalFormatting[0].Color.G | Should -BeGreaterThan 100 + $ws1.ConditionalFormatting[0].Color.R | Should -BeLessThan 100 + $ws1.ConditionalFormatting[0].Address.Address | Should -Be "C2:C7" } It "Added the chart " { - $ws1.Drawings[0] | Should not beNullOrEmpty - $ws1.Drawings[0].ChartType.ToString() | Should be "DoughNut" - $ws1.Drawings[0].Series[0].Series | Should be "'Sheet1'!C2:C7" + $ws1.Drawings[0] | Should -Not -BeNullOrEmpty + $ws1.Drawings[0].ChartType.ToString() | Should -Be "DoughNut" + $ws1.Drawings[0].Series[0].Series | Should -Be "'Sheet1'!C2:C7" } } Context "PivotTable" { it "Created the PivotTable on a new page " { - $ws2 | Should not beNullOrEmpty - $ws2.PivotTables[0] | Should not beNullOrEmpty - $ws2.PivotTables[0].Fields.Count | Should be 4 - $ws2.PivotTables[0].DataFields[0].Format | Should be "$#,##0.00" - $ws2.PivotTables[0].RowFields[0].Name | Should be "City" - $ws2.PivotTables[0].ColumnFields[0].Name | Should be "Product" - $ws2.PivotTables[0].RowGrandTotals | Should be $true - $ws2.PivotTables[0].ColumGrandTotals | Should be $true #Epplus's mis-spelling of column not mine + $ws2 | Should -Not -BeNullOrEmpty + $ws2.PivotTables[0] | Should -Not -BeNullOrEmpty + $ws2.PivotTables[0].Fields.Count | Should -Be 4 + $ws2.PivotTables[0].DataFields[0].Format | Should -Be "$#,##0.00" + $ws2.PivotTables[0].RowFields[0].Name | Should -Be "City" + $ws2.PivotTables[0].ColumnFields[0].Name | Should -Be "Product" + $ws2.PivotTables[0].RowGrandTotals | Should -Be $true + $ws2.PivotTables[0].ColumGrandTotals | Should -Be $true #Epplus's mis-spelling of column not mine } it "Made the PivotTable page active " { Set-ItResult -Pending -Because "Bug in EPPLus 4.5" - $ws2.View.TabSelected | Should be $true + $ws2.View.TabSelected | Should -Be $true } it "Created the Pivot Chart " { - $ws2.Drawings[0] | Should not beNullOrEmpty - $ws2.Drawings[0].ChartType.ToString() | Should be ColumnClustered - $ws2.Drawings[0].YAxis.MajorUnit | Should be 500 - $ws2.Drawings[0].YAxis.MinorUnit | Should be 100 - $ws2.Drawings[0].YAxis.Format | Should be "$#,##0" - $ws2.Drawings[0].Legend.Position.ToString() | Should be "Bottom" + $ws2.Drawings[0] | Should -Not -BeNullOrEmpty + $ws2.Drawings[0].ChartType.ToString() | Should -Be ColumnClustered + $ws2.Drawings[0].YAxis.MajorUnit | Should -Be 500 + $ws2.Drawings[0].YAxis.MinorUnit | Should -Be 100 + $ws2.Drawings[0].YAxis.Format | Should -Be "$#,##0" + $ws2.Drawings[0].Legend.Position.ToString() | Should -Be "Bottom" } } diff --git a/__tests__/First10Races.tests.ps1 b/__tests__/First10Races.tests.ps1 index 995fe41..e014c4c 100644 --- a/__tests__/First10Races.tests.ps1 +++ b/__tests__/First10Races.tests.ps1 @@ -62,84 +62,84 @@ Describe "Creating small named ranges with hyperlinks" { } Context "Creating hyperlinks" { it "Put the data into the sheet and created the expected named ranges " { - $sheet.Dimension.Rows | should be $expectedRows - $sheet.Dimension.Columns | should be $columns - $sheet.Names.Count | should be ($columns + $results.Count) - $sheet.Names[$results[0].Name] | should not benullorEmpty - $sheet.Names[$results[-1].Name] | should not benullorEmpty + $sheet.Dimension.Rows | Should -Be $expectedRows + $sheet.Dimension.Columns | Should -Be $columns + $sheet.Names.Count | Should -Be ($columns + $results.Count) + $sheet.Names[$results[0].Name] | Should -Not -BenullorEmpty + $sheet.Names[$results[-1].Name] | Should -Not -BenullorEmpty } it "Added hyperlinks to the named ranges " { - $sheet.cells["a1"].Hyperlink.Display | should match $results[0].Name - $sheet.cells["a1"].Hyperlink.ReferenceAddress | should match $results[0].Name + $sheet.cells["a1"].Hyperlink.Display | Should -Match $results[0].Name + $sheet.cells["a1"].Hyperlink.ReferenceAddress | Should -Match $results[0].Name } } Context "Adding calculated column" { It "Populated the cells with the right heading and formulas " { - $sheet.Cells[( $results.Count), $columns] | Should benullorEmpty - $sheet.Cells[(1 + $results.Count), $columns].Value | Should be "PlacesGained/Lost" - $sheet.Cells[(2 + $results.Count), $columns].Formula | should be "GridPosition-FinishPosition" - $sheet.Names["PlacesGained_Lost"] | should not benullorEmpty + $sheet.Cells[( $results.Count), $columns] | Should -BenullorEmpty + $sheet.Cells[(1 + $results.Count), $columns].Value | Should -Be "PlacesGained/Lost" + $sheet.Cells[(2 + $results.Count), $columns].Formula | Should -Be "GridPosition-FinishPosition" + $sheet.Names["PlacesGained_Lost"] | Should -Not -BenullorEmpty } It "Performed the calculation " { $placesMade = $Sheet.Cells[(2 + $results.Count), 5].value - $Sheet.Cells[(2 + $results.Count), 3].value - $sheet.Cells[(2 + $results.Count), $columns].value | Should be $placesmade + $sheet.Cells[(2 + $results.Count), $columns].value | Should -Be $placesmade } It "Applied ConditionalFormatting, including StopIfTrue, Priority " { - $sheet.ConditionalFormatting[0].Address.Start.Column | should be $columns - $sheet.ConditionalFormatting[0].Address.End.Column | should be $columns - $sheet.ConditionalFormatting[0].Address.End.Row | should be $expectedRows - $sheet.ConditionalFormatting[0].Address.Start.Row | should be ($results.Count + 1) - $sheet.ConditionalFormatting[0].Icon3.Type.ToString() | Should be "Num" - $sheet.ConditionalFormatting[0].Icon3.Value | Should be 1 - $sheet.ConditionalFormatting[1].Priority | Should be 1 - $sheet.ConditionalFormatting[1].StopIfTrue | Should be $true + $sheet.ConditionalFormatting[0].Address.Start.Column | Should -Be $columns + $sheet.ConditionalFormatting[0].Address.End.Column | Should -Be $columns + $sheet.ConditionalFormatting[0].Address.End.Row | Should -Be $expectedRows + $sheet.ConditionalFormatting[0].Address.Start.Row | Should -Be ($results.Count + 1) + $sheet.ConditionalFormatting[0].Icon3.Type.ToString() | Should -Be "Num" + $sheet.ConditionalFormatting[0].Icon3.Value | Should -Be 1 + $sheet.ConditionalFormatting[1].Priority | Should -Be 1 + $sheet.ConditionalFormatting[1].StopIfTrue | Should -Be $true } It "Applied ConditionalFormatting, including Reverse " { Set-ItResult -Pending -Because "Bug in EPPLus 4.5" - $sheet.ConditionalFormatting[3].LowValue.Color.R | Should begreaterThan 180 - $sheet.ConditionalFormatting[3].LowValue.Color.G | Should beLessThan 128 - $sheet.ConditionalFormatting[3].HighValue.Color.R | Should beLessThan 128 - $sheet.ConditionalFormatting[3].HighValue.Color.G | Should begreaterThan 180 + $sheet.ConditionalFormatting[3].LowValue.Color.R | Should -BegreaterThan 180 + $sheet.ConditionalFormatting[3].LowValue.Color.G | Should -BeLessThan 128 + $sheet.ConditionalFormatting[3].HighValue.Color.R | Should -BeLessThan 128 + $sheet.ConditionalFormatting[3].HighValue.Color.G | Should -BegreaterThan 180 } } Context "Adding a table" { it "Created a table " { - $sheet.tables[0] | Should not beNullOrEmpty - $sheet.tables[0].Address.Start.Column | should be 1 - $sheet.tables[0].Address.End.Column | should be $columns - $sheet.tables[0].Address.Start.row | should be ($results.Count + 1) - $sheet.Tables[0].Address.End.Row | should be $expectedRows - $sheet.Tables[0].StyleName | should be "TableStyleLight4" - $sheet.Tables[0].ShowColumnStripes | should be $true - $sheet.Tables[0].ShowRowStripes | should not be $true + $sheet.tables[0] | Should -Not -BeNullOrEmpty + $sheet.tables[0].Address.Start.Column | Should -Be 1 + $sheet.tables[0].Address.End.Column | Should -Be $columns + $sheet.tables[0].Address.Start.row | Should -Be ($results.Count + 1) + $sheet.Tables[0].Address.End.Row | Should -Be $expectedRows + $sheet.Tables[0].StyleName | Should -Be "TableStyleLight4" + $sheet.Tables[0].ShowColumnStripes | Should -Be $true + $sheet.Tables[0].ShowRowStripes | Should -Not -Be $true } } Context "Adding Pivot tables" { it "Added a worksheet with a pivot table grouped by date " { - $excel.Points1 | should not beNullOrEmpty - $excel.Points1.PivotTables.Count | should be 1 + $excel.Points1 | Should -Not -BeNullOrEmpty + $excel.Points1.PivotTables.Count | Should -Be 1 $pt = $excel.Points1.PivotTables[0] - $pt.RowFields.Count | should be 3 - $pt.RowFields[0].name | should be "Driver" - $pt.RowFields[0].Grouping | should benullorEmpty - $pt.RowFields[1].name | should be "years" - $pt.RowFields[1].Grouping | should not benullorEmpty - $pt.RowFields[2].name | should be "date" - $pt.RowFields[2].Grouping | should not benullorEmpty + $pt.RowFields.Count | Should -Be 3 + $pt.RowFields[0].name | Should -Be "Driver" + $pt.RowFields[0].Grouping | Should -BenullorEmpty + $pt.RowFields[1].name | Should -Be "years" + $pt.RowFields[1].Grouping | Should -Not -BenullorEmpty + $pt.RowFields[2].name | Should -Be "date" + $pt.RowFields[2].Grouping | Should -Not -BenullorEmpty } it "Added a worksheet with a pivot table grouped by Number " { - $excel.Places1 | should not beNullOrEmpty - $excel.Places1.PivotTables.Count | should be 1 + $excel.Places1 | Should -Not -BeNullOrEmpty + $excel.Places1.PivotTables.Count | Should -Be 1 $pt = $excel.Places1.PivotTables[0] - $pt.RowFields.Count | should be 2 - $pt.RowFields[0].name | should be "Driver" - $pt.RowFields[0].Grouping | should benullorEmpty - $pt.RowFields[0].SubTotalFunctions.ToString() | should be "None" - $pt.RowFields[1].name | should be "FinishPosition" - $pt.RowFields[1].Grouping | should not benullorEmpty - $pt.RowFields[1].Grouping.Start | should be 1 - $pt.RowFields[1].Grouping.End | should be 25 - $pt.RowFields[1].Grouping.Interval | should be 3 + $pt.RowFields.Count | Should -Be 2 + $pt.RowFields[0].name | Should -Be "Driver" + $pt.RowFields[0].Grouping | Should -BenullorEmpty + $pt.RowFields[0].SubTotalFunctions.ToString() | Should -Be "None" + $pt.RowFields[1].name | Should -Be "FinishPosition" + $pt.RowFields[1].Grouping | Should -Not -BenullorEmpty + $pt.RowFields[1].Grouping.Start | Should -Be 1 + $pt.RowFields[1].Grouping.End | Should -Be 25 + $pt.RowFields[1].Grouping.Interval | Should -Be 3 } } } \ No newline at end of file diff --git a/__tests__/FunctionAlias.tests.ps1 b/__tests__/FunctionAlias.tests.ps1 index 2a813a4..0fc954c 100644 --- a/__tests__/FunctionAlias.tests.ps1 +++ b/__tests__/FunctionAlias.tests.ps1 @@ -6,23 +6,23 @@ if (-not (Get-command Import-Excel -ErrorAction SilentlyContinue)) { Describe "Check if Function aliases exist" { It "Set-Column should exist".PadRight(90) { - ${Alias:Set-Column} | Should Not BeNullOrEmpty + ${Alias:Set-Column} | Should -Not -BeNullOrEmpty } It "Set-Row should exist".PadRight(90) { - ${Alias:Set-Row} | Should Not BeNullOrEmpty + ${Alias:Set-Row} | Should -Not -BeNullOrEmpty } It "Set-Format should exist".PadRight(90) { - ${Alias:Set-Format} | Should Not BeNullOrEmpty + ${Alias:Set-Format} | Should -Not -BeNullOrEmpty } <#It "Merge-MulipleSheets should exist" { - Get-Command Merge-MulipleSheets | Should Not Be $null + Get-Command Merge-MulipleSheets | Should -Not -Be $null } #> It "New-ExcelChart should exist".PadRight(90) { - ${Alias:New-ExcelChart} | Should Not BeNullOrEmpty + ${Alias:New-ExcelChart} | Should -Not -BeNullOrEmpty } } \ No newline at end of file diff --git a/__tests__/Get-ExcelColumnName.Test.ps1 b/__tests__/Get-ExcelColumnName.Test.ps1 index bb09628..070650e 100644 --- a/__tests__/Get-ExcelColumnName.Test.ps1 +++ b/__tests__/Get-ExcelColumnName.Test.ps1 @@ -17,13 +17,13 @@ $map = @{ 16384 = 'XFD' } -(Get-ExcelColumnName 26).columnName | Should be 'Z' -(Get-ExcelColumnName 27).columnName | Should be 'AA' -(Get-ExcelColumnName 28).columnNamee | Should be 'AB' -(Get-ExcelColumnName 30).columnName | Should be 'AD' -(Get-ExcelColumnName 48).columnName | Should be 'AV' +(Get-ExcelColumnName 26).columnName | Should -Be 'Z' +(Get-ExcelColumnName 27).columnName | Should -Be 'AA' +(Get-ExcelColumnName 28).columnNamee | Should -Be 'AB' +(Get-ExcelColumnName 30).columnName | Should -Be 'AD' +(Get-ExcelColumnName 48).columnName | Should -Be 'AV' 1..16 | ForEach-Object { $number = $_ * 1024 - (Get-ExcelColumnName $number).columnName | Should be $map.$number + (Get-ExcelColumnName $number).columnName | Should -Be $map.$number } diff --git a/__tests__/ImportExcelHeaderName.tests.ps1 b/__tests__/ImportExcelHeaderName.tests.ps1 index cff85bc..1d83429 100644 --- a/__tests__/ImportExcelHeaderName.tests.ps1 +++ b/__tests__/ImportExcelHeaderName.tests.ps1 @@ -25,15 +25,15 @@ Describe "Import-Excel on a sheet with no headings" { $actualNames = $actual[0].psobject.properties.name - $actualNames.Count | Should Be 3 - $actualNames[0] | Should BeExactly 'A' - $actualNames[1] | Should BeExactly 'B' - $actualNames[2] | Should BeExactly 'C' + $actualNames.Count | Should -Be 3 + $actualNames[0] | Should -BeExactly 'A' + $actualNames[1] | Should -BeExactly 'B' + $actualNames[2] | Should -BeExactly 'C' - $actual.Count | Should Be 2 - $actual[0].A | Should BeExactly 'D' - $actual[0].B | Should BeExactly 'E' - $actual[0].C | Should BeExactly 'F' + $actual.Count | Should -Be 2 + $actual[0].A | Should -BeExactly 'D' + $actual[0].B | Should -BeExactly 'E' + $actual[0].C | Should -BeExactly 'F' } It "Import-Excel -NoHeader should have this shape" { @@ -41,12 +41,12 @@ Describe "Import-Excel on a sheet with no headings" { $actualNames = $actual[0].psobject.properties.name - $actualNames.Count | Should Be 3 - $actualNames[0] | Should BeExactly 'P1' - $actualNames[1] | Should BeExactly 'P2' - $actualNames[2] | Should BeExactly 'P3' + $actualNames.Count | Should -Be 3 + $actualNames[0] | Should -BeExactly 'P1' + $actualNames[1] | Should -BeExactly 'P2' + $actualNames[2] | Should -BeExactly 'P3' - $actual.Count | Should Be 3 + $actual.Count | Should -Be 3 } It "Import-Excel -HeaderName should have this shape" { @@ -54,20 +54,20 @@ Describe "Import-Excel on a sheet with no headings" { $actualNames = $actual[0].psobject.properties.name - $actualNames.Count | Should Be 3 - $actualNames[0] | Should BeExactly 'Q' - $actualNames[1] | Should BeExactly 'R' - $actualNames[2] | Should BeExactly 'S' + $actualNames.Count | Should -Be 3 + $actualNames[0] | Should -BeExactly 'Q' + $actualNames[1] | Should -BeExactly 'R' + $actualNames[2] | Should -BeExactly 'S' - $actual.Count | Should Be 3 + $actual.Count | Should -Be 3 - $actual[0].Q | Should BeExactly 'A' - $actual[0].R | Should BeExactly 'B' - $actual[0].S | Should BeExactly 'C' + $actual[0].Q | Should -BeExactly 'A' + $actual[0].R | Should -BeExactly 'B' + $actual[0].S | Should -BeExactly 'C' - $actual[1].Q | Should BeExactly 'D' - $actual[1].R | Should BeExactly 'E' - $actual[1].S | Should BeExactly 'F' + $actual[1].Q | Should -BeExactly 'D' + $actual[1].R | Should -BeExactly 'E' + $actual[1].S | Should -BeExactly 'F' } It "Should work with StartRow" { @@ -75,20 +75,20 @@ Describe "Import-Excel on a sheet with no headings" { $actualNames = $actual[0].psobject.properties.name - $actualNames.Count | Should Be 3 - $actualNames[0] | Should BeExactly 'Q' - $actualNames[1] | Should BeExactly 'R' - $actualNames[2] | Should BeExactly 'S' + $actualNames.Count | Should -Be 3 + $actualNames[0] | Should -BeExactly 'Q' + $actualNames[1] | Should -BeExactly 'R' + $actualNames[2] | Should -BeExactly 'S' - $actual.Count | Should Be 2 + $actual.Count | Should -Be 2 - $actual[0].Q | Should BeExactly 'D' - $actual[0].R | Should BeExactly 'E' - $actual[0].S | Should BeExactly 'F' + $actual[0].Q | Should -BeExactly 'D' + $actual[0].R | Should -BeExactly 'E' + $actual[0].S | Should -BeExactly 'F' - $actual[1].Q | Should BeExactly 'G' - $actual[1].R | Should BeExactly 'H' - $actual[1].S | Should BeExactly 'I' + $actual[1].Q | Should -BeExactly 'G' + $actual[1].R | Should -BeExactly 'H' + $actual[1].S | Should -BeExactly 'I' } @@ -96,64 +96,64 @@ Describe "Import-Excel on a sheet with no headings" { $actual = @(Import-Excel $xlfile -NoHeader) $actualNames = $actual[0].psobject.properties.name - $actualNames.Count | Should Be 3 - $actualNames[0] | Should BeExactly 'P1' - $actualNames[1] | Should BeExactly 'P2' - $actualNames[2] | Should BeExactly 'P3' + $actualNames.Count | Should -Be 3 + $actualNames[0] | Should -BeExactly 'P1' + $actualNames[1] | Should -BeExactly 'P2' + $actualNames[2] | Should -BeExactly 'P3' - $actual.Count | Should Be 3 + $actual.Count | Should -Be 3 - $actual[0].P1 | Should BeExactly 'A' - $actual[0].P2 | Should BeExactly 'B' - $actual[0].P3 | Should BeExactly 'C' + $actual[0].P1 | Should -BeExactly 'A' + $actual[0].P2 | Should -BeExactly 'B' + $actual[0].P3 | Should -BeExactly 'C' - $actual[1].P1 | Should BeExactly 'D' - $actual[1].P2 | Should BeExactly 'E' - $actual[1].P3 | Should BeExactly 'F' + $actual[1].P1 | Should -BeExactly 'D' + $actual[1].P2 | Should -BeExactly 'E' + $actual[1].P3 | Should -BeExactly 'F' - $actual[2].P1 | Should BeExactly 'G' - $actual[2].P2 | Should BeExactly 'H' - $actual[2].P3 | Should BeExactly 'I' + $actual[2].P1 | Should -BeExactly 'G' + $actual[2].P2 | Should -BeExactly 'H' + $actual[2].P3 | Should -BeExactly 'I' } It "Should work with -NoHeader -DataOnly" { $actual = @(Import-Excel $xlfile -NoHeader -DataOnly) $actualNames = $actual[0].psobject.properties.name - $actualNames.Count | Should Be 3 - $actualNames[0] | Should BeExactly 'P1' - $actualNames[1] | Should BeExactly 'P2' - $actualNames[2] | Should BeExactly 'P3' + $actualNames.Count | Should -Be 3 + $actualNames[0] | Should -BeExactly 'P1' + $actualNames[1] | Should -BeExactly 'P2' + $actualNames[2] | Should -BeExactly 'P3' - $actual.Count | Should Be 3 + $actual.Count | Should -Be 3 - $actual[0].P1 | Should BeExactly 'A' - $actual[0].P2 | Should BeExactly 'B' - $actual[0].P3 | Should BeExactly 'C' + $actual[0].P1 | Should -BeExactly 'A' + $actual[0].P2 | Should -BeExactly 'B' + $actual[0].P3 | Should -BeExactly 'C' - $actual[1].P1 | Should BeExactly 'D' - $actual[1].P2 | Should BeExactly 'E' - $actual[1].P3 | Should BeExactly 'F' + $actual[1].P1 | Should -BeExactly 'D' + $actual[1].P2 | Should -BeExactly 'E' + $actual[1].P3 | Should -BeExactly 'F' - $actual[2].P1 | Should BeExactly 'G' - $actual[2].P2 | Should BeExactly 'H' - $actual[2].P3 | Should BeExactly 'I' + $actual[2].P1 | Should -BeExactly 'G' + $actual[2].P2 | Should -BeExactly 'H' + $actual[2].P3 | Should -BeExactly 'I' } It "Should work with -HeaderName -DataOnly -StartRow" { $actual = @(Import-Excel $xlfile -HeaderName 'Q', 'R', 'S' -DataOnly -StartRow 2) $actualNames = $actual[0].psobject.properties.name - $actualNames.Count | Should Be 3 - $actualNames[0] | Should BeExactly 'Q' - $actualNames[1] | Should BeExactly 'R' - $actualNames[2] | Should BeExactly 'S' + $actualNames.Count | Should -Be 3 + $actualNames[0] | Should -BeExactly 'Q' + $actualNames[1] | Should -BeExactly 'R' + $actualNames[2] | Should -BeExactly 'S' - $actual.Count | Should Be 1 + $actual.Count | Should -Be 1 - $actual[0].Q | Should BeExactly 'G' - $actual[0].R | Should BeExactly 'H' - $actual[0].S | Should BeExactly 'I' + $actual[0].Q | Should -BeExactly 'G' + $actual[0].R | Should -BeExactly 'H' + $actual[0].S | Should -BeExactly 'I' } It "Should" { @@ -180,17 +180,17 @@ Describe "Import-Excel on a sheet with no headings" { $actual = @(Import-Excel -Path $xlfile -DataOnly -HeaderName 'FirstName', 'SecondName', 'City' -StartRow 2) $actualNames = $actual[0].psobject.properties.name - $actualNames.Count | Should Be 3 - $actualNames[0] | Should BeExactly 'FirstName' - $actualNames[1] | Should BeExactly 'SecondName' - $actualNames[2] | Should BeExactly 'City' + $actualNames.Count | Should -Be 3 + $actualNames[0] | Should -BeExactly 'FirstName' + $actualNames[1] | Should -BeExactly 'SecondName' + $actualNames[2] | Should -BeExactly 'City' - $actual.Count | Should Be 1 + $actual.Count | Should -Be 1 # Looks like -DataOnly does not handle empty columns - # $actual[0].FirstName | Should BeExactly 'Jean-Claude' - # $actual[0].SecondName | Should BeExactly 'Vandamme' - # $actual[0].City | Should BeExactly 'Brussels' + # $actual[0].FirstName | Should -BeExactly 'Jean-Claude' + # $actual[0].SecondName | Should -BeExactly 'Vandamme' + # $actual[0].City | Should -BeExactly 'Brussels' } } \ No newline at end of file diff --git a/__tests__/ImportExcelTests/Simple.tests.ps1 b/__tests__/ImportExcelTests/Simple.tests.ps1 index abb229c..949889b 100644 --- a/__tests__/ImportExcelTests/Simple.tests.ps1 +++ b/__tests__/ImportExcelTests/Simple.tests.ps1 @@ -12,19 +12,19 @@ Describe "Tests" { } It "Should have a valid manifest".PadRight(90){ {try {Test-ModuleManifest -Path $PSScriptRoot\..\..\ImportExcel.psd1 -ErrorAction stop} - catch {throw} } | should not throw + catch {throw} } | Should -Not -Throw } It "Should have two items in the imported simple data".PadRight(90) { - $data.count | Should be 2 + $data.count | Should -Be 2 } It "Should have items a and b in the imported simple data".PadRight(90) { - $data[0].p1 | Should be "a" - $data[1].p1 | Should be "b" + $data[0].p1 | Should -Be "a" + $data[1].p1 | Should -Be "b" } It "Should read the simple xlsx in < 2100 milliseconds".PadRight(90) { - $timer.TotalMilliseconds | should BeLessThan 2100 + $timer.TotalMilliseconds | Should -BeLessThan 2100 } It "Should read larger xlsx, 4k rows 1 col < 3000 milliseconds".PadRight(90) { @@ -32,7 +32,7 @@ Describe "Tests" { $null = Import-Excel $PSScriptRoot\LargerFile.xlsx } - $timer.TotalMilliseconds | should BeLessThan 3000 + $timer.TotalMilliseconds | Should -BeLessThan 3000 } It "Should be able to open, read and close as seperate actions".PadRight(90) { @@ -40,30 +40,30 @@ Describe "Tests" { $excel = Open-ExcelPackage $PSScriptRoot\Simple.xlsx $data = Import-Excel -ExcelPackage $excel Close-ExcelPackage -ExcelPackage $excel -NoSave} - $timer.TotalMilliseconds | should BeLessThan 2100 - $data.count | Should be 2 - $data[0].p1 | Should be "a" - $data[1].p1 | Should be "b" + $timer.TotalMilliseconds | Should -BeLessThan 2100 + $data.count | Should -Be 2 + $data[0].p1 | Should -Be "a" + $data[1].p1 | Should -Be "b" } It "Should take Paths from parameter".PadRight(90) { $data = Import-Excel -Path (Get-ChildItem -Path $PSScriptRoot -Filter "TestData?.xlsx").FullName - $data.count | Should be 4 - $data[0].cola | Should be 1 - $data[2].cola | Should be 5 + $data.count | Should -Be 4 + $data[0].cola | Should -Be 1 + $data[2].cola | Should -Be 5 } It "Should take Paths from pipeline".PadRight(90) { $data = (Get-ChildItem -Path $PSScriptRoot -Filter "TestData?.xlsx").FullName | Import-Excel - $data.count | Should be 4 - $data[0].cola | Should be 1 - $data[2].cola | Should be 5 + $data.count | Should -Be 4 + $data[0].cola | Should -Be 1 + $data[2].cola | Should -Be 5 } It "Should support PipelineVariable".PadRight(90) { $data = Import-Excel $PSScriptRoot\Simple.xlsx -PipelineVariable 'Pv' | ForEach-Object { $Pv.p1 } - $data.count | Should be 2 - $data[0] | Should be "a" - $data[1] | Should be "b" + $data.count | Should -Be 2 + $data[0] | Should -Be "a" + $data[1] | Should -Be "b" } } \ No newline at end of file diff --git a/__tests__/InputItemParameter.tests.ps1 b/__tests__/InputItemParameter.tests.ps1 index 53939b3..d87a22f 100644 --- a/__tests__/InputItemParameter.tests.ps1 +++ b/__tests__/InputItemParameter.tests.ps1 @@ -46,41 +46,41 @@ Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking I } Context "Array of processes" { it "Put the correct rows and columns into the sheet " { - $sheet.Dimension.Rows | should be ($results.Count + 1) - $sheet.Dimension.Columns | should be 5 - $sheet.cells["A1"].Value | should be "Name" - $sheet.cells["E1"].Value | should be "StartTime" - $sheet.cells["A3"].Value | should be $results[1].Name + $sheet.Dimension.Rows | Should -Be ($results.Count + 1) + $sheet.Dimension.Columns | Should -Be 5 + $sheet.cells["A1"].Value | Should -Be "Name" + $sheet.cells["E1"].Value | Should -Be "StartTime" + $sheet.cells["A3"].Value | Should -Be $results[1].Name } it "Created a range for the whole sheet " { - $sheet.Names[0].Name | should be "Whole" - $sheet.Names[0].Start.Address | should be "A1" - $sheet.Names[0].End.row | should be ($results.Count + 1) - $sheet.Names[0].End.Column | should be 5 + $sheet.Names[0].Name | Should -Be "Whole" + $sheet.Names[0].Start.Address | Should -Be "A1" + $sheet.Names[0].End.row | Should -Be ($results.Count + 1) + $sheet.Names[0].End.Column | Should -Be 5 } it "Formatted date fields with date type " { - $sheet.Cells["E11"].Style.Numberformat.NumFmtID | should be 22 + $sheet.Cells["E11"].Style.Numberformat.NumFmtID | Should -Be 22 } } $sheet = $excel.Sheet2 Context "Table of processes" { it "Put the correct rows and columns into the sheet " { - $sheet.Dimension.Rows | should be ($results.Count + 1) - $sheet.Dimension.Columns | should be 5 - $sheet.cells["A1"].Value | should be "Name" - $sheet.cells["E1"].Value | should be "StartTime" - $sheet.cells["A3"].Value | should be $results[1].Name + $sheet.Dimension.Rows | Should -Be ($results.Count + 1) + $sheet.Dimension.Columns | Should -Be 5 + $sheet.cells["A1"].Value | Should -Be "Name" + $sheet.cells["E1"].Value | Should -Be "StartTime" + $sheet.cells["A3"].Value | Should -Be $results[1].Name } it "Created named ranges for each column " { - $sheet.Names.count | should be 5 - $sheet.Names[0].Name | should be "Name" - $sheet.Names[1].Start.Address | should be "B2" - $sheet.Names[2].End.row | should be ($results.Count + 1) - $sheet.Names[3].End.Column | should be 4 - $sheet.Names[4].Start.Column | should be 5 + $sheet.Names.count | Should -Be 5 + $sheet.Names[0].Name | Should -Be "Name" + $sheet.Names[1].Start.Address | Should -Be "B2" + $sheet.Names[2].End.row | Should -Be ($results.Count + 1) + $sheet.Names[3].End.Column | Should -Be 4 + $sheet.Names[4].Start.Column | Should -Be 5 } it "Formatted date fields with date type " { - $sheet.Cells["E11"].Style.Numberformat.NumFmtID | should be 22 + $sheet.Cells["E11"].Style.Numberformat.NumFmtID | Should -Be 22 } } @@ -88,14 +88,14 @@ Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking I $NowPkg = Open-ExcelPackage $NowPath1 $sheet = $NowPkg.Sheet1 it "Formatted data as a table by default " { - $sheet.Tables.Count | should be 1 + $sheet.Tables.Count | Should -Be 1 } Close-ExcelPackage -NoSave $NowPkg Remove-Item $NowPath1 $NowPkg = Open-ExcelPackage $NowPath2 $sheet = $NowPkg.Sheet1 it "Did not data as a table when table:`$false was used " { - $sheet.Tables.Count | should be 0 + $sheet.Tables.Count | Should -Be 0 } Close-ExcelPackage -NoSave $NowPkg Remove-Item $NowPath2 @@ -103,37 +103,37 @@ Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking I $sheet = $excel.Sheet3 Context "Table of processes via Send-SQLDataToExcel" { it "Put the correct data rows and columns into the sheet " { - $sheet.Dimension.Rows | should be ($results.Count + 1) - $sheet.Dimension.Columns | should be 5 - $sheet.cells["A1"].Value | should be "Name" - $sheet.cells["E1"].Value | should be "StartTime" - $sheet.cells["A3"].Value | should be $results[1].Name + $sheet.Dimension.Rows | Should -Be ($results.Count + 1) + $sheet.Dimension.Columns | Should -Be 5 + $sheet.cells["A1"].Value | Should -Be "Name" + $sheet.cells["E1"].Value | Should -Be "StartTime" + $sheet.cells["A3"].Value | Should -Be $results[1].Name } it "Created a table " { - $sheet.Tables.count | should be 1 - $sheet.Tables[0].Columns[4].name | should be "StartTime" + $sheet.Tables.count | Should -Be 1 + $sheet.Tables[0].Columns[4].name | Should -Be "StartTime" } it "Formatted date fields with date type " { - $sheet.Cells["E11"].Style.Numberformat.NumFmtID | should be 22 + $sheet.Cells["E11"].Style.Numberformat.NumFmtID | Should -Be 22 } it "Handled two data tables with the same name " { - $sheet.Tables[0].Name | should be "Data_" - $wvThree[0] | should match "is not unique" + $sheet.Tables[0].Name | Should -Be "Data_" + $wvThree[0] | Should -Match "is not unique" } } $Sheet = $excel.Sheet4 Context "Zero-row Data Table sent with Send-SQLDataToExcel -Force" { it "Raised a warning and put the correct data headers into the sheet " { - $sheet.Dimension.Rows | should be 1 - $sheet.Dimension.Columns | should be 5 - $sheet.cells["A1"].Value | should be "Name" - $sheet.cells["E1"].Value | should be "StartTime" - $sheet.cells["A3"].Value | should beNullOrEmpty - $wvone[0] | should match "Zero" + $sheet.Dimension.Rows | Should -Be 1 + $sheet.Dimension.Columns | Should -Be 5 + $sheet.cells["A1"].Value | Should -Be "Name" + $sheet.cells["E1"].Value | Should -Be "StartTime" + $sheet.cells["A3"].Value | Should -BeNullOrEmpty + $wvone[0] | Should -Match "Zero" } it "Applied table formatting " { - $sheet.Tables.Count | should be 1 - $sheet.Tables[0].Name | should be "Data" + $sheet.Tables.Count | Should -Be 1 + $sheet.Tables[0].Name | Should -Be "Data" } @@ -141,8 +141,8 @@ Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking I $Sheet = $excel.Sheet5 Context "Zero-column Data Table handled by Send-SQLDataToExcel -Force" { it "Created a blank Sheet and raised a warning " { - $sheet.Dimension | should beNullOrEmpty - $wvTwo | should not beNullOrEmpty + $sheet.Dimension | Should -BeNullOrEmpty + $wvTwo | Should -Not -BeNullOrEmpty } } @@ -150,32 +150,32 @@ Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking I $excel = Open-ExcelPackage $path2 Context "Send-SQLDataToExcel -append works correctly" { it "Works without table settings " { - $excel.sheet1.Dimension.Address | should be "A1:E21" - $excel.sheet1.cells[1,1].value | should be "Name" - $excel.sheet1.cells[12,1].value | should be $excel.sheet1.cells[2,1].value - $excel.sheet1.Tables.count | should be 0 + $excel.sheet1.Dimension.Address | Should -Be "A1:E21" + $excel.sheet1.cells[1,1].value | Should -Be "Name" + $excel.sheet1.cells[12,1].value | Should -Be $excel.sheet1.cells[2,1].value + $excel.sheet1.Tables.count | Should -Be 0 } it "Extends an existing table when appending " { - $excel.sheet2.Dimension.Address | should be "A1:E21" - $excel.sheet2.cells[1,2].value | should be "CPU" - $excel.sheet2.cells[13,2].value | should be $excel.sheet2.cells[3,2].value - $excel.sheet2.Tables.count | should be 1 - $excel.sheet2.Tables[0].name | should be "FirstLot" - $excel.sheet2.Tables[0].StyleName | should be "TableStyleLight7" + $excel.sheet2.Dimension.Address | Should -Be "A1:E21" + $excel.sheet2.cells[1,2].value | Should -Be "CPU" + $excel.sheet2.cells[13,2].value | Should -Be $excel.sheet2.cells[3,2].value + $excel.sheet2.Tables.count | Should -Be 1 + $excel.sheet2.Tables[0].name | Should -Be "FirstLot" + $excel.sheet2.Tables[0].StyleName | Should -Be "TableStyleLight7" } it "Creates a new table by name when appending " { - $excel.sheet3.cells[1,3].value | should be "PM" - $excel.sheet3.cells[14,3].value | should be $excel.sheet3.cells[4,3].value - $excel.sheet3.Tables.count | should be 1 - $excel.sheet3.Tables[0].name | should be "SecondLot" - $excel.sheet3.Tables[0].StyleName | should be "TableStyleMedium6" + $excel.sheet3.cells[1,3].value | Should -Be "PM" + $excel.sheet3.cells[14,3].value | Should -Be $excel.sheet3.cells[4,3].value + $excel.sheet3.Tables.count | Should -Be 1 + $excel.sheet3.Tables[0].name | Should -Be "SecondLot" + $excel.sheet3.Tables[0].StyleName | Should -Be "TableStyleMedium6" } it "Creates a new table by style when appending " { - $excel.sheet4.cells[1,4].value | should be "Handles" - $excel.sheet4.cells[15,4].value | should be $excel.sheet4.cells[5,4].value - $excel.sheet4.Tables.count | should be 1 - $excel.sheet4.Tables[0].name | should be "Table1" - $excel.sheet4.Tables[0].StyleName | should be "TableStyleDark5" + $excel.sheet4.cells[1,4].value | Should -Be "Handles" + $excel.sheet4.cells[15,4].value | Should -Be $excel.sheet4.cells[5,4].value + $excel.sheet4.Tables.count | Should -Be 1 + $excel.sheet4.Tables[0].name | Should -Be "Table1" + $excel.sheet4.Tables[0].StyleName | Should -Be "TableStyleDark5" } } @@ -183,9 +183,9 @@ Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking I Context "Import As Text returns text values" { $x = Import-excel $path -WorksheetName sheet3 -AsText StartTime,hand* | Select-Object -last 1 it "Had fields of type string, not date or int, where specified as ASText " { - $x.Handles.GetType().Name | should be "String" - $x.StartTime.GetType().Name | should be "String" - $x.CPU.GetType().Name | should not be "String" + $x.Handles.GetType().Name | Should -Be "String" + $x.StartTime.GetType().Name | Should -Be "String" + $x.CPU.GetType().Name | Should -Not -Be "String" } } diff --git a/__tests__/Join-Worksheet.tests.ps1 b/__tests__/Join-Worksheet.tests.ps1 index 8ba42c8..df389b2 100644 --- a/__tests__/Join-Worksheet.tests.ps1 +++ b/__tests__/Join-Worksheet.tests.ps1 @@ -44,52 +44,52 @@ Describe "Join Worksheet part 1" { } Context "Export-Excel setting spreadsheet visibility" { it "Hid the worksheets " { - $excel.Workbook.Worksheets["Oxford"].Hidden | Should be 'Hidden' - $excel.Workbook.Worksheets["Banbury"].Hidden | Should be 'Hidden' - $excel.Workbook.Worksheets["Abingdon"].Hidden | Should be 'Hidden' + $excel.Workbook.Worksheets["Oxford"].Hidden | Should -Be 'Hidden' + $excel.Workbook.Worksheets["Banbury"].Hidden | Should -Be 'Hidden' + $excel.Workbook.Worksheets["Abingdon"].Hidden | Should -Be 'Hidden' } it "Un-hid two of the worksheets " { - $excel.Workbook.Worksheets["Total"].Hidden | Should be 'Visible' - $excel.Workbook.Worksheets["SummaryPivot"].Hidden | Should be 'Visible' + $excel.Workbook.Worksheets["Total"].Hidden | Should -Be 'Visible' + $excel.Workbook.Worksheets["SummaryPivot"].Hidden | Should -Be 'Visible' } it "Activated the correct worksheet " { Set-ItResult -Pending -Because "Bug in EPPLus 4.5" - $excel.Workbook.worksheets["SummaryPivot"].View.TabSelected | Should be $true - $excel.Workbook.worksheets["Total"].View.TabSelected | Should be $false + $excel.Workbook.worksheets["SummaryPivot"].View.TabSelected | Should -Be $true + $excel.Workbook.worksheets["Total"].View.TabSelected | Should -Be $false } } Context "Merging 3 blocks" { it "Created sheet of the right size with a title and a table " { - $ws.Dimension.Address | Should be "A1:F16" - $ws.Tables[0].Address.Address | Should be "A2:F16" - $ws.Cells["A1"].Value | Should be "Store Sales Summary" - $ws.Cells["A1"].Style.Font.Size | Should be 14 - $ws.Cells["A1"].Style.Font.Bold | Should be $True - $ws.Cells["A1"].Style.Fill.BackgroundColor.Rgb | Should be "FFF0F8FF" - $ws.Cells["A1"].Style.Fill.PatternType.ToString() | Should be "Solid" - $ws.Tables[0].StyleName | Should be "TableStyleLight1" - $ws.Cells["A2:F2"].Style.Font.Bold | Should be $True + $ws.Dimension.Address | Should -Be "A1:F16" + $ws.Tables[0].Address.Address | Should -Be "A2:F16" + $ws.Cells["A1"].Value | Should -Be "Store Sales Summary" + $ws.Cells["A1"].Style.Font.Size | Should -Be 14 + $ws.Cells["A1"].Style.Font.Bold | Should -Be $True + $ws.Cells["A1"].Style.Fill.BackgroundColor.Rgb | Should -Be "FFF0F8FF" + $ws.Cells["A1"].Style.Fill.PatternType.ToString() | Should -Be "Solid" + $ws.Tables[0].StyleName | Should -Be "TableStyleLight1" + $ws.Cells["A2:F2"].Style.Font.Bold | Should -Be $True } it "Added a from column with the right heading " { - $ws.Cells["F2" ].Value | Should be "Store" - $ws.Cells["F3" ].Value | Should be "Oxford" - $ws.Cells["F8" ].Value | Should be "Abingdon" - $ws.Cells["F13"].Value | Should be "Banbury" + $ws.Cells["F2" ].Value | Should -Be "Store" + $ws.Cells["F3" ].Value | Should -Be "Oxford" + $ws.Cells["F8" ].Value | Should -Be "Abingdon" + $ws.Cells["F13"].Value | Should -Be "Banbury" } it "Filled in the data " { - $ws.Cells["C3" ].Value | Should be $data1[0].quantity - $ws.Cells["C8" ].Value | Should be $data2[0].quantity - $ws.Cells["C13"].Value | Should be $data3[0].quantity + $ws.Cells["C3" ].Value | Should -Be $data1[0].quantity + $ws.Cells["C8" ].Value | Should -Be $data2[0].quantity + $ws.Cells["C13"].Value | Should -Be $data3[0].quantity } it "Created the pivot table " { - $pt | Should not beNullOrEmpty - $pt.StyleName | Should be "PivotStyleMedium9" - $pt.RowFields[0].Name | Should be "Store" - $pt.ColumnFields[0].name | Should be "Product" - $pt.DataFields[0].name | Should be "Sum of Total" - $pc.ChartType | Should be "ColumnStacked" - $pc.Title.text | Should be "Sales Breakdown" + $pt | Should -Not -BeNullOrEmpty + $pt.StyleName | Should -Be "PivotStyleMedium9" + $pt.RowFields[0].Name | Should -Be "Store" + $pt.ColumnFields[0].name | Should -Be "Product" + $pt.DataFields[0].name | Should -Be "Sum of Total" + $pc.ChartType | Should -Be "ColumnStacked" + $pc.Title.text | Should -Be "Sales Breakdown" } } } @@ -109,22 +109,22 @@ Describe "Join Worksheet part 2" { $ws = $excel.Workbook.Worksheets["Summary"] Context "Bringing 3 Unlinked blocks onto one page" { it "Hid the source worksheets " { - $excel.Workbook.Worksheets[1].Hidden.tostring() | Should be "Hidden" - $excel.Workbook.Worksheets[2].Hidden.tostring() | Should be "Hidden" + $excel.Workbook.Worksheets[1].Hidden.tostring() | Should -Be "Hidden" + $excel.Workbook.Worksheets[2].Hidden.tostring() | Should -Be "Hidden" } it "Created the Summary sheet with title, and block labels, and copied the correct data " { - $ws.Cells["A1"].Value | Should be "Summary" - $ws.Cells["A2"].Value | Should be $excel.Workbook.Worksheets[1].name - $ws.Cells["A3"].Value | Should be $excel.Workbook.Worksheets[1].Cells["A1"].value - $ws.Cells["A4"].Value | Should be $excel.Workbook.Worksheets[1].Cells["A2"].value - $ws.Cells["B4"].Value | Should be $excel.Workbook.Worksheets[1].Cells["B2"].value + $ws.Cells["A1"].Value | Should -Be "Summary" + $ws.Cells["A2"].Value | Should -Be $excel.Workbook.Worksheets[1].name + $ws.Cells["A3"].Value | Should -Be $excel.Workbook.Worksheets[1].Cells["A1"].value + $ws.Cells["A4"].Value | Should -Be $excel.Workbook.Worksheets[1].Cells["A2"].value + $ws.Cells["B4"].Value | Should -Be $excel.Workbook.Worksheets[1].Cells["B2"].value $nextRow = $excel.Workbook.Worksheets[1].Dimension.Rows + 3 - $ws.Cells["A$NextRow"].Value | Should be $excel.Workbook.Worksheets[2].name + $ws.Cells["A$NextRow"].Value | Should -Be $excel.Workbook.Worksheets[2].name $nextRow ++ - $ws.Cells["A$NextRow"].Value | Should be $excel.Workbook.Worksheets[2].Cells["A1"].value + $ws.Cells["A$NextRow"].Value | Should -Be $excel.Workbook.Worksheets[2].Cells["A1"].value $nextRow ++ - $ws.Cells["A$NextRow"].Value | Should be $excel.Workbook.Worksheets[2].Cells["A2"].value - $ws.Cells["B$NextRow"].Value | Should be $excel.Workbook.Worksheets[2].Cells["B2"].value + $ws.Cells["A$NextRow"].Value | Should -Be $excel.Workbook.Worksheets[2].Cells["A2"].value + $ws.Cells["B$NextRow"].Value | Should -Be $excel.Workbook.Worksheets[2].Cells["B2"].value } } } diff --git a/__tests__/PasswordProtection.tests.ps1 b/__tests__/PasswordProtection.tests.ps1 index c2bc679..66e7976 100644 --- a/__tests__/PasswordProtection.tests.ps1 +++ b/__tests__/PasswordProtection.tests.ps1 @@ -15,17 +15,17 @@ Describe "Password Support" { Get-Service | Select-Object -First 10 | Export-excel -password $password -Path $Path -DisplayPropertySet } it "Threw an error when the password was omitted " { - {Open-ExcelPackage -Path $path } | should throw + {Open-ExcelPackage -Path $path } | Should -Throw } it "Was able to append when the password was included " { {Get-Service | Select-Object -First 10 | - Export-excel -password $password -Path $Path -Append } | should not throw + Export-excel -password $password -Path $Path -Append } | Should -Not -Throw } it "Kept the password on the file when it was saved " { - {Import-Excel $Path } | should throw + {Import-Excel $Path } | Should -Throw } it "Could read the file when the password was included " { - (Import-excel $path -Password $password).count | should be 20 + (Import-excel $path -Password $password).count | Should -Be 20 } } } diff --git a/__tests__/Path.tests.ps1 b/__tests__/Path.tests.ps1 index 6b449bd..1d85ae3 100644 --- a/__tests__/Path.tests.ps1 +++ b/__tests__/Path.tests.ps1 @@ -10,29 +10,29 @@ It "Should read local file".PadRight(90) { $actual = Import-Excel -Path ".\$($script:xlfileName)" - $actual | Should Not Be $null - $actual.Count | Should Be 1 + $actual | Should -Not -Be $null + $actual.Count | Should -Be 1 } It "Should read with pwd".PadRight(90){ $actual = Import-Excel -Path (Join-Path $PWD "$($script:xlfileName)") - $actual | Should Not Be $null + $actual | Should -Not -Be $null } It "Should read with just a file name and resolve to cwd".PadRight(90){ $actual = Import-Excel -Path "$($script:xlfileName)" - $actual | Should Not Be $null + $actual | Should -Not -Be $null } It "Should fail for not found".PadRight(90){ - { Import-Excel -Path "ExcelFileDoesNotExist.xlsx" } | Should Throw "'ExcelFileDoesNotExist.xlsx' file not found" + { Import-Excel -Path "ExcelFileDoesNotExist.xlsx" } | Should -Throw "'ExcelFileDoesNotExist.xlsx' file not found" } It "Should fail for xls extension".PadRight(90){ - { Import-Excel -Path "ExcelFileDoesNotExist.xls" } | Should Throw "Import-Excel does not support reading this extension type .xls" + { Import-Excel -Path "ExcelFileDoesNotExist.xls" } | Should -Throw "Import-Excel does not support reading this extension type .xls" } It "Should fail for xlsxs extension".PadRight(90){ - { Import-Excel -Path "ExcelFileDoesNotExist.xlsxs" } | Should Throw "Import-Excel does not support reading this extension type .xlsxs" + { Import-Excel -Path "ExcelFileDoesNotExist.xlsxs" } | Should -Throw "Import-Excel does not support reading this extension type .xlsxs" } } \ No newline at end of file diff --git a/__tests__/ProtectWorksheet.tests.ps1 b/__tests__/ProtectWorksheet.tests.ps1 index 6d7fab0..b179178 100644 --- a/__tests__/ProtectWorksheet.tests.ps1 +++ b/__tests__/ProtectWorksheet.tests.ps1 @@ -22,15 +22,15 @@ Apple, New York, 1200,700 $ws = $ws = $excel.sheet1 } it "Turned on protection for the sheet " { - $ws.Protection.IsProtected | should be $true + $ws.Protection.IsProtected | Should -Be $true } it "Set sheet-wide protection options " { - $ws.Protection.AllowEditObject | should be $false - $ws.Protection.AllowFormatRows | should be $true - $ws.cells["a2"].Style.Locked | should be $true + $ws.Protection.AllowEditObject | Should -Be $false + $ws.Protection.AllowFormatRows | Should -Be $true + $ws.cells["a2"].Style.Locked | Should -Be $true } it "Unprotected some cells " { - $ws.cells["a1"].Style.Locked | should be $false + $ws.cells["a1"].Style.Locked | Should -Be $false } } diff --git a/__tests__/RangePassing.ps1 b/__tests__/RangePassing.ps1 index c7f4300..b2bb041 100644 --- a/__tests__/RangePassing.ps1 +++ b/__tests__/RangePassing.ps1 @@ -6,36 +6,36 @@ describe "Consistent passing of ranges." { Remove-Item -path $path -ErrorAction SilentlyContinue $excel = Get-Service | Export-Excel -Path $path -WorksheetName Services -PassThru -AutoSize -DisplayPropertySet -AutoNameRange -Title "Services on $Env:COMPUTERNAME" it "accepts named ranges, cells['name'], worksheet + Name, worksheet + column " { - {Add-ConditionalFormatting $excel.Services.Names["Status"] -StrikeThru -RuleType ContainsText -ConditionValue "Stopped" } | Should not throw - $excel.Services.ConditionalFormatting.Count | Should be 1 - {Add-ConditionalFormatting $excel.Services.Cells["Name"] -Italic -RuleType ContainsText -ConditionValue "SVC" } | Should not throw - $excel.Services.ConditionalFormatting.Count | Should be 2 + {Add-ConditionalFormatting $excel.Services.Names["Status"] -StrikeThru -RuleType ContainsText -ConditionValue "Stopped" } | Should -Not -Throw + $excel.Services.ConditionalFormatting.Count | Should -Be 1 + {Add-ConditionalFormatting $excel.Services.Cells["Name"] -Italic -RuleType ContainsText -ConditionValue "SVC" } | Should -Not -Throw + $excel.Services.ConditionalFormatting.Count | Should -Be 2 $warnvar = $null Add-ConditionalFormatting $excel.Services.Column(3) ` -underline -RuleType ContainsText -ConditionValue "Windows" -WarningVariable warnvar -WarningAction SilentlyContinue - $warnvar | should not beNullOrEmpty - $excel.Services.ConditionalFormatting.Count | Should be 2 + $warnvar | Should -Not -BeNullOrEmpty + $excel.Services.ConditionalFormatting.Count | Should -Be 2 $warnvar = $null Add-ConditionalFormatting $excel.Services.Column(3) -Worksheet $excel.Services` -underline -RuleType ContainsText -ConditionValue "Windows" -WarningVariable warnvar -WarningAction SilentlyContinue - $warnvar | should beNullOrEmpty - $excel.Services.ConditionalFormatting.Count | Should be 3 + $warnvar | Should -BeNullOrEmpty + $excel.Services.ConditionalFormatting.Count | Should -Be 3 {Add-ConditionalFormatting "Status" -Worksheet $excel.Services ` - -ForeGroundColor ([System.Drawing.Color]::Green) -RuleType ContainsText -ConditionValue "Running"} | Should not throw - $excel.Services.ConditionalFormatting.Count | Should be 4 + -ForeGroundColor ([System.Drawing.Color]::Green) -RuleType ContainsText -ConditionValue "Running"} | Should -Not -Throw + $excel.Services.ConditionalFormatting.Count | Should -Be 4 } Close-ExcelPackage -NoSave $excel $excel = Get-Service | Export-Excel -Path $path -WorksheetName Services -PassThru -AutoSize -DisplayPropertySet -TableName servicetable -Title "Services on $Env:COMPUTERNAME" it "accepts table, table.Address and worksheet + 'C:C' " { {Add-ConditionalFormatting $excel.Services.Tables[0] ` - -Italic -RuleType ContainsText -ConditionValue "Svc" } | Should not throw - $excel.Services.ConditionalFormatting.Count | Should be 1 + -Italic -RuleType ContainsText -ConditionValue "Svc" } | Should -Not -Throw + $excel.Services.ConditionalFormatting.Count | Should -Be 1 {Add-ConditionalFormatting $excel.Services.Tables["ServiceTable"].Address ` - -Bold -RuleType ContainsText -ConditionValue "windows" } | Should not throw - $excel.Services.ConditionalFormatting.Count | Should be 2 + -Bold -RuleType ContainsText -ConditionValue "windows" } | Should -Not -Throw + $excel.Services.ConditionalFormatting.Count | Should -Be 2 {Add-ConditionalFormatting -Worksheet $excel.Services -Address "a:a" ` - -RuleType ContainsText -ConditionValue "stopped" -ForeGroundColor ([System.Drawing.Color]::Red) } | Should not throw - $excel.Services.ConditionalFormatting.Count | Should be 3 + -RuleType ContainsText -ConditionValue "stopped" -ForeGroundColor ([System.Drawing.Color]::Red) } | Should -Not -Throw + $excel.Services.ConditionalFormatting.Count | Should -Be 3 } Close-ExcelPackage -NoSave $excel } @@ -43,29 +43,29 @@ describe "Consistent passing of ranges." { Context "Formating (Set-ExcelRange or its alias Set-Format) " { it "accepts Named Range, cells['Name'], cells['A1:Z9'], row, Worksheet + 'A1:Z9'" { $excel = Get-Service | Export-Excel -Path test2.xlsx -WorksheetName Services -PassThru -AutoSize -DisplayPropertySet -RangeName servicerange -Title "Services on $Env:COMPUTERNAME" - {Set-format $excel.Services.Names["serviceRange"] -Bold } | Should Not Throw - $excel.Services.cells["B2"].Style.Font.Bold | Should be $true - {Set-ExcelRange -Range $excel.Services.Cells["serviceRange"] -italic:$true } | Should not throw - $excel.Services.cells["C3"].Style.Font.Italic | Should be $true - {Set-format $excel.Services.Row(4) -underline -Bold:$false } | Should not throw - $excel.Services.cells["A4"].Style.Font.UnderLine | Should be $true - $excel.Services.cells["A4"].Style.Font.Bold | Should not be $true - {Set-ExcelRange $excel.Services.Cells["A3:B3"] -StrikeThru } | Should not throw - $excel.Services.cells["B3"].Style.Font.Strike | Should be $true - {Set-ExcelRange -Worksheet $excel.Services -Range "A5:B6" -FontSize 8 } | Should not throw - $excel.Services.cells["A5"].Style.Font.Size | Should be 8 + {Set-format $excel.Services.Names["serviceRange"] -Bold } | Should -Not -Throw + $excel.Services.cells["B2"].Style.Font.Bold | Should -Be $true + {Set-ExcelRange -Range $excel.Services.Cells["serviceRange"] -italic:$true } | Should -Not -Throw + $excel.Services.cells["C3"].Style.Font.Italic | Should -Be $true + {Set-format $excel.Services.Row(4) -underline -Bold:$false } | Should -Not -Throw + $excel.Services.cells["A4"].Style.Font.UnderLine | Should -Be $true + $excel.Services.cells["A4"].Style.Font.Bold | Should -Not -Be $true + {Set-ExcelRange $excel.Services.Cells["A3:B3"] -StrikeThru } | Should -Not -Throw + $excel.Services.cells["B3"].Style.Font.Strike | Should -Be $true + {Set-ExcelRange -Worksheet $excel.Services -Range "A5:B6" -FontSize 8 } | Should -Not -Throw + $excel.Services.cells["A5"].Style.Font.Size | Should -Be 8 } Close-ExcelPackage -NoSave $excel it "Accepts Table, Table.Address , worksheet + Name, Column," { $excel = Get-Service | Export-Excel -Path test2.xlsx -WorksheetName Services -PassThru -AutoNameRange -AutoSize -DisplayPropertySet -TableName servicetable -Title "Services on $Env:COMPUTERNAME" - {Set-ExcelRange $excel.Services.Tables[0] -Italic } | Should not throw - $excel.Services.cells["C3"].Style.Font.Italic | Should be $true - {Set-format $excel.Services.Tables["ServiceTable"].Address -Underline } | Should not throw - $excel.Services.cells["C3"].Style.Font.UnderLine | Should be $true - {Set-ExcelRange -Worksheet $excel.Services -Range "Name" -Bold } | Should not throw - $excel.Services.cells["B4"].Style.Font.Bold | Should be $true - {$excel.Services.Column(3) | Set-ExcelRange -FontColor ([System.Drawing.Color]::Red) } | Should not throw - $excel.Services.cells["C4"].Style.Font.Color.Rgb | Should be "FFFF0000" + {Set-ExcelRange $excel.Services.Tables[0] -Italic } | Should -Not -Throw + $excel.Services.cells["C3"].Style.Font.Italic | Should -Be $true + {Set-format $excel.Services.Tables["ServiceTable"].Address -Underline } | Should -Not -Throw + $excel.Services.cells["C3"].Style.Font.UnderLine | Should -Be $true + {Set-ExcelRange -Worksheet $excel.Services -Range "Name" -Bold } | Should -Not -Throw + $excel.Services.cells["B4"].Style.Font.Bold | Should -Be $true + {$excel.Services.Column(3) | Set-ExcelRange -FontColor ([System.Drawing.Color]::Red) } | Should -Not -Throw + $excel.Services.cells["C4"].Style.Font.Color.Rgb | Should -Be "FFFF0000" } Close-ExcelPackage -NoSave $excel } @@ -77,24 +77,24 @@ describe "Consistent passing of ranges." { $end = $ws.Dimension.End.Address #can get a named ranged by name or index - starting at zero {Add-PivotTable -ExcelPackage $excel -PivotTableName pt0 -SourceRange $ws.Names[0]` - -PivotRows Status -PivotData Name } | Should not throw - $excel.Workbook.Worksheets["pt0"] | Should not beNullOrEmpty + -PivotRows Status -PivotData Name } | Should -Not -Throw + $excel.Workbook.Worksheets["pt0"] | Should -Not -BeNullOrEmpty {Add-PivotTable -ExcelPackage $excel -PivotTableName pt1 -SourceRange $ws.Names["servicerange"]` - -PivotRows Status -PivotData Name } | Should not throw - $excel.Workbook.Worksheets["pt1"] | Should not beNullOrEmpty + -PivotRows Status -PivotData Name } | Should -Not -Throw + $excel.Workbook.Worksheets["pt1"] | Should -Not -BeNullOrEmpty #Can specify the range for a pivot as NamedRange or Table or TableAddress or Worksheet + "A1:Z10" or worksheet + RangeName, or worksheet.cells["A1:Z10"] or worksheet.cells["RangeName"] {Add-PivotTable -ExcelPackage $excel -PivotTableName pt2 -SourceRange "servicerange" -SourceWorkSheet $ws ` - -PivotRows Status -PivotData Name } | Should not throw - $excel.Workbook.Worksheets["pt2"] | Should not beNullOrEmpty + -PivotRows Status -PivotData Name } | Should -Not -Throw + $excel.Workbook.Worksheets["pt2"] | Should -Not -BeNullOrEmpty {Add-PivotTable -ExcelPackage $excel -PivotTableName pt3 -SourceRange $ws.cells["servicerange"]` - -PivotRows Status -PivotData Name } | Should not throw - $excel.Workbook.Worksheets["pt3"] | Should not beNullOrEmpty + -PivotRows Status -PivotData Name } | Should -Not -Throw + $excel.Workbook.Worksheets["pt3"] | Should -Not -BeNullOrEmpty {Add-PivotTable -ExcelPackage $excel -PivotTableName pt4 -SourceRange $ws.cells["A2:$end"]` - -PivotRows Status -PivotData Name } | Should not throw - $excel.Workbook.Worksheets["pt4"] | Should not beNullOrEmpty + -PivotRows Status -PivotData Name } | Should -Not -Throw + $excel.Workbook.Worksheets["pt4"] | Should -Not -BeNullOrEmpty {Add-PivotTable -ExcelPackage $excel -PivotTableName pt5 -SourceRange "A2:$end" -SourceWorkSheet $ws ` - -PivotRows Status -PivotData Name } | Should not throw - $excel.Workbook.Worksheets["pt5"] | Should not beNullOrEmpty + -PivotRows Status -PivotData Name } | Should -Not -Throw + $excel.Workbook.Worksheets["pt5"] | Should -Not -BeNullOrEmpty Close-ExcelPackage -NoSave $excel } it "Accepts Table, Table.Addres " { @@ -102,11 +102,11 @@ describe "Consistent passing of ranges." { $ws = $excel.Workbook.Worksheets["Services"] #can get a worksheet by name or index - starting at 1 #Can get a table by name or -stating at zero. Can specify the range for a pivot as or Table or TableAddress {Add-PivotTable -ExcelPackage $excel -PivotTableName pt1 -SourceRange $ws.tables["servicetable"]` - -PivotRows Status -PivotData Name } | Should not throw - $excel.Workbook.Worksheets["pt1"] | Should not beNullOrEmpty + -PivotRows Status -PivotData Name } | Should -Not -Throw + $excel.Workbook.Worksheets["pt1"] | Should -Not -BeNullOrEmpty {Add-PivotTable -ExcelPackage $excel -PivotTableName pt2 -SourceRange $ws.tables[0].Address ` - -PivotRows Status -PivotData Name } | Should not throw - $excel.Workbook.Worksheets["pt2"] | Should not beNullOrEmpty + -PivotRows Status -PivotData Name } | Should -Not -Throw + $excel.Workbook.Worksheets["pt2"] | Should -Not -BeNullOrEmpty Close-ExcelPackage -NoSave $excel } diff --git a/__tests__/Remove-WorkSheet.tests.ps1 b/__tests__/Remove-WorkSheet.tests.ps1 index 45a9ae3..ca660b6 100644 --- a/__tests__/Remove-WorkSheet.tests.ps1 +++ b/__tests__/Remove-WorkSheet.tests.ps1 @@ -29,7 +29,7 @@ John,20 } it "Should throw about the Path".PadRight(87) { - {Remove-Worksheet} | Should throw 'Remove-Worksheet requires the and Excel file' + {Remove-Worksheet} | Should -Throw 'Remove-Worksheet requires the and Excel file' } it "Should delete Target2".PadRight(87) { @@ -37,10 +37,10 @@ John,20 $actual = Get-ExcelSheetInfo -Path $xlFile1 - $actual.Count | Should Be 3 - $actual[0].Name | Should Be "Target1" - $actual[1].Name | Should Be "Target3" - $actual[2].Name | Should Be "Sheet1" + $actual.Count | Should -Be 3 + $actual[0].Name | Should -Be "Target1" + $actual[1].Name | Should -Be "Target3" + $actual[2].Name | Should -Be "Sheet1" } it "Should delete Sheet1".PadRight(87) { @@ -48,10 +48,10 @@ John,20 $actual = Get-ExcelSheetInfo -Path $xlFile1 - $actual.Count | Should Be 3 - $actual[0].Name | Should Be "Target1" - $actual[1].Name | Should Be "Target2" - $actual[2].Name | Should Be "Target3" + $actual.Count | Should -Be 3 + $actual[0].Name | Should -Be "Target1" + $actual[1].Name | Should -Be "Target2" + $actual[2].Name | Should -Be "Target3" } it "Should delete multiple sheets".PadRight(87) { @@ -59,9 +59,9 @@ John,20 $actual = Get-ExcelSheetInfo -Path $xlFile1 - $actual.Count | Should Be 2 - $actual[0].Name | Should Be "Target2" - $actual[1].Name | Should Be "Target3" + $actual.Count | Should -Be 2 + $actual[0].Name | Should -Be "Target2" + $actual[1].Name | Should -Be "Target3" } it "Should delete sheet from multiple workbooks".PadRight(87) { @@ -70,10 +70,10 @@ John,20 $actual = Get-ExcelSheetInfo -Path $xlFile1 - $actual.Count | Should Be 3 - $actual[0].Name | Should Be "Target1" - $actual[1].Name | Should Be "Target2" - $actual[2].Name | Should Be "Target3" + $actual.Count | Should -Be 3 + $actual[0].Name | Should -Be "Target1" + $actual[1].Name | Should -Be "Target2" + $actual[2].Name | Should -Be "Target3" } } } \ No newline at end of file diff --git a/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 b/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 index 0ecf7d6..aea3d8a 100644 --- a/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 +++ b/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 @@ -29,16 +29,16 @@ Describe "Number format expansion and setting" { Context "Expand-NumberFormat function" { It "Expanded named number formats as expected " { $r = [regex]::Escape([cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol) - Expand-NumberFormat 'Currency' | Should match "^[$r\(\)\[\] RED0#\?\-;,.]+$" - Expand-NumberFormat 'Number' | Should be "0.00" - Expand-NumberFormat 'Percentage' | Should be "0.00%" - Expand-NumberFormat 'Scientific' | Should be "0.00E+00" - Expand-NumberFormat 'Fraction' | Should be "# ?/?" - Expand-NumberFormat 'Short Date' | Should be "mm-dd-yy" - Expand-NumberFormat 'Short Time' | Should be "h:mm" - Expand-NumberFormat 'Long Time' | Should be "h:mm:ss" - Expand-NumberFormat 'Date-Time' | Should be "m/d/yy h:mm" - Expand-NumberFormat 'Text' | Should be "@" + Expand-NumberFormat 'Currency' | Should -Match "^[$r\(\)\[\] RED0#\?\-;,.]+$" + Expand-NumberFormat 'Number' | Should -Be "0.00" + Expand-NumberFormat 'Percentage' | Should -Be "0.00%" + Expand-NumberFormat 'Scientific' | Should -Be "0.00E+00" + Expand-NumberFormat 'Fraction' | Should -Be "# ?/?" + Expand-NumberFormat 'Short Date' | Should -Be "mm-dd-yy" + Expand-NumberFormat 'Short Time' | Should -Be "h:mm" + Expand-NumberFormat 'Long Time' | Should -Be "h:mm:ss" + Expand-NumberFormat 'Date-Time' | Should -Be "m/d/yy h:mm" + Expand-NumberFormat 'Text' | Should -Be "@" } } Context "Apply-NumberFormat" { @@ -87,36 +87,36 @@ Describe "Number format expansion and setting" { } It "Set formats which translate to the correct format ID " { - $ws.Cells[ 1, 1].Style.Numberformat.NumFmtID | Should be 0 # Set as General - $ws.Cells[20, 1].Style.Numberformat.NumFmtID | Should be 1 # Set as 0 - $ws.Cells[ 2, 1].Style.Numberformat.NumFmtID | Should be 2 # Set as "Number" - $ws.Cells[21, 1].Style.Numberformat.NumFmtID | Should be 2 # Set as 0.00 - $ws.Cells[22, 1].Style.Numberformat.NumFmtID | Should be 3 # Set as #,##0 - $ws.Cells[23, 1].Style.Numberformat.NumFmtID | Should be 4 # Set as #,##0.00 - $ws.Cells[26, 1].Style.Numberformat.NumFmtID | Should be 9 # Set as 0% - $ws.Cells[27, 1].Style.Numberformat.NumFmtID | Should be 10 # Set as 0.00% - $ws.Cells[ 3, 1].Style.Numberformat.NumFmtID | Should be 10 # Set as "Percentage" - $ws.Cells[28, 1].Style.Numberformat.NumFmtID | Should be 11 # Set as 0.00E+00 - $ws.Cells[ 4, 1].Style.Numberformat.NumFmtID | Should be 11 # Set as "Scientific" - $ws.Cells[ 5, 1].Style.Numberformat.NumFmtID | Should be 12 # Set as "Fraction" - $ws.Cells[29, 1].Style.Numberformat.NumFmtID | Should be 12 # Set as # ?/? - $ws.Cells[30, 1].Style.Numberformat.NumFmtID | Should be 13 # Set as # ??/? - $ws.Cells[ 6, 1].Style.Numberformat.NumFmtID | Should be 14 # Set as "Short date" - $ws.Cells[17, 1].Style.Numberformat.NumFmtID | Should be 15 # Set as d-mmm-yy - $ws.Cells[18, 1].Style.Numberformat.NumFmtID | Should be 16 # Set as d-mmm - $ws.Cells[19, 1].Style.Numberformat.NumFmtID | Should be 17 # Set as mmm-yy - $ws.Cells[12, 1].Style.Numberformat.NumFmtID | Should be 18 # Set as h:mm AM/PM - $ws.Cells[13, 1].Style.Numberformat.NumFmtID | Should be 19 # Set as h:mm:ss AM/PM - $ws.Cells[ 7, 1].Style.Numberformat.NumFmtID | Should be 20 # Set as "Short time" - $ws.Cells[ 8, 1].Style.Numberformat.NumFmtID | Should be 21 # Set as "Long time" - $ws.Cells[ 9, 1].Style.Numberformat.NumFmtID | Should be 22 # Set as "Date-time" - $ws.Cells[14, 1].Style.Numberformat.NumFmtID | Should be 45 # Set as mm:ss - $ws.Cells[15, 1].Style.Numberformat.NumFmtID | Should be 46 # Set as [h]:mm:ss - $ws.Cells[16, 1].Style.Numberformat.NumFmtID | Should be 47 # Set as mmss.0 - $ws.Cells[11, 1].Style.Numberformat.NumFmtID | Should be 49 # Set as "Text" - $ws.Cells[31, 1].Style.Numberformat.NumFmtID | Should be 49 # Set as @ - $ws.Cells[24, 1].Style.Numberformat.Format | Should be '#,' # Whole thousands - $ws.Cells[25, 1].Style.Numberformat.Format | Should be '#.0,,' # Millions + $ws.Cells[ 1, 1].Style.Numberformat.NumFmtID | Should -Be 0 # Set as General + $ws.Cells[20, 1].Style.Numberformat.NumFmtID | Should -Be 1 # Set as 0 + $ws.Cells[ 2, 1].Style.Numberformat.NumFmtID | Should -Be 2 # Set as "Number" + $ws.Cells[21, 1].Style.Numberformat.NumFmtID | Should -Be 2 # Set as 0.00 + $ws.Cells[22, 1].Style.Numberformat.NumFmtID | Should -Be 3 # Set as #,##0 + $ws.Cells[23, 1].Style.Numberformat.NumFmtID | Should -Be 4 # Set as #,##0.00 + $ws.Cells[26, 1].Style.Numberformat.NumFmtID | Should -Be 9 # Set as 0% + $ws.Cells[27, 1].Style.Numberformat.NumFmtID | Should -Be 10 # Set as 0.00% + $ws.Cells[ 3, 1].Style.Numberformat.NumFmtID | Should -Be 10 # Set as "Percentage" + $ws.Cells[28, 1].Style.Numberformat.NumFmtID | Should -Be 11 # Set as 0.00E+00 + $ws.Cells[ 4, 1].Style.Numberformat.NumFmtID | Should -Be 11 # Set as "Scientific" + $ws.Cells[ 5, 1].Style.Numberformat.NumFmtID | Should -Be 12 # Set as "Fraction" + $ws.Cells[29, 1].Style.Numberformat.NumFmtID | Should -Be 12 # Set as # ?/? + $ws.Cells[30, 1].Style.Numberformat.NumFmtID | Should -Be 13 # Set as # ??/? + $ws.Cells[ 6, 1].Style.Numberformat.NumFmtID | Should -Be 14 # Set as "Short date" + $ws.Cells[17, 1].Style.Numberformat.NumFmtID | Should -Be 15 # Set as d-mmm-yy + $ws.Cells[18, 1].Style.Numberformat.NumFmtID | Should -Be 16 # Set as d-mmm + $ws.Cells[19, 1].Style.Numberformat.NumFmtID | Should -Be 17 # Set as mmm-yy + $ws.Cells[12, 1].Style.Numberformat.NumFmtID | Should -Be 18 # Set as h:mm AM/PM + $ws.Cells[13, 1].Style.Numberformat.NumFmtID | Should -Be 19 # Set as h:mm:ss AM/PM + $ws.Cells[ 7, 1].Style.Numberformat.NumFmtID | Should -Be 20 # Set as "Short time" + $ws.Cells[ 8, 1].Style.Numberformat.NumFmtID | Should -Be 21 # Set as "Long time" + $ws.Cells[ 9, 1].Style.Numberformat.NumFmtID | Should -Be 22 # Set as "Date-time" + $ws.Cells[14, 1].Style.Numberformat.NumFmtID | Should -Be 45 # Set as mm:ss + $ws.Cells[15, 1].Style.Numberformat.NumFmtID | Should -Be 46 # Set as [h]:mm:ss + $ws.Cells[16, 1].Style.Numberformat.NumFmtID | Should -Be 47 # Set as mmss.0 + $ws.Cells[11, 1].Style.Numberformat.NumFmtID | Should -Be 49 # Set as "Text" + $ws.Cells[31, 1].Style.Numberformat.NumFmtID | Should -Be 49 # Set as @ + $ws.Cells[24, 1].Style.Numberformat.Format | Should -Be '#,' # Whole thousands + $ws.Cells[25, 1].Style.Numberformat.Format | Should -Be '#.0,,' # Millions } } } @@ -155,70 +155,70 @@ Describe "Set-ExcelColumn, Set-ExcelRow and Set-ExcelRange" { } Context "Set-ExcelRow and Set-ExcelColumn" { it "Set a row and a column to have zero width/height " { - $r | Should not beNullorEmpty - # $c | Should not beNullorEmpty ## can't see why but this test breaks in appveyor - $ws.Column(1).width | Should be 0 - $ws.Row(5).height | Should be 0 + $r | Should -Not -BeNullorEmpty + # $c | Should -Not -BeNullorEmpty ## can't see why but this test breaks in appveyor + $ws.Column(1).width | Should -Be 0 + $ws.Row(5).height | Should -Be 0 } it "Set a column formula, with numberformat, color, bold face and alignment " { - $ws.Cells["e2"].Formula | Should be "Quantity*Price" - $ws.Cells["e2"].Value | Should be 147.63 - $ws.Cells["e2"].Style.Font.Color.rgb | Should be "FF0000FF" - $ws.Cells["e2"].Style.Font.Bold | Should be $true - $ws.Cells["e2"].Style.Font.VerticalAlign | Should be "None" - $ws.Cells["e2"].Style.Numberformat.format | Should be "£#,###.00" - $ws.Cells["e2"].Style.HorizontalAlignment | Should be "Right" + $ws.Cells["e2"].Formula | Should -Be "Quantity*Price" + $ws.Cells["e2"].Value | Should -Be 147.63 + $ws.Cells["e2"].Style.Font.Color.rgb | Should -Be "FF0000FF" + $ws.Cells["e2"].Style.Font.Bold | Should -Be $true + $ws.Cells["e2"].Style.Font.VerticalAlign | Should -Be "None" + $ws.Cells["e2"].Style.Numberformat.format | Should -Be "£#,###.00" + $ws.Cells["e2"].Style.HorizontalAlignment | Should -Be "Right" } } Context "Other formatting" { it "Trapped an attempt to hide a range instead of a Row/Column " { - $BadHideWarnvar | Should not beNullOrEmpty + $BadHideWarnvar | Should -Not -BeNullOrEmpty } it "Set and calculated a row formula with border font size and underline " { - $ws.Cells["b7"].Style.Border.Top.Style | Should be "None" - $ws.Cells["F7"].Style.Border.Top.Style | Should be "None" - $ws.Cells["C7"].Style.Border.Top.Style | Should be "Thin" - $ws.Cells["C7"].Style.Border.Bottom.Style | Should be "Thin" - $ws.Cells["C7"].Style.Border.Right.Style | Should be "None" - $ws.Cells["C7"].Style.Border.Left.Style | Should be "Thin" - $ws.Cells["E7"].Style.Border.Left.Style | Should be "None" - $ws.Cells["E7"].Style.Border.Right.Style | Should be "Thin" - $ws.Cells["C7"].Style.Font.size | Should be 14 - $ws.Cells["C7"].Formula | Should be "sum(C2:C6)" - $ws.Cells["C7"].value | Should be 81 - $ws.Cells["C7"].Style.Font.UnderLine | Should be $true - $ws.Cells["C6"].Style.Font.UnderLine | Should be $false + $ws.Cells["b7"].Style.Border.Top.Style | Should -Be "None" + $ws.Cells["F7"].Style.Border.Top.Style | Should -Be "None" + $ws.Cells["C7"].Style.Border.Top.Style | Should -Be "Thin" + $ws.Cells["C7"].Style.Border.Bottom.Style | Should -Be "Thin" + $ws.Cells["C7"].Style.Border.Right.Style | Should -Be "None" + $ws.Cells["C7"].Style.Border.Left.Style | Should -Be "Thin" + $ws.Cells["E7"].Style.Border.Left.Style | Should -Be "None" + $ws.Cells["E7"].Style.Border.Right.Style | Should -Be "Thin" + $ws.Cells["C7"].Style.Font.size | Should -Be 14 + $ws.Cells["C7"].Formula | Should -Be "sum(C2:C6)" + $ws.Cells["C7"].value | Should -Be 81 + $ws.Cells["C7"].Style.Font.UnderLine | Should -Be $true + $ws.Cells["C6"].Style.Font.UnderLine | Should -Be $false } it "Set custom font, size, text-wrapping, alignment, superscript, border and Fill " { - $ws.Cells["b3"].Style.Border.Left.Color.Rgb | Should be "FFFF0000" - $ws.Cells["b3"].Style.Border.Left.Style | Should be "Thick" - $ws.Cells["b3"].Style.Border.Right.Style | Should be "Thick" - $ws.Cells["b3"].Style.Border.Top.Style | Should be "Thick" - $ws.Cells["b3"].Style.Border.Bottom.Style | Should be "Thick" - $ws.Cells["b3"].Style.Font.Strike | Should be $true - $ws.Cells["e1"].Style.Font.Color.Rgb | Should be "ff000000" - $ws.Cells["e1"].Style.Font.Bold | Should be $false - $ws.Cells["e1"].Style.Font.Name | Should be "Courier New" - $ws.Cells["e1"].Style.Font.Size | Should be 9 - $ws.Cells["e3"].Style.Font.VerticalAlign | Should be "Superscript" - $ws.Cells["e3"].Style.HorizontalAlignment | Should be "Left" - $ws.Cells["C6"].Style.WrapText | Should be $false - $ws.Cells["e7"].Style.WrapText | Should be $true - $ws.Cells["e7"].Style.Fill.BackgroundColor.Rgb | Should be "FFF0F8FF" - $ws.Cells["e7"].Style.Fill.PatternColor.Rgb | Should be "FFFF0000" - $ws.Cells["e7"].Style.Fill.PatternType | Should be "DarkTrellis" + $ws.Cells["b3"].Style.Border.Left.Color.Rgb | Should -Be "FFFF0000" + $ws.Cells["b3"].Style.Border.Left.Style | Should -Be "Thick" + $ws.Cells["b3"].Style.Border.Right.Style | Should -Be "Thick" + $ws.Cells["b3"].Style.Border.Top.Style | Should -Be "Thick" + $ws.Cells["b3"].Style.Border.Bottom.Style | Should -Be "Thick" + $ws.Cells["b3"].Style.Font.Strike | Should -Be $true + $ws.Cells["e1"].Style.Font.Color.Rgb | Should -Be "ff000000" + $ws.Cells["e1"].Style.Font.Bold | Should -Be $false + $ws.Cells["e1"].Style.Font.Name | Should -Be "Courier New" + $ws.Cells["e1"].Style.Font.Size | Should -Be 9 + $ws.Cells["e3"].Style.Font.VerticalAlign | Should -Be "Superscript" + $ws.Cells["e3"].Style.HorizontalAlignment | Should -Be "Left" + $ws.Cells["C6"].Style.WrapText | Should -Be $false + $ws.Cells["e7"].Style.WrapText | Should -Be $true + $ws.Cells["e7"].Style.Fill.BackgroundColor.Rgb | Should -Be "FFF0F8FF" + $ws.Cells["e7"].Style.Fill.PatternColor.Rgb | Should -Be "FFFF0000" + $ws.Cells["e7"].Style.Fill.PatternType | Should -Be "DarkTrellis" } } Context "Set-ExcelRange value setting " { it "Inserted a formula " { - $ws.Cells["D7"].Formula | Should be "E7/C7" + $ws.Cells["D7"].Formula | Should -Be "E7/C7" } it "Inserted a value " { - $ws.Cells["B7"].Value | Should be "Total" + $ws.Cells["B7"].Value | Should -Be "Total" } it "Inserted a date with localized date-time format " { - $ws.Cells["B8"].Style.Numberformat.NumFmtID | Should be 22 + $ws.Cells["B8"].Style.Numberformat.NumFmtID | Should -Be 22 } } @@ -249,27 +249,27 @@ Describe "Set-ExcelColumn, Set-ExcelRow and Set-ExcelRange" { $ws = $excel.Workbook.Worksheets["Sheet1"] } It "Inserted Hyperlinks " { - $ws.Cells["D2"].Hyperlink | Should not beNullorEmpty - $ws.Cells["D2"].Style.Font.UnderLine | Should be $true + $ws.Cells["D2"].Hyperlink | Should -Not -BeNullorEmpty + $ws.Cells["D2"].Style.Font.UnderLine | Should -Be $true } It "Inserted and formatted Dates " { - $ws.Cells["C2"].Value.GetType().name | should be "DateTime" - $ws.Cells["C2"].Style.Numberformat.NumFmtID | should be 14 - $ws.Cells["E2"].Value.GetType().name | should be "DateTime" - $ws.Cells["E2"].Style.Numberformat.NumFmtID | should be 14 + $ws.Cells["C2"].Value.GetType().name | Should -Be "DateTime" + $ws.Cells["C2"].Style.Numberformat.NumFmtID | Should -Be 14 + $ws.Cells["E2"].Value.GetType().name | Should -Be "DateTime" + $ws.Cells["E2"].Style.Numberformat.NumFmtID | Should -Be 14 } It "Inserted Formulas " { - $ws.Cells["F2"].Formula | Should not beNullorEmpty + $ws.Cells["F2"].Formula | Should -Not -BeNullorEmpty } It "Created Named ranges " { - $ws.Names.Count | Should be 6 - $ws.Names["Age"] | Should not beNullorEmpty - $ws.Names["Age"].Start.Column | Should be 6 - $ws.Names["Age"].Start.Row | Should be 2 - $ws.Names["Age"].End.Row | Should be 7 - $ws.names[0].name | Should be "Name" - $ws.Names[0].Start.Column | Should be 1 - $ws.Names[0].Start.Row | Should be 2 + $ws.Names.Count | Should -Be 6 + $ws.Names["Age"] | Should -Not -BeNullorEmpty + $ws.Names["Age"].Start.Column | Should -Be 6 + $ws.Names["Age"].Start.Row | Should -Be 2 + $ws.Names["Age"].End.Row | Should -Be 7 + $ws.names[0].name | Should -Be "Name" + $ws.Names[0].Start.Column | Should -Be 1 + $ws.Names[0].Start.Row | Should -Be 2 } } @@ -286,9 +286,9 @@ Describe "Conditional Formatting" { } Context "Using a pre-prepared 3 Arrows rule" { it "Set the right type, IconSet and range " { - $ws.ConditionalFormatting[0].IconSet | Should be "Arrows" - $ws.ConditionalFormatting[0].Address.Address | Should be "c:c" - $ws.ConditionalFormatting[0].Type.ToString() | Should be "ThreeIconSet" + $ws.ConditionalFormatting[0].IconSet | Should -Be "Arrows" + $ws.ConditionalFormatting[0].Address.Address | Should -Be "c:c" + $ws.ConditionalFormatting[0].Type.ToString() | Should -Be "ThreeIconSet" } } @@ -329,8 +329,8 @@ Sold $ws = $excel.Workbook.Worksheets["Sheet1"] - $ws.Names.Count | Should Be 1 - $ws.Names[0].Name | Should Be 'Sold' + $ws.Names.Count | Should -Be 1 + $ws.Names[0].Name | Should -Be 'Sold' } it "Should have a more than a single item as a named range " { @@ -344,9 +344,9 @@ Sold,ID $ws = $excel.Workbook.Worksheets["Sheet1"] - $ws.Names.Count | Should Be 2 - $ws.Names[0].Name | Should Be 'Sold' - $ws.Names[1].Name | Should Be 'ID' + $ws.Names.Count | Should -Be 2 + $ws.Names[0].Name | Should -Be 'Sold' + $ws.Names[1].Name | Should -Be 'ID' } } @@ -368,20 +368,20 @@ Describe "Table Formatting" { } Context "Setting and not clearing when Export-Excel touches the file again." { it "Set the Table Options " { - $ws1.Tables[0].Address.Address | should be "A1:E16" - $ws1.Tables[0].Name | should be "HardwareTable" - $ws1.Tables[0].ShowFirstColumn | should be $true - $ws1.Tables[0].ShowLastColumn | should not be $true - $ws1.Tables[0].ShowTotal | should be $true - $ws1.Tables[0].Columns["Total"].TotalsRowFunction | Should be "Sum" - $ws1.Tables[0].StyleName | should be "TableStyleLight1" - $ws1.Cells["D4"].Style.Numberformat.Format | Should match ([regex]::Escape([cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol)) - $ws1.Cells["E5"].Style.Numberformat.Format | Should match ([regex]::Escape([cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol)) + $ws1.Tables[0].Address.Address | Should -Be "A1:E16" + $ws1.Tables[0].Name | Should -Be "HardwareTable" + $ws1.Tables[0].ShowFirstColumn | Should -Be $true + $ws1.Tables[0].ShowLastColumn | Should -Not -Be $true + $ws1.Tables[0].ShowTotal | Should -Be $true + $ws1.Tables[0].Columns["Total"].TotalsRowFunction | Should -Be "Sum" + $ws1.Tables[0].StyleName | Should -Be "TableStyleLight1" + $ws1.Cells["D4"].Style.Numberformat.Format | Should -Match ([regex]::Escape([cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol)) + $ws1.Cells["E5"].Style.Numberformat.Format | Should -Match ([regex]::Escape([cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol)) } it "Set the Pivot Options " { - $ws2.PivotTables[0].DataFields[0].Format | Should match ([regex]::Escape([cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol)) - $ws2.PivotTables[0].ColumGrandTotals | Should be $false - $ws2.PivotTables[0].StyleName | Should be "PivotStyleDark2" + $ws2.PivotTables[0].DataFields[0].Format | Should -Match ([regex]::Escape([cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol)) + $ws2.PivotTables[0].ColumGrandTotals | Should -Be $false + $ws2.PivotTables[0].StyleName | Should -Be "PivotStyleDark2" } } } \ No newline at end of file diff --git a/__tests__/Validation.tests.ps1 b/__tests__/Validation.tests.ps1 index c2651fe..080f7f0 100644 --- a/__tests__/Validation.tests.ps1 +++ b/__tests__/Validation.tests.ps1 @@ -28,30 +28,30 @@ Describe "Data validation and protection" { $ws = $excelPackage.Sales } It "Created the expected number of rules " { - $ws.DataValidations.count | Should be 2 + $ws.DataValidations.count | Should -Be 2 } It "Created a List validation rule against a range of Cells " { - $ws.DataValidations[0].ValidationType.Type.tostring() | Should be 'List' - $ws.DataValidations[0].Formula.ExcelFormula | Should be 'values!$a$1:$a$10' - $ws.DataValidations[0].Formula2 | Should benullorempty + $ws.DataValidations[0].ValidationType.Type.tostring() | Should -Be 'List' + $ws.DataValidations[0].Formula.ExcelFormula | Should -Be 'values!$a$1:$a$10' + $ws.DataValidations[0].Formula2 | Should -Benullorempty } It "Created an integer validation rule for values between X and Y " { - $ws.DataValidations[1].ValidationType.Type.tostring() | Should be 'Whole' - $ws.DataValidations[1].Formula.Value | Should be 0 - $ws.DataValidations[1].Formula2.value | Should not benullorempty - $ws.DataValidations[1].Operator.tostring() | should be 'between' + $ws.DataValidations[1].ValidationType.Type.tostring() | Should -Be 'Whole' + $ws.DataValidations[1].Formula.Value | Should -Be 0 + $ws.DataValidations[1].Formula2.value | Should -Not -Benullorempty + $ws.DataValidations[1].Operator.tostring() | Should -Be 'between' } It "Set Error behaviors for both rules " { - $ws.DataValidations[0].ErrorStyle.tostring() | Should be 'stop' - $ws.DataValidations[1].ErrorStyle.tostring() | Should be 'stop' - $ws.DataValidations[0].AllowBlank | Should be $true - $ws.DataValidations[1].AllowBlank | Should be $true - $ws.DataValidations[0].ShowErrorMessage | Should be $true - $ws.DataValidations[1].ShowErrorMessage | Should be $true - $ws.DataValidations[0].ErrorTitle | Should not benullorempty - $ws.DataValidations[1].ErrorTitle | Should not benullorempty - $ws.DataValidations[0].Error | Should not benullorempty - $ws.DataValidations[1].Error | Should not benullorempty + $ws.DataValidations[0].ErrorStyle.tostring() | Should -Be 'stop' + $ws.DataValidations[1].ErrorStyle.tostring() | Should -Be 'stop' + $ws.DataValidations[0].AllowBlank | Should -Be $true + $ws.DataValidations[1].AllowBlank | Should -Be $true + $ws.DataValidations[0].ShowErrorMessage | Should -Be $true + $ws.DataValidations[1].ShowErrorMessage | Should -Be $true + $ws.DataValidations[0].ErrorTitle | Should -Not -Benullorempty + $ws.DataValidations[1].ErrorTitle | Should -Not -Benullorempty + $ws.DataValidations[0].Error | Should -Not -Benullorempty + $ws.DataValidations[1].Error | Should -Not -Benullorempty } } From e65210e3788746ab9aa3af18a45d47dece3e3119 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Mon, 30 Dec 2019 00:34:40 +0000 Subject: [PATCH 06/12] Fix test not working with single digit dates. --- Examples/Pester-To-XLSx.ps1 | 96 ++++++++++++---------- __tests__/ConvertFrom-ExcelSheet.Tests.ps1 | 2 +- 2 files changed, 53 insertions(+), 45 deletions(-) diff --git a/Examples/Pester-To-XLSx.ps1 b/Examples/Pester-To-XLSx.ps1 index c4ec038..4c65e19 100644 --- a/Examples/Pester-To-XLSx.ps1 +++ b/Examples/Pester-To-XLSx.ps1 @@ -1,5 +1,4 @@  - [CmdletBinding(DefaultParameterSetName = 'Default')] param( [Parameter(Position=0)] @@ -8,11 +7,11 @@ param( [Parameter(ParameterSetName='Default',Position=1)] [Alias('Path', 'relative_path')] [object[]]$Script = '.', - + [Parameter(ParameterSetName='Existing',Mandatory=$true)] [switch] $UseExisting, - + [Parameter(ParameterSetName='Default', Position=2)] [Parameter(ParameterSetName='Existing',Position=2, Mandatory=$true)] [string]$OutputFile, @@ -20,38 +19,39 @@ param( [Parameter(ParameterSetName='Default')] [Alias("Name")] [string[]]$TestName, - + [Parameter(ParameterSetName='Default')] [switch]$EnableExit, - + [Parameter(ParameterSetName='Default')] [Alias('Tags')] [string[]]$Tag, [string[]]$ExcludeTag, - + [Parameter(ParameterSetName='Default')] - [Switch]$Strict, + [switch]$Strict, - [String]$WorkSheetName = 'PesterResults', - - [switch]$Show + [string]$WorkSheetName = 'PesterResults', + [switch]$append, + [switch]$Show ) $InvokePesterParams = @{OutputFormat = 'NUnitXml'} + $PSBoundParameters -if (-not $InvokePesterParams['OutputFile']) { +if (-not $InvokePesterParams['OutputFile']) { $InvokePesterParams['OutputFile'] = Join-Path -ChildPath 'Pester.xml'-Path ([environment]::GetFolderPath([System.Environment+SpecialFolder]::MyDocuments)) } if ($InvokePesterParams['Show'] ) {} if ($InvokePesterParams['XLFile']) {$InvokePesterParams.Remove('XLFile')} else {$XLFile = $InvokePesterParams['OutputFile'] -replace '.xml$','.xlsx'} if (-not $UseExisting) { + $InvokePesterParams.Remove('Append') $InvokePesterParams.Remove('UseExisting') $InvokePesterParams.Remove('Show') $InvokePesterParams.Remove('WorkSheetName') Invoke-Pester @InvokePesterParams } -if (-not (Test-Path -Path $InvokePesterParams['OutputFile'])) { - throw "Could not output file $($InvokePesterParams['OutputFile'])"; return +if (-not (Test-Path -Path $InvokePesterParams['OutputFile'])) { + throw "Could not output file $($InvokePesterParams['OutputFile'])"; return } $resultXML = ([xml](Get-Content $InvokePesterParams['OutputFile'])).'test-results' @@ -59,37 +59,44 @@ $startDate = [datetime]$resultXML.date $startTime = $resultXML.time $machine = $resultXML.environment.'machine-name' #$user = $resultXML.environment.'user-domain' + '\' + $resultXML.environment.user -$os = $resultXML.environment.platform -replace '\|.*$'," $($resultXML.environment.'os-version')" -<#hierarchy goes +$os = $resultXML.environment.platform -replace '\|.*$'," $($resultXML.environment.'os-version')" +<#hierarchy goes root, [date], start [time], [Name] (always "Pester"), test results broken down as [total],[errors],[failures],[not-run] etc. - Environment (user & machine info) + Environment (user & machine info) Culture-Info (current, and currentUi culture) - Test-Suite [name] = "Pester" [result], [time] to execute, etc. + Test-Suite [name] = "Pester" [result], [time] to execute, etc. Results - Test-Suite [name] = filename,[result], [Time] to Execute etc + Test-Suite [name] = filename,[result], [Time] to Execute etc Results Test-Suite [Name] = Describe block Name, [result], [Time] to execute etc.. Results Test-Suite [Name] = Context block name [result], [Time] to execute etc. - Results - Test-Case [name] = Describe.Context.It block names [description]= it block name, result], [Time] to execute etc - + Results + Test-Case [name] = Describe.Context.It block names [description]= it block name, result], [Time] to execute etc + or if the tests are parameterized + Test suite [description] - name in the the it block with not filled in + Results + Test-case [description] - name as rendered for display with filled in #> $testResults = foreach ($test in $resultXML.'test-suite'.results.'test-suite') { - $testPs1File = $test.name + $testPs1File = $test.name #Test if there are context blocks in the hierarchy OR if we go straight from Describe to test-case if ($test.results.'test-suite'.results.'test-suite' -ne $null) { foreach ($suite in $test.results.'test-suite') { - $Describe = $suite.description + $Describe = $suite.description foreach ($subsuite in $suite.results.'test-suite') { $Context = $subsuite.description - $subsuite.results.'test-case'| ForEach-Object { + if ($subsuite.results.'test-suite'.results.'test-case') { + $testCases = $subsuite.results.'test-suite'.results.'test-case' + } + else {$testCases = $subsuite.results.'test-case'} + $testCases | ForEach-Object { New-Object -TypeName psobject -Property ([ordered]@{ Machine = $machine ; OS = $os - Date = $startDate ; Time = $startTime - Executed = $_.executed ; Result = $_.result ; Duration = $_.time + Date = $startDate ; Time = $startTime + Executed = $_.executed ; Result = $_.result ; Duration = $_.time File = $testPs1File; Group = $Describe ; SubGroup = $Context - Test =($_.Description -replace '\s{2,}', ' ') + Test =($_.Description -replace '\s{2,}', ' ') FullDesc = '=Group&" "&SubGroup&" "&Test'}) } } @@ -97,37 +104,38 @@ $testResults = foreach ($test in $resultXML.'test-suite'.results.'test-suite') { } else { $test.results.'test-suite' | ForEach-Object { - $Describe = $_.description + $Describe = $_.description $_.results.'test-case'| ForEach-Object { New-Object -TypeName psobject -Property ([ordered]@{ Machine = $machine ; OS = $os - Date = $startDate ; Time = $startTime - Executed = $_.executed ; Result = $_.result ; Duration = $_.time - File = $testPs1File; Group = $Describe ; SubGroup = $null + Date = $startDate ; Time = $startTime + Executed = $_.executed ; Result = $_.result ; Duration = $_.time + File = $testPs1File; Group = $Describe ; SubGroup = $null Test =($_.Description -replace '\s{2,}', ' ') FullDesc = '=Group&" "&Test'}) } } } } +if (-not $testResults) {Write-Warning 'No Results found' ; return} +$clearSheet = -not $Append +$excel = $testResults | Export-Excel -Path $xlFile -WorkSheetname $WorkSheetName -ClearSheet:$clearSheet -Append:$append -PassThru -BoldTopRow -FreezeTopRow -AutoSize -AutoFilter -AutoNameRange +$ws = $excel.Workbook.Worksheets[$WorkSheetName] -$excel = $testResults | Export-Excel -Path $xlFile -WorkSheetname $WorkSheetName -ClearSheet -PassThru -BoldTopRow -FreezeTopRow -AutoSize -AutoFilter -AutoNameRange -$ws = $excel.Workbook.Worksheets["PesterResults"] - -<# Worksheet should look like ... - |A |B |C D |E |F |G |H |I |J |K |L - 1|Machine |OS |Date Time |Executed |Result |Duration |File |Group |SubGroup |Test |FullDescription - 2|Flatfish |Name_Version |[run started] |Boolean |Success |In seconds |xx.ps1 |Describe |Context |It |Desc_Context_It -#> +<# Worksheet should look like ... + |A |B |C D |E |F |G |H |I |J |K |L + 1|Machine |OS |Date Time |Executed |Result |Duration |File |Group |SubGroup |Test |FullDescription + 2|Flatfish |Name_Version |[run started] |Boolean |Success |In seconds |xx.ps1 |Describe |Context |It |Desc_Context_It +#> #Display Date as a date, not a date time Set-Column -Worksheet $ws -Column 3 -NumberFormat 'Short Date' # -AutoSize -#Hide columns G to K (the file and the parts of the description, and the duration)5 -(7..10) + 5 | ForEach-Object {Set-ExcelColumn -Worksheet $ws -Column $_ -Hide } +#Hide columns G to K (the file and the parts of the description, and the duration)5 +(7..10) + 5 | ForEach-Object {Set-ExcelColumn -Worksheet $ws -Column $_ -Hide } -#Use conditional formatting to make Failures red, and Successes green (skipped remains black ) ... and save +#Use conditional formatting to make Failures red, and Successes green (skipped remains black ) ... and save $endRow = $ws.Dimension.End.Row -Add-ConditionalFormatting -WorkSheet $ws -range "f2:f$endrow" -RuleType ContainsText -ConditionValue "Failure" -BackgroundPattern None -ForegroundColor Red -Bold -Add-ConditionalFormatting -WorkSheet $ws -range "f2:f$endRow" -RuleType ContainsText -ConditionValue "Success" -BackgroundPattern None -ForeGroundColor Green +Add-ConditionalFormatting -WorkSheet $ws -range "f2:f$endrow" -RuleType ContainsText -ConditionValue "Failure" -BackgroundPattern None -ForegroundColor Red -Bold +Add-ConditionalFormatting -WorkSheet $ws -range "f2:f$endRow" -RuleType ContainsText -ConditionValue "Success" -BackgroundPattern None -ForeGroundColor Green Close-ExcelPackage -ExcelPackage $excel -Show:$show diff --git a/__tests__/ConvertFrom-ExcelSheet.Tests.ps1 b/__tests__/ConvertFrom-ExcelSheet.Tests.ps1 index 3702d87..127882e 100644 --- a/__tests__/ConvertFrom-ExcelSheet.Tests.ps1 +++ b/__tests__/ConvertFrom-ExcelSheet.Tests.ps1 @@ -29,7 +29,7 @@ Describe 'ConvertFrom-ExcelSheet / Export-ExcelSheet' { $secondText[1] | Should -Belike "*$date*" $secondText[1] | Should -Match '"0\d","\w+","\d{1,2}"$' $ThirdText[1] | Should -Match '^"\w+ \w+","#\d\d/\d\d/\d{4}#","\d","0\d"$' - $FourthText[1] | Should -Match '^"\w+","[012]\d' + $FourthText[1] | Should -Match '^"\w+","([012]\d/|[1-9]/)' } } Context "Export aliased to ConvertFrom" { From 17ec0400556210a4bf0d8a98eb4decbd4ae80f7b Mon Sep 17 00:00:00 2001 From: jhoneill Date: Tue, 31 Dec 2019 19:38:28 +0000 Subject: [PATCH 07/12] fix message in merge, improve pester example --- Examples/Pester-To-XLSx.ps1 | 39 ++++++++++++++++++--------------- Public/Merge-MultipleSheets.ps1 | 2 +- Public/Merge-Worksheet.ps1 | 2 +- 3 files changed, 23 insertions(+), 20 deletions(-) diff --git a/Examples/Pester-To-XLSx.ps1 b/Examples/Pester-To-XLSx.ps1 index 4c65e19..85b6933 100644 --- a/Examples/Pester-To-XLSx.ps1 +++ b/Examples/Pester-To-XLSx.ps1 @@ -1,5 +1,4 @@ - -[CmdletBinding(DefaultParameterSetName = 'Default')] +[CmdletBinding(DefaultParameterSetName = 'Default')] param( [Parameter(Position=0)] [string]$XLFile, @@ -94,10 +93,12 @@ $testResults = foreach ($test in $resultXML.'test-suite'.results.'test-suite') { New-Object -TypeName psobject -Property ([ordered]@{ Machine = $machine ; OS = $os Date = $startDate ; Time = $startTime - Executed = $_.executed ; Result = $_.result ; Duration = $_.time - File = $testPs1File; Group = $Describe ; SubGroup = $Context - Test =($_.Description -replace '\s{2,}', ' ') - FullDesc = '=Group&" "&SubGroup&" "&Test'}) + Executed = $(if ($_.executed -eq 'True') {1}) + Success = $(if ($_.success -eq 'True') {1}) + Duration = $_.time + File = $testPs1File; Group = $Describe + SubGroup = $Context ; Name =($_.Description -replace '\s{2,}', ' ') + Result = $_.result ; FullDesc = '=Group&" "&SubGroup&" "&Test'}) } } } @@ -109,10 +110,12 @@ $testResults = foreach ($test in $resultXML.'test-suite'.results.'test-suite') { New-Object -TypeName psobject -Property ([ordered]@{ Machine = $machine ; OS = $os Date = $startDate ; Time = $startTime - Executed = $_.executed ; Result = $_.result ; Duration = $_.time - File = $testPs1File; Group = $Describe ; SubGroup = $null - Test =($_.Description -replace '\s{2,}', ' ') - FullDesc = '=Group&" "&Test'}) + Executed = $(if ($_.executed -eq 'True') {1}) + Success = $(if ($_.success -eq 'True') {1}) + Duration = $_.time + File = $testPs1File; Group = $Describe + SubGroup = $null ; Name =($_.Description -replace '\s{2,}', ' ') + Result = $_.result ; FullDesc = '=Group&" "&Test'}) } } } @@ -122,20 +125,20 @@ $clearSheet = -not $Append $excel = $testResults | Export-Excel -Path $xlFile -WorkSheetname $WorkSheetName -ClearSheet:$clearSheet -Append:$append -PassThru -BoldTopRow -FreezeTopRow -AutoSize -AutoFilter -AutoNameRange $ws = $excel.Workbook.Worksheets[$WorkSheetName] -<# Worksheet should look like ... - |A |B |C D |E |F |G |H |I |J |K |L - 1|Machine |OS |Date Time |Executed |Result |Duration |File |Group |SubGroup |Test |FullDescription - 2|Flatfish |Name_Version |[run started] |Boolean |Success |In seconds |xx.ps1 |Describe |Context |It |Desc_Context_It +<# Worksheet should look like .. + |A |B |C D |E |F |G |H |I |J |K |L |M + 1|Machine |OS |Date Time |Executed |Success |Duration |File |Group |SubGroup |Name |Result |FullDescription + 2|Flatfish |Name_Version |[run started] |Boolean |Boolean |In seconds |xx.ps1 |Describe |Context |It |Success |Desc_Context_It #> #Display Date as a date, not a date time Set-Column -Worksheet $ws -Column 3 -NumberFormat 'Short Date' # -AutoSize -#Hide columns G to K (the file and the parts of the description, and the duration)5 -(7..10) + 5 | ForEach-Object {Set-ExcelColumn -Worksheet $ws -Column $_ -Hide } +#Hide columns E to J (Executed, Success, Duration, File, Group and Subgroup) +(5..10) | ForEach-Object {Set-ExcelColumn -Worksheet $ws -Column $_ -Hide } #Use conditional formatting to make Failures red, and Successes green (skipped remains black ) ... and save $endRow = $ws.Dimension.End.Row -Add-ConditionalFormatting -WorkSheet $ws -range "f2:f$endrow" -RuleType ContainsText -ConditionValue "Failure" -BackgroundPattern None -ForegroundColor Red -Bold -Add-ConditionalFormatting -WorkSheet $ws -range "f2:f$endRow" -RuleType ContainsText -ConditionValue "Success" -BackgroundPattern None -ForeGroundColor Green +Add-ConditionalFormatting -WorkSheet $ws -range "L2:L$endrow" -RuleType ContainsText -ConditionValue "Failure" -BackgroundPattern None -ForegroundColor Red -Bold +Add-ConditionalFormatting -WorkSheet $ws -range "L2:L$endRow" -RuleType ContainsText -ConditionValue "Success" -BackgroundPattern None -ForeGroundColor Green Close-ExcelPackage -ExcelPackage $excel -Show:$show diff --git a/Public/Merge-MultipleSheets.ps1 b/Public/Merge-MultipleSheets.ps1 index acffcb6..4e62402 100644 --- a/Public/Merge-MultipleSheets.ps1 +++ b/Public/Merge-MultipleSheets.ps1 @@ -1,4 +1,4 @@ -function Merge-MultipleSheets { +function Merge-MultipleSheets { [CmdletBinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification="False positives when initializing variable in begin block")] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification="MultipleSheet would be incorrect")] diff --git a/Public/Merge-Worksheet.ps1 b/Public/Merge-Worksheet.ps1 index 8a561a1..0963c28 100644 --- a/Public/Merge-Worksheet.ps1 +++ b/Public/Merge-Worksheet.ps1 @@ -118,7 +118,7 @@ $headings = $DifferenceObject[0].psobject.Properties.Name # This preserves the sequence - using Get-member would sort them alphabetically! There may be extra properties in if ($NoHeader -and "Name" -eq $Key) {$Key = "p1"} if ($headings -notcontains $Key -and - ('*' -ne $Key)) {Write-Warning -Message "You need to specify one of the headings in the sheet '$Worksheet1' as a key." ; return } + ('*' -ne $Key)) {Write-Warning -Message "You need to specify one of the headings in the sheet '$Worksheet2' as a key." ; return } foreach ($p in $Property) { $propList += ($headings.where({$_ -like $p}) )} foreach ($p in $ExcludeProperty) { $propList = $propList.where({$_ -notlike $p}) } if (($propList -notcontains $Key) -and From 7e75ecd0fb8601f00bd14bb84ad267c905c54a1c Mon Sep 17 00:00:00 2001 From: jhoneill Date: Tue, 31 Dec 2019 22:32:34 +0000 Subject: [PATCH 08/12] Add Subtotals & Groups example --- Examples/Subtotals.ps1 | 62 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Examples/Subtotals.ps1 diff --git a/Examples/Subtotals.ps1 b/Examples/Subtotals.ps1 new file mode 100644 index 0000000..24692ca --- /dev/null +++ b/Examples/Subtotals.ps1 @@ -0,0 +1,62 @@ +$excelpath = "$env:temp\subtotal.xlsx" +$SheetName = 'Sheet1' +$SubtotalFieldName = 'Net' +$GroupByFieldName = 'City' +$SubtotalFormula = '=SUBTOTAL(3,D{0}:D{1})' # {0} and {1} are placeholders for the first and last row. D is the column to total in + # 1=AVERAGE; 2=COUNT; 3=COUNTA; 4=MAX; 5=MIN; 6=PRODUCT; 7=STDEV; 8=STDEVP; 9=SUM; 10=VAR; 11=VARP add 100 to ignore hidden values + +Remove-Item -Path $excelpath -ErrorAction SilentlyContinue + +$Data = ConvertFrom-Csv @' +Product, City, Gross, Net +Apple, London , 300, 250 +Orange, London , 400, 350 +Banana, London , 300, 200 +Orange, Paris, 600, 500 +Banana, Paris, 300, 200 +Apple, New York, 1200,700 +'@ + +#at each change in the Group by field, insert a subtotal (count) formula in the title column & send to excel - list those rows and make them half height after export +$currentRow = 2 +$lastChangeRow = 2 +$insertedRows = @() +$hideRows = @() +$lastValue = $Data[0].$GroupByFieldName +$excel = $Data | ForEach-Object -Process { + if ($_.$GroupByFieldName -ne $lastvalue) { + $Formula = $SubtotalFormula -f $lastChangeRow, ($currentrow - 1) + if ($lastChangeRow -eq ($currentrow - 1)) {$hideRows += $CurrentRow } + else {$insertedRows += $CurrentRow } + [pscustomobject]@{$SubtotalFieldName=$Formula} + $currentRow += 1 + $lastChangeRow = $currentRow + $lastValue = $_.$GroupByFieldName + } + $_ + $currentRow += 1 +} -end { + $Formula = $SubtotalFormula -f $lastChangeRow, ($currentrow - 1) + [pscustomobject]@{$SubtotalFieldName=$Formula} +} | Export-Excel -Path $excelpath -PassThru -AutoSize -AutoFilter -BoldTopRow -WorksheetName $SheetName + +#We kept a lists of the total rows Since 1 rows won't get expand/collapse hide them. +#foreach ($r in $insertedrows) { $excel.WorkItems.Row($r).Height = 8} +foreach ($r in $hideRows) { $excel.$SheetName.Row($r).hidden = $true} +$range = $excel.$SheetName.Dimension.Address +$SheetIndex = $excel.Sheet1.Index +Close-ExcelPackage -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.Selection.AutoOutline() +$excelWorkBook.Save() +$excelWorkBook.Close() +$excelApp.Quit() + +Start $excelpath \ No newline at end of file From fe68ddbb0dd86e9fd1f3bfe01c4d2b9ce5509510 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Mon, 16 Mar 2020 11:07:30 +0000 Subject: [PATCH 09/12] New examples incl. Pester to XLSx --- Examples/Pester-To-XLSx.ps1 | 7 ++-- Examples/PsGallery.ps1 | 21 ++++++++++ Examples/Subtotals.ps1 | 76 ++++++++++++++++++++++--------------- 3 files changed, 71 insertions(+), 33 deletions(-) create mode 100644 Examples/PsGallery.ps1 diff --git a/Examples/Pester-To-XLSx.ps1 b/Examples/Pester-To-XLSx.ps1 index 85b6933..0eafcf8 100644 --- a/Examples/Pester-To-XLSx.ps1 +++ b/Examples/Pester-To-XLSx.ps1 @@ -1,4 +1,5 @@ -[CmdletBinding(DefaultParameterSetName = 'Default')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSPossibleIncorrectComparisonWithNull','',Justification='Intentional use to select non null array items')] +[CmdletBinding(DefaultParameterSetName = 'Default')] param( [Parameter(Position=0)] [string]$XLFile, @@ -49,6 +50,7 @@ if (-not $UseExisting) { $InvokePesterParams.Remove('WorkSheetName') Invoke-Pester @InvokePesterParams } + if (-not (Test-Path -Path $InvokePesterParams['OutputFile'])) { throw "Could not output file $($InvokePesterParams['OutputFile'])"; return } @@ -98,7 +100,7 @@ $testResults = foreach ($test in $resultXML.'test-suite'.results.'test-suite') { Duration = $_.time File = $testPs1File; Group = $Describe SubGroup = $Context ; Name =($_.Description -replace '\s{2,}', ' ') - Result = $_.result ; FullDesc = '=Group&" "&SubGroup&" "&Test'}) + Result = $_.result ; FullDesc = '=Group&" "&SubGroup&" "&Name'}) } } } @@ -124,7 +126,6 @@ if (-not $testResults) {Write-Warning 'No Results found' ; return} $clearSheet = -not $Append $excel = $testResults | Export-Excel -Path $xlFile -WorkSheetname $WorkSheetName -ClearSheet:$clearSheet -Append:$append -PassThru -BoldTopRow -FreezeTopRow -AutoSize -AutoFilter -AutoNameRange $ws = $excel.Workbook.Worksheets[$WorkSheetName] - <# Worksheet should look like .. |A |B |C D |E |F |G |H |I |J |K |L |M 1|Machine |OS |Date Time |Executed |Success |Duration |File |Group |SubGroup |Name |Result |FullDescription diff --git a/Examples/PsGallery.ps1 b/Examples/PsGallery.ps1 new file mode 100644 index 0000000..2e5c44b --- /dev/null +++ b/Examples/PsGallery.ps1 @@ -0,0 +1,21 @@ + +$top1000 = foreach ($p in 1..50) { + $c = Invoke-WebRequest -Uri "https://www.powershellgallery.com/packages" -method Post -Body "q=&sortOrder=package-download-count&page=$p" + [regex]::Matches($c.Content,'.*?
', [System.Text.RegularExpressions.RegexOptions]::Singleline) | foreach { + $name = [regex]::Match($_, "(?<=

).*(?=

)").value + $n = [regex]::replace($_,'^.*By:\s*
  • ','', [System.Text.RegularExpressions.RegexOptions]::Singleline) + $n = [regex]::replace($n,'.*$','', [System.Text.RegularExpressions.RegexOptions]::Singleline) + $by = [regex]::match($n,'(?<=">).*(?=)').value + $qty = [regex]::match($n,'\S*(?= downloads)').value + [PSCustomObject]@{ + Name = $name + by = $by + Downloads = $qty + } + } +} + +del "~\Documents\gallery.xlsx" +$pivotdef = New-PivotTableDefinition -PivotTableName 'Summary' -PivotRows by -PivotData @{name="Count" + Downloads="Sum"} -PivotDataToColumn -Activate -ChartType ColumnClustered -PivotNumberFormat '#,###' +$top1000 | export-excel -path '~\Documents\gallery.xlsx' -Numberformat '#,###' -PivotTableDefinition $pivotdef -TableName 'TopDownloads' -Show \ No newline at end of file diff --git a/Examples/Subtotals.ps1 b/Examples/Subtotals.ps1 index 24692ca..1e6bf0d 100644 --- a/Examples/Subtotals.ps1 +++ b/Examples/Subtotals.ps1 @@ -1,62 +1,78 @@ -$excelpath = "$env:temp\subtotal.xlsx" -$SheetName = 'Sheet1' -$SubtotalFieldName = 'Net' -$GroupByFieldName = 'City' -$SubtotalFormula = '=SUBTOTAL(3,D{0}:D{1})' # {0} and {1} are placeholders for the first and last row. D is the column to total in - # 1=AVERAGE; 2=COUNT; 3=COUNTA; 4=MAX; 5=MIN; 6=PRODUCT; 7=STDEV; 8=STDEVP; 9=SUM; 10=VAR; 11=VARP add 100 to ignore hidden values - -Remove-Item -Path $excelpath -ErrorAction SilentlyContinue - -$Data = ConvertFrom-Csv @' +$Data = ConvertFrom-Csv @' Product, City, Gross, Net Apple, London , 300, 250 Orange, London , 400, 350 Banana, London , 300, 200 +Grape, Munich, 100, 100 Orange, Paris, 600, 500 Banana, Paris, 300, 200 Apple, New York, 1200,700 '@ +$ExcelPath = "$env:temp\subtotal.xlsx" +$SheetName = 'Sheet1' +Remove-Item -Path $ExcelPath -ErrorAction SilentlyContinue + + +$GroupByFieldName = 'City' +$TotalSingleRows = $false +$GrandTotal = $false +$SubtotalRowHeight = 0 #If non zero will set subtotals to this height +$Subtotals =@{ 'Net' = {"=SUBTOTAL(3,D{0}:D{1})" -f $from, $to} + + +} +$SubtotalFieldName = 'Net' + +$SubtotalFormula = '=SUBTOTAL(3,D{0}:D{1})' # {0} and {1} are placeholders for the first and last row. D is the column to total in + # 1=AVERAGE; 2=COUNT; 3=COUNTA; 4=MAX; 5=MIN; 6=PRODUCT; 7=STDEV; 8=STDEVP; 9=SUM; 10=VAR; 11=VARP add 100 to ignore hidden values #at each change in the Group by field, insert a subtotal (count) formula in the title column & send to excel - list those rows and make them half height after export $currentRow = 2 $lastChangeRow = 2 $insertedRows = @() -$hideRows = @() +#$hideRows = @() $lastValue = $Data[0].$GroupByFieldName $excel = $Data | ForEach-Object -Process { - if ($_.$GroupByFieldName -ne $lastvalue) { - $Formula = $SubtotalFormula -f $lastChangeRow, ($currentrow - 1) - if ($lastChangeRow -eq ($currentrow - 1)) {$hideRows += $CurrentRow } - else {$insertedRows += $CurrentRow } - [pscustomobject]@{$SubtotalFieldName=$Formula} - $currentRow += 1 - $lastChangeRow = $currentRow - $lastValue = $_.$GroupByFieldName + if ($_.$GroupByFieldName -ne $lastvalue) { + if ($lastChangeRow -lt ($currentrow - 1) -or $totalSingleRows) { + $formula = $SubtotalFormula -f $lastChangeRow, ($currentrow - 1) + $insertedRows += $currentRow + [pscustomobject]@{$SubtotalFieldName = $formula} + $currentRow += 1 + } + $lastChangeRow = $currentRow + $lastValue = $_.$GroupByFieldName } $_ $currentRow += 1 } -end { - $Formula = $SubtotalFormula -f $lastChangeRow, ($currentrow - 1) - [pscustomobject]@{$SubtotalFieldName=$Formula} -} | Export-Excel -Path $excelpath -PassThru -AutoSize -AutoFilter -BoldTopRow -WorksheetName $SheetName + $formula = $SubtotalFormula -f $lastChangeRow, ($currentrow - 1) + [pscustomobject]@{$SubtotalFieldName=$formula} + if ($GrandTotal) { + $formula = $SubtotalFormula -f $lastChangeRow, ($currentrow - 1) + [pscustomobject]@{$SubtotalFieldName=$formula} + } +} | Export-Excel -Path $ExcelPath -PassThru -AutoSize -AutoFilter -BoldTopRow -WorksheetName $sheetName -#We kept a lists of the total rows Since 1 rows won't get expand/collapse hide them. -#foreach ($r in $insertedrows) { $excel.WorkItems.Row($r).Height = 8} -foreach ($r in $hideRows) { $excel.$SheetName.Row($r).hidden = $true} +#We kept a lists of the total rows. Since single rows won't get expanded/collapsed hide them. +if ($subtotalrowHeight) { + foreach ($r in $insertedrows) { $excel.WorkItems.Row($r).Height = $SubtotalRowHeight} +} +#foreach ($r in $hideRows) { $excel.$SheetName.Row($r).hidden = $true} $range = $excel.$SheetName.Dimension.Address -$SheetIndex = $excel.Sheet1.Index +$sheetIndex = $excel.Sheet1.Index Close-ExcelPackage -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) +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.Selection.AutoOutline() $excelWorkBook.Save() $excelWorkBook.Close() $excelApp.Quit() -Start $excelpath \ No newline at end of file +Start-Process $ExcelPath \ No newline at end of file From 3130020e20e3faaa1cacb4b83dcaf56d2cc99e1b Mon Sep 17 00:00:00 2001 From: jhoneill Date: Mon, 16 Mar 2020 11:10:44 +0000 Subject: [PATCH 10/12] apply freeze to 2 rows if title present #795 --- Public/Export-Excel.ps1 | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/Public/Export-Excel.ps1 b/Public/Export-Excel.ps1 index 5900aac..168e3a2 100644 --- a/Public/Export-Excel.ps1 +++ b/Public/Export-Excel.ps1 @@ -477,12 +477,24 @@ try { #Allow single switch or two seperate ones. if ($FreezeTopRowFirstColumn -or ($FreezeTopRow -and $FreezeFirstColumn)) { - $ws.View.FreezePanes(2, 2) - Write-Verbose -Message "Froze top row and first column" + if ($Title) { + $ws.View.FreezePanes(3, 2) + Write-Verbose -Message "Froze title and header rows and first column" + } + else { + $ws.View.FreezePanes(2, 2) + Write-Verbose -Message "Froze top row and first column" + } } elseif ($FreezeTopRow) { - $ws.View.FreezePanes(2, 1) - Write-Verbose -Message "Froze top row" + if ($Title) { + $ws.View.FreezePanes(2, 1) + Write-Verbose -Message "Froze title and header rows" + } + else { + $ws.View.FreezePanes(2, 1) + Write-Verbose -Message "Froze top row" + } } elseif ($FreezeFirstColumn) { $ws.View.FreezePanes(1, 2) From eb3a7d3f2da75e2d9d290a931a68c2ee066f316c Mon Sep 17 00:00:00 2001 From: jhoneill Date: Mon, 16 Mar 2020 11:15:40 +0000 Subject: [PATCH 11/12] Allow 0 or false to be a column heading --- Public/Import-Excel.ps1 | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/Public/Import-Excel.ps1 b/Public/Import-Excel.ps1 index 0afc8db..e5e6ce7 100644 --- a/Public/Import-Excel.ps1 +++ b/Public/Import-Excel.ps1 @@ -83,7 +83,8 @@ } foreach ($C in $Columns) { - $Worksheet.Cells[$StartRow, $C] | Where-Object { $_.Value } | Select-Object @{N = 'Column'; E = { $C } }, Value + #allow "False" or "0" to be column headings + $Worksheet.Cells[$StartRow, $C] | Where-Object {-not [string]::IsNullOrEmpty($_.Value) } | Select-Object @{N = 'Column'; E = { $C } }, Value } } } @@ -127,7 +128,7 @@ if ($DataOnly) { #If we are using headers startrow will be the header-row so examine data from startRow + 1, if ($NoHeader) { $range = "A" + ($StartRow ) + ":" + $endAddress } - else { $range = "A" + ($StartRow + 1 ) + ":" + $endAddress } + else { $range = "A" + ($StartRow + 1 ) + ":" + $endAddress } #We're going to look at every cell and build 2 hash tables holding rows & columns which contain data. #Want to Avoid 'select unique' operations & large Sorts, becuse time time taken increases with square #of number of items (PS uses heapsort at large size). Instead keep a list of what we have seen, @@ -137,14 +138,14 @@ foreach ($cell in $Worksheet.Cells[$range]) { if ($null -ne $cell.Value ) { $colHash[$cell.Start.Column] = 1; $rowHash[$cell.Start.row] = 1 } } - $rows = ( $StartRow..$EndRow ).Where( { $rowHash[$_] }) + $rows = ( $StartRow..$EndRow ).Where( { $rowHash[$_] }) $columns = ($StartColumn..$EndColumn).Where( { $colHash[$_] }) } else { - $Columns = $StartColumn .. $EndColumn ; if ($StartColumn -gt $EndColumn) { Write-Warning -Message "Selecting columns $StartColumn to $EndColumn might give odd results." } - if ($NoHeader) { $Rows = $StartRow..$EndRow ; if ($StartRow -gt $EndRow) { Write-Warning -Message "Selecting rows $StartRow to $EndRow might give odd results." } } + $Columns = $StartColumn .. $EndColumn ; if ($StartColumn -gt $EndColumn) { Write-Warning -Message "Selecting columns $StartColumn to $EndColumn might give odd results." } + if ($NoHeader) { $Rows = $StartRow..$EndRow ; if ($StartRow -gt $EndRow) { Write-Warning -Message "Selecting rows $StartRow to $EndRow might give odd results." } } elseif ($HeaderName) { $Rows = $StartRow..$EndRow } - else { $Rows = (1 + $StartRow)..$EndRow } # ; if ($StartRow -ge $EndRow) { Write-Warning -Message "Selecting $StartRow as the header with data in $(1+$StartRow) to $EndRow might give odd results." } } + else { $Rows = (1 + $StartRow)..$EndRow } # ; if ($StartRow -ge $EndRow) { Write-Warning -Message "Selecting $StartRow as the header with data in $(1+$StartRow) to $EndRow might give odd results." } } } #endregion #region Create property names From ae64a884fcf8f223775fbfdbe42d031402f2214c Mon Sep 17 00:00:00 2001 From: jhoneill Date: Mon, 16 Mar 2020 12:10:51 +0000 Subject: [PATCH 12/12] Put back asDate lost in merge --- Public/Import-Excel.ps1 | 45 +++++++++++++++++++++++++++-------------- 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/Public/Import-Excel.ps1 b/Public/Import-Excel.ps1 index 5fe1234..ba7d2b5 100644 --- a/Public/Import-Excel.ps1 +++ b/Public/Import-Excel.ps1 @@ -50,9 +50,9 @@ } function Get-PropertyNames { <# - .SYNOPSIS - Create objects containing the column number and the column name for each of the different header types. - #> + .SYNOPSIS + Create objects containing the column number and the column name for each of the different header types. + #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = "Name would be incorrect, and command is not exported")] param( [Parameter(Mandatory)] @@ -82,9 +82,10 @@ throw 'The top row can never be less than 1 when we need to retrieve headers from the worksheet.' ; return } - foreach ($C in $Columns) { - #allow "False" or "0" to be column headings - $Worksheet.Cells[$StartRow, $C] | Where-Object {-not [string]::IsNullOrEmpty($_.Value) } | Select-Object @{N = 'Column'; E = { $C } }, Value + foreach ($C in $Columns) { + #allow "False" or "0" to be column headings + $Worksheet.Cells[$StartRow, $C] | Where-Object {-not [string]::IsNullOrEmpty($_.Value) } | Select-Object @{N = 'Column'; E = { $C } }, Value + } } } catch { @@ -166,25 +167,39 @@ } else { #region Create one object per row - if ($AsText) { + if ($AsText -or $AsDate) { <#join items in AsText together with ~~~ . Escape any regex special characters... - # which turns "*" into "\*" make it ".*". Convert ~~~ to $|^ and top and tail with ^%; - So if we get "Week", "[Time]" and "*date*" ; make the expression ^week$|^\[Time\]$|^.*Date.*$ - $make a regex for this which is case insensitive (option 1) and compiled (option 8) - #> - $TextColExpression = "^" + [regex]::Escape($AsText -join "~~~").replace("\*", ".*").replace("~~~", "$|^") + "$" + # which turns "*" into "\*" make it ".*". Convert ~~~ to $|^ and top and tail with ^%; + So if we get "Week", "[Time]" and "*date*" ; make the expression ^week$|^\[Time\]$|^.*Date.*$ + $make a regex for this which is case insensitive (option 1) and compiled (option 8) + #> + $TextColExpression = '' + if ($AsText) { + $TextColExpression += '(?^' + [regex]::Escape($AsText -join '~~~').replace('\*', '.*').replace('~~~', '$|^') + '$)' + } + if ($AsText -and $AsDate) { + $TextColExpression += "|" + } + if ($AsDate) { + $TextColExpression += '(?^' + [regex]::Escape($AsDate -join '~~~').replace('\*', '.*').replace('~~~', '$|^') + '$)' + } $TextColRegEx = New-Object -TypeName regex -ArgumentList $TextColExpression , 9 } + else {$TextColRegEx = $null} foreach ($R in $Rows) { #Disabled write-verbose for speed # Write-Verbose "Import row '$R'" $NewRow = [Ordered]@{ } if ($TextColRegEx) { foreach ($P in $PropertyNames) { - if ($TextColRegEx.IsMatch($P.Value)) { - $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Text + $MatchTest = $TextColRegEx.Match($P.value) + if ($MatchTest.groups.name -eq "astext") { + $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Text } - else { $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Value } + elseif ($MatchTest.groups.name -eq "asdate" -and $Worksheet.Cells[$R, $P.Column].Value -is [System.ValueType]) { + $NewRow[$P.Value] = [datetime]::FromOADate(($Worksheet.Cells[$R, $P.Column].Value)) + } + else { $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Value } } } else {