diff --git a/AddConditionalFormatting.ps1 b/AddConditionalFormatting.ps1 index 99754f2..c96e1e3 100644 --- a/AddConditionalFormatting.ps1 +++ b/AddConditionalFormatting.ps1 @@ -122,7 +122,7 @@ $rule.Formula2 = $ConditionValue2 } - if ($NumberFormat) {$rule.Style.NumberFormat.Format = $NumberFormat } + if ($NumberFormat) {$rule.Style.NumberFormat.Format = (Expand-NumberFormat $NumberFormat) } if ($Underline) {$rule.Style.Font.Underline = [OfficeOpenXml.Style.ExcelUnderLineType]::Single } if ($Bold) {$rule.Style.Font.Bold = $true } if ($Italic) {$rule.Style.Font.Italic = $true } diff --git a/Export-Excel.ps1 b/Export-Excel.ps1 index e8d7659..32a1f0d 100644 --- a/Export-Excel.ps1 +++ b/Export-Excel.ps1 @@ -8,7 +8,7 @@ Path to a new or existing .XLSX file. .PARAMETER ExcelPackage An object representing an Excel Package - usually this is returned by specifying -Passthru allowing multiple commands to work on the same Workbook without saving and reloading each time. - .PARAMETER WorkSheetName + .PARAMETER WorksheetName The name of a sheet within the workbook - "Sheet1" by default. .PARAMETER ClearSheet If specified Export-Excel will remove any existing worksheet with the selected name. The Default behaviour is to overwrite cells in this sheet as needed (but leaving non-overwritten ones in place). @@ -123,6 +123,8 @@ Enables the 'Filter' in Excel on the complete header row. So users can easily sort, filter and/or search the data in the selected column from within Excel. .PARAMETER AutoSize Sizes the width of the Excel column to the maximum width needed to display all the containing data in that cell. + .PARAMETER Activate + If there is already content in the workbook, a new sheet will not be active UNLESS Activate is specified; if a Pivot table is included it will be the active sheet .PARAMETER Now The 'Now' switch is a shortcut that creates automatically a temporary file, enables 'AutoSize', 'AutoFiler' and 'Show', and opens the file immediately. .PARAMETER NumberFormat @@ -287,15 +289,15 @@ $Array = $Obj1, $Obj2, $Obj3 $Array | Out-GridView -Title 'Not showing Member3 and Member4' - $Array | Update-FirstObjectProperties | Export-Excel @ExcelParams -WorkSheetname Numbers + $Array | Update-FirstObjectProperties | Export-Excel @ExcelParams -WorksheetName Numbers Updates the first object of the array by adding property 'Member3' and 'Member4'. Afterwards. all objects are exported to an Excel file and all column headers are visible. .EXAMPLE - Get-Process | Export-Excel .\test.xlsx -WorkSheetname Processes -IncludePivotTable -Show -PivotRows Company -PivotData PM + Get-Process | Export-Excel .\test.xlsx -WorksheetName Processes -IncludePivotTable -Show -PivotRows Company -PivotData PM .EXAMPLE - Get-Process | Export-Excel .\test.xlsx -WorkSheetname Processes -ChartType PieExploded3D -IncludePivotChart -IncludePivotTable -Show -PivotRows Company -PivotData PM + Get-Process | Export-Excel .\test.xlsx -WorksheetName Processes -ChartType PieExploded3D -IncludePivotChart -IncludePivotTable -Show -PivotRows Company -PivotData PM .EXAMPLE Get-Service | Export-Excel 'c:\temp\test.xlsx' -Show -IncludePivotTable -PivotRows status -PivotData @{status='count'} @@ -316,7 +318,7 @@ } Remove-Item -Path .\test.xlsx Get-Service | Select-Object -Property Status,Name,DisplayName,StartType | Export-Excel -Path .\test.xlsx -AutoSize - Get-Process | Select-Object -Property Name,Company,Handles,CPU,VM | Export-Excel -Path .\test.xlsx -AutoSize -WorkSheetname 'sheet2' + Get-Process | Select-Object -Property Name,Company,Handles,CPU,VM | Export-Excel -Path .\test.xlsx -AutoSize -WorksheetName 'sheet2' Export-Excel -Path .\test.xlsx -PivotTableDefinition $pt -Show This example defines two pivot tables. Then it puts Service data on Sheet1 with one call to Export-Excel and Process Data on sheet2 with a second call to Export-Excel. @@ -339,7 +341,7 @@ .EXAMPLE Remove-Item -Path .\test.xlsx -ErrorAction Ignore - $excel = Get-Process | Select-Object -Property Name,Company,Handles,CPU,PM,NPM,WS | Export-Excel -Path .\test.xlsx -ClearSheet -WorkSheetname "Processes" -PassThru + $excel = Get-Process | Select-Object -Property Name,Company,Handles,CPU,PM,NPM,WS | Export-Excel -Path .\test.xlsx -ClearSheet -WorksheetName "Processes" -PassThru $sheet = $excel.Workbook.Worksheets["Processes"] $sheet.Column(1) | Set-Format -Bold -AutoFit $sheet.Column(2) | Set-Format -Width 29 -WrapText @@ -350,7 +352,7 @@ Add-ConditionalFormatting -WorkSheet $sheet -Range "D2:D1048576" -DataBarColor Red Add-ConditionalFormatting -WorkSheet $sheet -Range "G2:G1048576" -RuleType GreaterThan -ConditionValue "104857600" -ForeGroundColor Red foreach ($c in 5..9) {Set-Format -Address $sheet.Column($c) -AutoFit } - Export-Excel -ExcelPackage $excel -WorkSheetname "Processes" -IncludePivotChart -ChartType ColumnClustered -NoLegend -PivotRows company -PivotData @{'Name'='Count'} -Show + Export-Excel -ExcelPackage $excel -WorksheetName "Processes" -IncludePivotChart -ChartType ColumnClustered -NoLegend -PivotRows company -PivotData @{'Name'='Count'} -Show This a more sophisticated version of the previous example showing different ways of using Set-Format, and also adding conditional formatting. In the final command a Pivot chart is added and the workbook is opened in Excel. @@ -371,7 +373,7 @@ [Parameter(ValueFromPipeline = $true)] $TargetData, [Switch]$Show, - [String]$WorkSheetname = 'Sheet1', + [String]$WorksheetName = 'Sheet1', [String]$Password, [switch]$ClearSheet, [switch]$Append, @@ -445,6 +447,8 @@ [Object[]]$ConditionalFormat, [Object[]]$ConditionalText, [ScriptBlock]$CellStyleSB, + #If there is already content in the workbook the sheet with the Pivot table will not be active UNLESS Activate is specified + [switch]$Activate, [Parameter(ParameterSetName = 'Now')] [Switch]$Now, [Switch]$ReturnRange, @@ -553,11 +557,14 @@ } Else { $pkg = Open-ExcelPackage -Path $Path -Create -KillExcel:$KillExcel} - $params = @{WorkSheetname=$worksheetName} + $params = @{WorksheetName=$WorksheetName} if ($NoClobber) {Write-Warning -Message "-NoClobber parameter is no longer used" } - foreach ($p in @("ClearSheet", "MoveToStart", "MoveToEnd", "MoveBefore", "MoveAfter")) {if ($PSBoundParameters[$p]) {$params[$p] = $PSBoundParameters[$p]}} + foreach ($p in @("ClearSheet", "MoveToStart", "MoveToEnd", "MoveBefore", "MoveAfter", "Activate")) {if ($PSBoundParameters[$p]) {$params[$p] = $PSBoundParameters[$p]}} $ws = $pkg | Add-WorkSheet @params - + if ($ws.Name -ne $WorksheetName) { + Write-Warning -Message "The Worksheet name has been changed from $WorksheetName to $($ws.Name), this may cause errors later." + $WorksheetName = $ws.Name + } foreach ($format in $ConditionalFormat ) { switch ($format.formatter) { "ThreeIconSet" {Add-ConditionalFormatting -WorkSheet $ws -ThreeIconsSet $format.IconType -range $format.range -reverse:$format.reverse } @@ -598,7 +605,8 @@ } else { $Row = $StartRow } $ColumnIndex = $StartColumn - $setNumformat = ($numberformat -ne $ws.Cells.Style.Numberformat.Format) + $Numberformat = Expand-NumberFormat -NumberFormat $Numberformat + $setNumformat = ($Numberformat -ne $ws.Cells.Style.Numberformat.Format) $firstTimeThru = $true $isDataTypeValueType = $false @@ -606,10 +614,10 @@ Catch { if ($AlreadyExists) { #Is this set anywhere ? - throw "Failed exporting worksheet '$WorkSheetname' to '$Path': The worksheet '$WorkSheetname' already exists." + throw "Failed exporting worksheet '$WorksheetName' to '$Path': The worksheet '$WorksheetName' already exists." } else { - throw "Failed preparing to export to worksheet '$WorkSheetname' to '$Path': $_" + throw "Failed preparing to export to worksheet '$WorksheetName' to '$Path': $_" } } } @@ -668,7 +676,7 @@ } } Catch { - throw "Failed exporting data to worksheet '$WorkSheetname' to '$Path': $_" + throw "Failed exporting data to worksheet '$WorksheetName' to '$Path': $_" } } } @@ -719,7 +727,7 @@ } } } - Catch {Write-Warning -Message "Failed adding named ranges to worksheet '$WorkSheetname': $_" } + Catch {Write-Warning -Message "Failed adding named ranges to worksheet '$WorksheetName': $_" } } if ($RangeName) { @@ -732,7 +740,7 @@ if ($ws.Names[$RangeName]) { $ws.Names[$rangename].Address = $ws.Cells[$dataRange].FullAddressAbsolute } else {$ws.Names.Add($RangeName, $ws.Cells[$dataRange]) | Out-Null } } - Catch { Write-Warning -Message "Failed adding range '$RangeName' to worksheet '$WorkSheetname': $_" } + Catch { Write-Warning -Message "Failed adding range '$RangeName' to worksheet '$WorksheetName': $_" } } if ($TableName) { @@ -752,7 +760,7 @@ } Write-Verbose -Message "Defined table '$TableName' at $($targetRange.Address)" } - catch {Write-Warning -Message "Failed adding table '$TableName' to worksheet '$WorkSheetname': $_"} + catch {Write-Warning -Message "Failed adding table '$TableName' to worksheet '$WorksheetName': $_"} } if ($AutoFilter) { @@ -760,14 +768,15 @@ $ws.Cells[$dataRange].AutoFilter = $true Write-Verbose -Message "Enabeld autofilter. " } - catch {Write-Warning -Message "Failed adding autofilter to worksheet '$WorkSheetname': $_"} + catch {Write-Warning -Message "Failed adding autofilter to worksheet '$WorksheetName': $_"} } if ($PivotTableDefinition) { foreach ($item in $PivotTableDefinition.GetEnumerator()) { $params = $item.value + if ($Activate) {$params.Activate = $true } if ($params.keys -notcontains "SourceRange" -and - ($params.Keys -notcontains "SourceWorkSheet" -or $params.SourceWorkSheet -eq $WorkSheetname)) {$params.SourceRange = $dataRange} + ($params.Keys -notcontains "SourceWorkSheet" -or $params.SourceWorkSheet -eq $WorksheetName)) {$params.SourceRange = $dataRange} if ($params.Keys -notcontains "SourceWorkSheet") {$params.SourceWorkSheet = $ws } if ($params.Keys -notcontains "NoTotalsInPivot" -and $NoTotalsInPivot ) {$params.NoTotalsInPivot = $true} if ($params.Keys -notcontains "PivotDataToColumn" -and $PivotDataToColumn) {$params.PivotDataToColumn = $true} @@ -780,7 +789,8 @@ "SourceRange" = $dataRange } if ($PivotTableName) {$params.PivotTableName = $PivotTableName} - else {$params.PivotTableName = $WorkSheetname + 'PivotTable'} + else {$params.PivotTableName = $WorksheetName + 'PivotTable'} + if ($Activate) {$params.Activate = $true } if ($PivotFilter) {$params.PivotFilter = $PivotFilter} if ($PivotRows) {$params.PivotRows = $PivotRows} if ($PivotColumns) {$Params.PivotColumns = $PivotColumns} @@ -824,7 +834,7 @@ } } } - catch {Write-Warning -Message "Failed adding Freezing the panes in worksheet '$WorkSheetname': $_"} + catch {Write-Warning -Message "Failed adding Freezing the panes in worksheet '$WorksheetName': $_"} if ($BoldTopRow) { #it sets bold as far as there are populated cells: for whole row could do $ws.row($x).style.font.bold = $true try { @@ -837,14 +847,14 @@ $ws.Cells[$range].Style.Font.Bold = $true Write-Verbose -Message "Set $range font style to bold." } - catch {Write-Warning -Message "Failed setting the top row to bold in worksheet '$WorkSheetname': $_"} + catch {Write-Warning -Message "Failed setting the top row to bold in worksheet '$WorksheetName': $_"} } if ($AutoSize) { try { $ws.Cells.AutoFitColumns() Write-Verbose -Message "Auto-sized columns" } - catch { Write-Warning -Message "Failed autosizing columns of worksheet '$WorkSheetname': $_"} + catch { Write-Warning -Message "Failed autosizing columns of worksheet '$WorksheetName': $_"} } foreach ($Sheet in $HideSheet) { @@ -866,7 +876,7 @@ catch {Write-Warning -Message "Failed showing worksheet '$sheet': $_"} } if (-not $pkg.Workbook.Worksheets.Where({$_.Hidden -eq 'visible'})) { - Write-Verbose -Message "No Sheets were left visible, making $WorkSheetname visible" + Write-Verbose -Message "No Sheets were left visible, making $WorksheetName visible" $ws.Hidden = 'Visible' } @@ -911,7 +921,7 @@ Add-ConditionalFormatting -WorkSheet $ws @cfParams Write-Verbose -Message "Added conditional formatting to range $($ct.range)" } - catch {Write-Warning -Message "Failed adding conditional formatting to worksheet '$WorkSheetname': $_"} + catch {Write-Warning -Message "Failed adding conditional formatting to worksheet '$WorksheetName': $_"} } if ($CellStyleSB) { @@ -920,7 +930,7 @@ $LastColumn = $ws.Dimension.Address -replace "^.*:(\w*)\d+$" , '$1' & $CellStyleSB $ws $TotalRows $LastColumn } - catch {Write-Warning -Message "Failed processing CellStyleSB in worksheet '$WorkSheetname': $_"} + catch {Write-Warning -Message "Failed processing CellStyleSB in worksheet '$WorksheetName': $_"} } if ($Password) { @@ -929,7 +939,7 @@ Write-Verbose -Message "Set password on workbook" } - catch {throw "Failed setting password for worksheet '$WorkSheetname': $_"} + catch {throw "Failed setting password for worksheet '$WorksheetName': $_"} } if ($PassThru) { $pkg } @@ -977,7 +987,7 @@ function New-PivotTableDefinition { $pt = New-PivotTableDefinition -PivotTableName "PT1" -SourceWorkSheet "Sheet1" -PivotRows "Status" -PivotData @{Status='Count' } -PivotFilter 'StartType' -IncludePivotChart -ChartType BarClustered3D $Pt += New-PivotTableDefinition -PivotTableName "PT2" -SourceWorkSheet "Sheet2" -PivotRows "Company" -PivotData @{Company='Count'} -IncludePivotChart -ChartType PieExploded3D -ShowPercent -ChartTitle "Breakdown of processes by company" Get-Service | Select-Object -Property Status,Name,DisplayName,StartType | Export-Excel -Path .\test.xlsx -AutoSize - Get-Process | Select-Object -Property Name,Company,Handles,CPU,VM | Export-Excel -Path .\test.xlsx -AutoSize -WorkSheetname 'sheet2' + Get-Process | Select-Object -Property Name,Company,Handles,CPU,VM | Export-Excel -Path .\test.xlsx -AutoSize -WorksheetName 'sheet2' $excel = Export-Excel -Path .\test.xlsx -PivotTableDefinition $pt -Show This is a re-work of one of the examples in Export-Excel - instead of writing out the pivot definition hash table it is built by calling New-PivotTableDefinition. @@ -1024,7 +1034,9 @@ function New-PivotTableDefinition { #if specified attaches the category to slices in a pie chart : not supported on all chart types, this may give errors if applied to an unsupported type. [Switch]$ShowCategory, #If specified attaches percentages to slices in a pie chart. - [Switch]$ShowPercent + [Switch]$ShowPercent, + #If there is already content in the workbook the sheet with the Pivot table will not be active UNLESS Activate is specified + [switch]$Activate ) $validDataFuntions = [system.enum]::GetNames([OfficeOpenXml.Table.PivotTable.DataFieldFunctions]) @@ -1055,7 +1067,7 @@ function Add-WorkSheet { [Parameter(Mandatory = $true, ParameterSetName = "WorkBook")] [OfficeOpenXml.ExcelWorkbook]$ExcelWorkbook, #The name of the worksheet 'Sheet1' by default. - [string]$WorkSheetname , + [string]$WorksheetName , #If the worksheet already exists, by default it will returned, unless -ClearSheet is specified in which case it will be deleted and re-created. [switch]$ClearSheet, #If specified, the worksheet will be moved to the start of the workbook. @@ -1070,6 +1082,8 @@ function Add-WorkSheet { # If specified, the worksheet will be moved after the nominated one (which can be a postion starting from 1, or a name or *). # If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically. $MoveAfter , + #If there is already content in the workbook the new sheet will not be active UNLESS Activate is specified + [switch]$Activate, #If worksheet is provided as a copy source the new worksheet will be a copy of it. The source can be in the same workbook, or in a different file. [OfficeOpenXml.ExcelWorksheet]$CopySource, #Ignored but retained for backwards compatibility. @@ -1078,43 +1092,43 @@ function Add-WorkSheet { #if we were given a workbook use it, if we were given a package, use its workbook if ($ExcelPackage -and -not $ExcelWorkbook) {$ExcelWorkbook = $ExcelPackage.Workbook} - # If worksheetName was given, try to use that worksheet. If it wasn't, and we are copying an existing sheet, try to use the sheet name + # If WorksheetName was given, try to use that worksheet. If it wasn't, and we are copying an existing sheet, try to use the sheet name # if we are not copying a sheet or the name is in use, use the name "SheetX" where X is the number of the new sheet - if (-not $WorkSheetname -and $CopySource -and -not $ExcelWorkbook[$CopySource.Name]) {$WorkSheetname = $CopySource.Name} - elseif (-not $WorkSheetname) {$WorkSheetname = "Sheet" + (1 + $ExcelWorkbook.Worksheets.Count)} - else {$ws = $ExcelWorkbook.Worksheets[$WorkSheetname]} + if (-not $WorksheetName -and $CopySource -and -not $ExcelWorkbook[$CopySource.Name]) {$WorksheetName = $CopySource.Name} + elseif (-not $WorksheetName) {$WorksheetName = "Sheet" + (1 + $ExcelWorkbook.Worksheets.Count)} + else {$ws = $ExcelWorkbook.Worksheets[$WorksheetName]} #If -clearsheet was specified and the named sheet exists, delete it - if ($ws -and $ClearSheet) { $ExcelWorkbook.Worksheets.Delete($WorkSheetname) ; $ws = $null } + if ($ws -and $ClearSheet) { $ExcelWorkbook.Worksheets.Delete($WorksheetName) ; $ws = $null } #copy or create new sheet as needed if (-not $ws -and $CopySource) { - Write-Verbose -Message "Copying into worksheet '$WorkSheetname'." - $ws = $ExcelWorkbook.Worksheets.Add($WorkSheetname, $CopySource) + Write-Verbose -Message "Copying into worksheet '$WorksheetName'." + $ws = $ExcelWorkbook.Worksheets.Add($WorksheetName, $CopySource) } elseif (-not $ws) { - $ws = $ExcelWorkbook.Worksheets.Add($WorkSheetname) - Write-Verbose -Message "Adding worksheet '$WorkSheetname'." + $ws = $ExcelWorkbook.Worksheets.Add($WorksheetName) + Write-Verbose -Message "Adding worksheet '$WorksheetName'." } - else {Write-Verbose -Message "Worksheet '$WorkSheetname' already existed."} + else {Write-Verbose -Message "Worksheet '$WorksheetName' already existed."} #region Move sheet if needed - if ($MoveToStart) {$ExcelWorkbook.Worksheets.MoveToStart($worksheetName) } - elseif ($MoveToEnd ) {$ExcelWorkbook.Worksheets.MoveToEnd($worksheetName) } + if ($MoveToStart) {$ExcelWorkbook.Worksheets.MoveToStart($WorksheetName) } + elseif ($MoveToEnd ) {$ExcelWorkbook.Worksheets.MoveToEnd($WorksheetName) } elseif ($MoveBefore ) { if ($ExcelWorkbook.Worksheets[$MoveBefore]) { if ($MoveBefore -is [int]) { $ExcelWorkbook.Worksheets.MoveBefore($ws.Index, $MoveBefore) } - else {$ExcelWorkbook.Worksheets.MoveBefore($worksheetname, $MoveBefore)} + else {$ExcelWorkbook.Worksheets.MoveBefore($WorksheetName, $MoveBefore)} } - else {Write-Warning "Can't find worksheet '$MoveBefore'; worsheet '$WorkSheetname' will not be moved."} + else {Write-Warning "Can't find worksheet '$MoveBefore'; worsheet '$WorksheetName' will not be moved."} } elseif ($MoveAfter ) { if ($MoveAfter -eq "*") { - if ($WorkSheetname -lt $ExcelWorkbook.Worksheets[1].Name) {$ExcelWorkbook.Worksheets.MoveToStart($worksheetName)} + if ($WorksheetName -lt $ExcelWorkbook.Worksheets[1].Name) {$ExcelWorkbook.Worksheets.MoveToStart($WorksheetName)} else { $i = 1 - While ($i -lt $ExcelWorkbook.Worksheets.Count -and ($ExcelWorkbook.Worksheets[$i + 1].Name -le $worksheetname) ) { $i++} + While ($i -lt $ExcelWorkbook.Worksheets.Count -and ($ExcelWorkbook.Worksheets[$i + 1].Name -le $WorksheetName) ) { $i++} $ExcelWorkbook.Worksheets.MoveAfter($ws.Index, $i) } } @@ -1123,12 +1137,13 @@ function Add-WorkSheet { $ExcelWorkbook.Worksheets.MoveAfter($ws.Index, $MoveAfter) } else { - $ExcelWorkbook.Worksheets.MoveAfter($worksheetname, $MoveAfter) + $ExcelWorkbook.Worksheets.MoveAfter($WorksheetName, $MoveAfter) } } - else {Write-Warning "Can't find worksheet '$MoveAfter'; worsheet '$WorkSheetname' will not be moved."} + else {Write-Warning "Can't find worksheet '$MoveAfter'; worsheet '$WorksheetName' will not be moved."} } #endregion + if ($Activate) {Select-Worksheet -ExcelWorkbook $ExcelWorkbook -WorksheetName $ws.Name } return $ws } function Add-PivotTable { @@ -1182,12 +1197,13 @@ function Add-PivotTable { #if specified attaches the category to slices in a pie chart : not supported on all chart types, this may give errors if applied to an unsupported type. [Switch]$ShowCategory, #If specified attaches percentages to slices in a pie chart. - [Switch]$ShowPercent + [Switch]$ShowPercent, + #If there is already content in the workbook the sheet with the Pivot table will not be active UNLESS Activate is specified + [switch]$Activate ) $pivotTableDataName = $pivotTableName + 'PivotTableData' - [OfficeOpenXml.ExcelWorksheet]$wsPivot = Add-WorkSheet -ExcelPackage $ExcelPackage -WorkSheetname $pivotTableName - # $wsPivot.View.TabSelected = $true + [OfficeOpenXml.ExcelWorksheet]$wsPivot = Add-WorkSheet -ExcelPackage $ExcelPackage -WorksheetName $pivotTableName -Activate:$Activate #if the pivot doesn't exist, create it. if (-not $wsPivot.PivotTables[$pivotTableDataName] ) { @@ -1333,11 +1349,11 @@ function Add-ExcelChart { if ($XAxisTitleSize) {$chart.XAxis.Title.Font.Size = $XAxisTitleSize} } if ($XAxisPosition) {$chart.ChartXml.chartSpace.chart.plotArea.catAx.axPos.val = $XAxisPosition.ToString().substring(0,1)} - if ($XMajorUnit) {$chart.XAxis.MajorUnit = $XMajorUnit} + if ($XMajorUnit) {$chart.XAxis.MajorUnit = $XMajorUnit} if ($XMinorUnit) {$chart.XAxis.MinorUnit = $XMinorUnit} if ($null -ne $XMinValue) {$chart.XAxis.MinValue = $XMinValue} if ($null -ne $XMaxValue) {$chart.XAxis.MaxValue = $XMaxValue} - if ($XAxisNumberformat) {$chart.XAxis.Format = $XAxisNumberformat} + if ($XAxisNumberformat) {$chart.XAxis.Format = (Expand-NumberFormat $XAxisNumberformat)} if ($YAxisTitleText) { $chart.YAxis.Title.Text = $YAxisTitleText @@ -1349,7 +1365,7 @@ function Add-ExcelChart { if ($YMinorUnit) {$chart.YAxis.MinorUnit = $YMinorUnit} if ($null -ne $YMinValue){$chart.YAxis.MinValue = $YMinValue} if ($null -ne $YMaxValue){$chart.YAxis.MaxValue = $YMaxValue} - if ($YAxisNumberformat) {$chart.YAxis.Format = $YAxisNumberformat} + if ($YAxisNumberformat) {$chart.YAxis.Format = (Expand-NumberFormat $YAxisNumberformat)} if ($null -ne $chart.Datalabel) { $chart.Datalabel.ShowCategory = [boolean]$ShowCategory $chart.Datalabel.ShowPercent = [boolean]$ShowPercent @@ -1373,4 +1389,25 @@ function Add-ExcelChart { } } catch {Write-Warning -Message "Failed adding Chart to worksheet '$($WorkSheet).name': $_"} +} +function Select-Worksheet { + param ( + #An object representing an Excel Package. + [Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "Package", Position = 0)] + [OfficeOpenXml.ExcelPackage]$ExcelPackage, + #An Excel workbook to which the Worksheet will be added - a package contains one workbook so you can use whichever fits at the time. + [Parameter(Mandatory = $true, ParameterSetName = "WorkBook")] + [OfficeOpenXml.ExcelWorkbook]$ExcelWorkbook, + #The name of the worksheet 'Sheet1' by default. + [string]$WorksheetName + ) + #if we were given a workbook use it, if we were given a package, use its workbook + if ($ExcelPackage -and -not $ExcelWorkbook) {$ExcelWorkbook = $ExcelPackage.Workbook} + if (-not $ExcelWorkbook.Worksheets.Where({$_.name -eq $WorksheetName})) { + Write-Warning -Message "Workbook does not contain a worksheet named '$WorksheetName'" ; return + } + else { + foreach ($w in $ExcelWorkbook.Worksheets) {$w.View.TabSelected = $false} + $ExcelWorkbook.Worksheets[$WorksheetName].View.TabSelected = $true + } } \ No newline at end of file diff --git a/ImportExcel.psm1 b/ImportExcel.psm1 index c214007..44d2170 100644 --- a/ImportExcel.psm1 +++ b/ImportExcel.psm1 @@ -512,3 +512,20 @@ function Export-MultipleExcelSheets { if($Show) {Invoke-Item $Path} } + +Function WorksheetArgumentCompleter { + param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) + $xlPath = $fakeBoundParameter['Path'] + if (Test-Path -Path $xlPath) { + $xlpkg = Open-ExcelPackage -Path $xlPath + $WorksheetNames = $xlPkg.Workbook.Worksheets.Name + Close-ExcelPackage -nosave -ExcelPackage $xlpkg + $WorksheetNames.where({$_ -like "*$wordToComplete*"}) | foreach-object { + New-Object -TypeName System.Management.Automation.CompletionResult -ArgumentList "'$_'", + $_ , ([System.Management.Automation.CompletionResultType]::ParameterValue) ,$_ + } + } +} +If (Get-Command -ErrorAction SilentlyContinue -name Register-ArgumentCompleter) { + Register-ArgumentCompleter -CommandName 'Import-Excel' -ParameterName 'WorksheetName' -ScriptBlock $Function:WorksheetArgumentCompleter +} diff --git a/README.md b/README.md index 53fff78..2574dd7 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,13 @@ Install-Module ImportExcel -scope CurrentUser ```PowerShell Install-Module ImportExcel ``` +# What's new to Aug 2018 +- Set-Row and Set-Column will now create hyperlinks and insert dates correctly +- Import-Excel now has an argument completer for Worksheet name - this can be slow on large files +- The NumberFormat parameter (in Export-Excel, Set-Row, Set-Column, Set-Format and Add-ConditionalFormat) and X&YAxisNumberFormat paramaters (in New-ExcelChartDefinition and Add-ExcelChart) now have an argument completer and the names Currency, Number, Percentage, Scientific, Fraction, Short Date ,Short time,Long time, Date-Time and Text will be converted to the correct Excel formatting strings. +- Added new function Select-Worksheet to make a named sheet active: Added -Activate switch to Add-Worksheet, to make current sheet active, Export-Excel and Add-PivotTable support -Activate and pass it to Add-Worksheet, and New-PivotTableDefinition allows it to be part of the Pivot TableDefinition. +- Fixed a bug in Set-Format which caused -Hidden not to work +- Additional tests. # What's new to July 18 - Moved chart creation into its own function (Add-Excel chart) within Export-Excel.ps1. Renamed New-Excelchart to New-ExcelChartDefinition to make it clearer that it is not making anything in the workbook (but for compatibility put an alias of New-ExcelChart in so existing code does not break). Found that -Header does nothing, so it isn't Add-Excel chart and there is a message that does nothing in New-ExcelChartDefinition . diff --git a/Set-Column.ps1 b/Set-Column.ps1 index c7386b3..89fa93f 100644 --- a/Set-Column.ps1 +++ b/Set-Column.ps1 @@ -111,6 +111,18 @@ } else { $cellData = $Value} if ($cellData -match "^=") { $Worksheet.Cells[$Row, $Column].Formula = $cellData } + elseif ( [System.Uri]::IsWellFormedUriString($cellData , [System.UriKind]::Absolute)) { + # Save a hyperlink : internal links can be in the form xl://sheet!E419 (use A1 as goto sheet), or xl://RangeName + if ($cellData -match "^xl://internal/") { + $referenceAddress = $cellData -replace "^xl://internal/" , "" + $display = $referenceAddress -replace "!A1$" , "" + $h = New-Object -TypeName OfficeOpenXml.ExcelHyperLink -ArgumentList $referenceAddress , $display + $Worksheet.Cells[$Row, $Column].HyperLink = $h + } + else {$Worksheet.Cells[$Row, $Column].HyperLink = $cellData } + $Worksheet.Cells[$Row, $Column].Style.Font.Color.SetColor([System.Drawing.Color]::Blue) + $Worksheet.Cells[$Row, $Column].Style.Font.UnderLine = $true + } else { $Worksheet.Cells[$Row, $Column].Value = $cellData } if ($cellData -is [datetime]) { $Worksheet.Cells[$Row, $Column].Style.Numberformat.Format = 'm/d/yy h:mm' } # This is not a custom format, but a preset recognized as date and localized. }} diff --git a/Set-Row.ps1 b/Set-Row.ps1 index c96ce14..035548b 100644 --- a/Set-Row.ps1 +++ b/Set-Row.ps1 @@ -32,7 +32,7 @@ $Row = 0 , #Position in the row to start from [Int]$StartColumn, - #value, formula or script block for to fill in. Script block can use $row, $column [number], $ColumnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn + #value, formula or script block for to fill in. Script block can use $worksheet, $row, $column [number], $ColumnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn [parameter(Mandatory=$true)] $Value, #Optional Row heading @@ -110,6 +110,18 @@ } else{$cellData = $Value} if ($cellData -match "^=") { $Worksheet.Cells[$Row, $column].Formula = $cellData } + elseif ( [System.Uri]::IsWellFormedUriString($cellData , [System.UriKind]::Absolute)) { + # Save a hyperlink : internal links can be in the form xl://sheet!E419 (use A1 as goto sheet), or xl://RangeName + if ($cellData -match "^xl://internal/") { + $referenceAddress = $cellData -replace "^xl://internal/" , "" + $display = $referenceAddress -replace "!A1$" , "" + $h = New-Object -TypeName OfficeOpenXml.ExcelHyperLink -ArgumentList $referenceAddress , $display + $Worksheet.Cells[$Row, $Column].HyperLink = $h + } + else {$Worksheet.Cells[$Row, $Column].HyperLink = $cellData } + $Worksheet.Cells[$Row, $Column].Style.Font.Color.SetColor([System.Drawing.Color]::Blue) + $Worksheet.Cells[$Row, $Column].Style.Font.UnderLine = $true + } else { $Worksheet.Cells[$Row, $column].Value = $cellData } if ($cellData -is [datetime]) { $Worksheet.Cells[$Row, $column].Style.Numberformat.Format = 'm/d/yy h:mm' } # This is not a custom format, but a preset recognized as date and localized. }} diff --git a/SetFormat.ps1 b/SetFormat.ps1 index 5899f7b..5cbd839 100644 --- a/SetFormat.ps1 +++ b/SetFormat.ps1 @@ -120,9 +120,6 @@ if ($PSBoundParameters.ContainsKey('FontColor')){ $Address.Style.Font.Color.SetColor( $FontColor) } - if ($PSBoundParameters.ContainsKey('NumberFormat')) { - $Address.Style.Numberformat.Format = $NumberFormat - } if ($PSBoundParameters.ContainsKey('TextRotation')) { $Address.Style.TextRotation = $TextRotation } @@ -136,11 +133,21 @@ $Address.Style.VerticalAlignment = $VerticalAlignment } if ($PSBoundParameters.ContainsKey('Value')) { - $Address.Value = $Value + if ($Value -like '=*') {$Address.Formula = $Value} + else { + $Address.Value = $Value + if ($Value -is [DateTime]) { + $Address.Style.Numberformat.Format = 'm/d/yy h:mm' # This is not a custom format, but a preset recognized as date and localized. It might be overwritten in a moment + } + } } + if ($PSBoundParameters.ContainsKey('Formula')) { $Address.Formula = $Formula } + if ($PSBoundParameters.ContainsKey('NumberFormat')) { + $Address.Style.Numberformat.Format = (Expand-NumberFormat $NumberFormat) + } if ($PSBoundParameters.ContainsKey('BorderAround')) { $Address.Style.Border.BorderAround($BorderAround, $BorderColor) } @@ -194,7 +201,7 @@ } else {Write-Warning -Message ("Can set the width of a column or a range but not a {0} object" -f ($Address.GetType().name)) } } - if ($PSBoundParameters.ContainsKey('$Hidden')) { + if ($PSBoundParameters.ContainsKey('Hidden')) { if ($Address -is [OfficeOpenXml.ExcelRow] -or $Address -is [OfficeOpenXml.ExcelColumn] ) {$Address.Hidden = [boolean]$Hidden} else {Write-Warning -Message ("Can hide a row or a column but not a {0} object" -f ($Address.GetType().name)) } @@ -202,4 +209,73 @@ } } +} + +Function NumberFormatCompletion { + param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) + $numformats = [ordered]@{ + "General" = "General" # format ID 0 + "Number" = "0.00" # format ID 2 + "Percentage" = "0.00%" # format ID 10 + "Scientific" = "0.00E+00" # format ID 11 + "Fraction" = "# ?/?" # format ID 12 + "Short Date" = "Localized" # format ID 14 - will be translated to "mm-dd-yy" which is localized on load by Excel. + "Short Time" = "Localized" # format ID 20 - will be translated to "h:mm" which is localized on load by Excel. + "Long Time" = "Localized" # format ID 21 - will be translated to "h:mm:ss" which is localized on load by Excel. + "Date-Time" = "Localized" # format ID 22 - will be translated to "m/d/yy h:mm" which is localized on load by Excel. + "Currency" = [cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol + "#,##0.00" + "Text" = "@" # format ID 49 + "h:mm AM/PM" = "h:mm AM/PM" # format ID 18 + "h:mm:ss AM/PM" = "h:mm:ss AM/PM" # format ID 19 + "mm:ss" = "mm:ss" # format ID 45 + "[h]:mm:ss" = "Elapsed hours" # format ID 46 + "mm:ss.0" = "mm:ss.0" # format ID 47 + "d-mmm-yy" = "Localized" # format ID 15 which is localized on load by Excel. + "d-mmm" = "Localized" # format ID 16 which is localized on load by Excel. + "mmm-yy" = "mmm-yy" # format ID 17 which is localized on load by Excel. + "0" = "Whole number" # format ID 1 + "0.00" = "Number, 2 decimals" # format ID 2 or "number" + "#,##0" = "Thousand separators" # format ID 3 + "#,##0.00" = "Thousand separators and 2 decimals" # format ID 4 + "#," = "Whole thousands" + "#.0,," = "Millions, 1 Decimal" + "0%" = "Nearest whole percentage" # format ID 9 + "0.00%" = "Percentage with decimals" # format ID 10 or "Percentage" + "00E+00" = "Scientific" # format ID 11 or "Scientific" + "# ?/?" = "One Digit fraction" # format ID 12 or "Fraction" + "# ??/??" = "Two Digit fraction" # format ID 13 + "@" = "Text" # format ID 49 or "Text" + } + $numformats.keys.where({$_ -like "$wordToComplete*"} ) | ForEach-Object { + New-Object -TypeName System.Management.Automation.CompletionResult -ArgumentList "'$_'" , $_ , + ([System.Management.Automation.CompletionResultType]::ParameterValue) , $numformats[$_] + } +} +if (Get-Command -ErrorAction SilentlyContinue -name Register-ArgumentCompleter) { + Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName Export-Excel -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName Set-Format -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName Set-Column -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName Set-Row -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName New-ExcelChartDefinition -ParameterName XAxisNumberformat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName New-ExcelChartDefinition -ParameterName YAxisNumberformat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName Add-ExcelChart -ParameterName XAxisNumberformat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName Add-ExcelChart -ParameterName YAxisNumberformat -ScriptBlock $Function:NumberFormatCompletion +} + +Function Expand-NumberFormat { + param ($NumberFormat) + switch ($NumberFormat) { + "Currency" {return [cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol + "#,##0.00"} + "Number" {return "0.00" } # format id 2 + "Percentage" {return "0.00%" } # format id 10 + "Scientific" {return "0.00E+00" } # format id 11 + "Fraction" {return "# ?/?" } # format id 12 + "Short Date" {return "mm-dd-yy" } # format id 14 localized on load by Excel. + "Short Time" {return "h:mm" } # format id 20 localized on load by Excel. + "Long Time" {return "h:mm:ss" } # format id 21 localized on load by Excel. + "Date-Time" {return "m/d/yy h:mm"} # format id 22 localized on load by Excel. + "Text" {return "@" } # format ID 49 + Default {return $NumberFormat} + } } \ No newline at end of file diff --git a/ToDo.md b/ToDo.md index 338e45f..dc18a9a 100644 --- a/ToDo.md +++ b/ToDo.md @@ -1,11 +1,17 @@ -- [ ] Create an autocomplete for WorkSheetName param on ImportExcel and for number format ; where number format exists Translate "Date", "DateTime", "Currency" - +- [x] Create an autocomplete for WorkSheetName param on ImportExcel and for number format ; where number format exists Translate "Date", "DateTime", "Currency" +- [x] Support "make worksheet active" +- [X] Add checks for valid worksheet names +- [ ] Improve checking of worksheet, pivot names, range names and table names +- [ ] Investigate regional support for number conversion & possible date conversion. Also investigate feasablity of preserving number format when converting string to number - [ ] Add help text for parmaters which don't have it ( PivotDataToColumn , NoClobber and CellStyleSB ) in Export Excel, copy to Send-SQLDataToExcel -- [ ] Support "make worksheet active" -- [ ] Add checks for valid worksheet names (also check pivot names, range names and table names are valid) -- [ ] Investigate regional support for number conversion & possible date conversion - [ ] Add help in ConvertToExcelXLSx.ps1, Get-HTMLTable.ps1, GetRange.PS1, GetExcelTable.Ps1, Import-HTML.PS1, New-ConditionalFormattingIconSet.Ps1, NewConditionalText.PS1, New-Psitem.PS1, Remove-Worksheet.ps1 and Add-ExcelChart - Copy parameter help from function Add-ExcelChart into New-ExcelChart.ps1 -- [ ] Examples and tests for new "Quick charts" in Export Excel (replace examples) that use Charting.ps1, GetXYRange.ps1, InferData.PS1 (move these to deprecated). -- [ ] Test Add PivotTable selecting source sheet by position , UnhideSheet, and Wildcard support for hideSheet -- [ ] Test return range support to Set-Row and Set-Column and add examples to examples for set-Row and Set-column set-format, add-Conditional format (e.g. from tests) -- [ ] Increase code covereage for import-excel and Set-Format +- [ ] Add examples to add-ConditionalFormat, set-format,set-Row and Set-column (e.g. from tests) +- [ ] Add Examples and tests for new "Quick charts" in Export Excel (replace examples) that use Charting.ps1, GetXYRange.ps1, InferData.PS1 (move these to deprecated). +- [X] Test Add PivotTable selecting source sheet by position + -[X] Test UnhideSheet, and Wildcard support for hideSheet +- [X] Test return range support for Set-Row +- [X] Test return range support for Set-Column +- [X] Test Expand-NumberFormat. +- [X] Test Set-Row and Set-column setting values as dates and hyperlinks (only testing Column) +- [X] Increase Test code covereage for Set-Format +- [ ] Increase Test code covereage for import-excel \ No newline at end of file diff --git a/__tests__/Compare-WorkSheet.tests.ps1 b/__tests__/Compare-WorkSheet.tests.ps1 index bb82bda..21de628 100644 --- a/__tests__/Compare-WorkSheet.tests.ps1 +++ b/__tests__/Compare-WorkSheet.tests.ps1 @@ -235,7 +235,7 @@ Describe "Merge Worksheet" { } } Context "Wider data set" { - it "Copes with more columns beyond Z in the Output sheet " { + it "Coped with columns beyond Z in the Output sheet " { { Merge-Worksheet -Referencefile "$env:temp\server1.xlsx" -Differencefile "$env:temp\Server2.xlsx" -OutputFile "$env:temp\combined2.xlsx" } | Should not throw } } diff --git a/__tests__/Copy-ExcelWorksheet.Tests.ps1 b/__tests__/Copy-ExcelWorksheet.Tests.ps1 index c8d745d..9666660 100644 --- a/__tests__/Copy-ExcelWorksheet.Tests.ps1 +++ b/__tests__/Copy-ExcelWorksheet.Tests.ps1 @@ -37,7 +37,7 @@ Describe "Copy-Worksheet" { $excel = Open-ExcelPackage -Path $path2 $ws = $excel.Workbook.Worksheets["Processes"] } - it "inserted a worksheet " { + it "Inserted a worksheet " { $Excel.Workbook.Worksheets.count | Should be 2 $ws | Should not benullorEmpty $ws.Dimension.Address | should be $ProcRange @@ -50,7 +50,7 @@ Describe "Copy-Worksheet" { $excel = Open-ExcelPackage -Path $path2 $ws = $Excel.Workbook.Worksheets[3] } - it "inserted a worksheet with the expected name, number of rows and number of columns " { + it "Inserted a worksheet with 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" diff --git a/__tests__/Export-Excel.Tests.ps1 b/__tests__/Export-Excel.Tests.ps1 index ae8a98c..6d55436 100644 --- a/__tests__/Export-Excel.Tests.ps1 +++ b/__tests__/Export-Excel.Tests.ps1 @@ -50,7 +50,7 @@ Describe ExportExcel { } } - it "Formatted the process StartTime field as 'local short date' " { + 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 @@ -605,7 +605,7 @@ Describe ExportExcel { $rule = Add-ConditionalFormatting -passthru -Address $sheet.cells["C:C"] -RuleType TopPercent -ConditionValue 20 -Bold -StrikeThru Add-ConditionalFormatting -WorkSheet $sheet -Range "G2:G1048576" -RuleType GreaterThan -ConditionValue "104857600" -ForeGroundColor Red -Bold -Italic -Underline -BackgroundColor Beige -BackgroundPattern LightUp -PatternColor Gray foreach ($c in 5..9) {Set-Format $sheet.Column($c) -AutoFit } - Add-PivotTable -PivotTableName "PT_Procs" -ExcelPackage $excel -SourceWorkSheet "Processes" -PivotRows Company -PivotData @{'Name' = 'Count'} -IncludePivotChart -ChartType ColumnClustered -NoLegend + Add-PivotTable -PivotTableName "PT_Procs" -ExcelPackage $excel -SourceWorkSheet 1 -PivotRows Company -PivotData @{'Name' = 'Count'} -IncludePivotChart -ChartType ColumnClustered -NoLegend Close-ExcelPackage $excel $excel = Open-ExcelPackage $path diff --git a/__tests__/Join-Worksheet.tests.ps1 b/__tests__/Join-Worksheet.tests.ps1 index 8e8ce0b..89d2296 100644 --- a/__tests__/Join-Worksheet.tests.ps1 +++ b/__tests__/Join-Worksheet.tests.ps1 @@ -31,39 +31,58 @@ Describe "Join Worksheet" { $data3 | Export-Excel -Path $path -WorkSheetname Banbury $ptdef = New-PivotTableDefinition -PivotTableName "Summary" -PivotRows "Store" -PivotColumns "Product" -PivotData @{"Total"="SUM"} -IncludePivotChart -ChartTitle "Sales Breakdown" -ChartType ColumnStacked -ChartColumn 10 Join-Worksheet -Path $path -WorkSheetName "Total" -Clearsheet -FromLabel "Store" -TableName "Summary" -TableStyle Light1 -AutoSize -BoldTopRow -FreezePane 2,1 -Title "Store Sales Summary" -TitleBold -TitleSize 14 -PivotTableDefinition $ptdef - $excel = Open-ExcelPackage -Path $path + + $excel = Export-Excel -path $path -WorkSheetname Summary -Activate -HideSheet * -UnHideSheet "Total","Summary" -PassThru + # Open-ExcelPackage -Path $path + $ws = $excel.Workbook.Worksheets["Total"] $pt = $excel.Workbook.Worksheets["Summary"].pivottables[0] $pc = $excel.Workbook.Worksheets["Summary"].Drawings[0] } - Context "Merge 3 blocks" { + Context "Export-Excel setting spreadsheet visibility" { + it "Hid the worksheets " { + $excel.Workbook.Worksheets["Oxford"].Hidden | Should be $true + $excel.Workbook.Worksheets["Banbury"].Hidden | Should be $true + $excel.Workbook.Worksheets["Abingdon"].Hidden | Should be $true + } + it "Un-hid two of the worksheets " { + $excel.Workbook.Worksheets["Total"].Hidden | Should be $false + $excel.Workbook.Worksheets["Summary"].Hidden | Should be $false + } + it "Activated the correct worksheet " { + $excel.Workbook.worksheets["Summary"].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.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.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" } } $path = "$env:TEMP\Test.xlsx" @@ -78,26 +97,25 @@ Describe "Join Worksheet" { Join-Worksheet -Path $path -HideSource -WorkSheetName Summary -NoHeader -LabelBlocks -AutoSize -Title "Summary" -TitleBold -TitleSize 22 $excel = Open-ExcelPackage -Path $path $ws = $excel.Workbook.Worksheets["Summary"] - Context "3 Unlinked blocks" { + 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__/Set-Row_Set-Column-SetFormat.tests.ps1 b/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 index 692733e..acaf67e 100644 --- a/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 +++ b/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 @@ -1,6 +1,5 @@ - + $path = "$Env:TEMP\test.xlsx" -Remove-Item -Path $path -ErrorAction SilentlyContinue $data = ConvertFrom-Csv -InputObject @" ID,Product,Quantity,Price @@ -11,15 +10,136 @@ ID,Product,Quantity,Price 12011,Crowbar,7,23.48 "@ +$DriverData = convertFrom-CSv @" +Name,Wikipage,DateOfBirth +Fernando Alonso,/wiki/Fernando_Alonso,1981-07-29 +Jenson Button,/wiki/Jenson_Button,1980-01-19 +Kimi Räikkönen,/wiki/Kimi_R%C3%A4ikk%C3%B6nen,1979-10-17 +Lewis Hamilton,/wiki/Lewis_Hamilton,1985-01-07 +Nico Rosberg,/wiki/Nico_Rosberg,1985-06-27 +Sebastian Vettel,/wiki/Sebastian_Vettel,1987-07-03 +"@ | ForEach-Object {$_.DateOfBirth = [datetime]$_.DateofBirth; $_ } + + +Describe "Number format expansion and setting" { + Context "Argmument Completer for NumberFormat" { + it "Returned at least 20 items " { + (NumberFormatCompletion ).count | Should beGreaterThan 20 + } + It "Resolved percent to 'percentage' " { + $x = (NumberFormatCompletion -wordToComplete Percent) + $x.count | Should be 1 + $x.CompletionText | Should match "^'.*'$" + $x.ToolTip | Should be "0.00%" + $x.ListItemText | Should be "Percentage" + } + } + Context "Expand-NumberFormat function" { + It "Expanded named number formats as expected " { + Expand-NumberFormat 'Number' | Should be "0.00" + Expand-NumberFormat 'Percentage' | Should be "0.00%" + Expand-NumberFormat 'Scientific' | Should be "0.00E+00" + Expand-NumberFormat 'Currency' | Should be ([cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol + "#,##0.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" { + BeforeAll { + Remove-Item -Path $path -ErrorAction SilentlyContinue + $n = [datetime]::Now.ToOADate() + + $excel = 1..32 | ForEach-Object {$n} | Export-Excel -Path $path -PassThru + $ws = $excel.Workbook.Worksheets[1] + Set-Format -WorkSheet $ws -Range "A1" -numberFormat 'General' + Set-Format -WorkSheet $ws -Range "A2" -numberFormat 'Number' + Set-Format -WorkSheet $ws -Range "A3" -numberFormat 'Percentage' + Set-Format -WorkSheet $ws -Range "A4" -numberFormat 'Scientific' + Set-Format -WorkSheet $ws -Range "A5" -numberFormat 'Fraction' + Set-Format -WorkSheet $ws -Range "A6" -numberFormat 'Short Date' + Set-Format -WorkSheet $ws -Range "A7" -numberFormat 'Short Time' + Set-Format -WorkSheet $ws -Range "A8" -numberFormat 'Long Time' + Set-Format -WorkSheet $ws -Range "A9" -numberFormat 'Date-Time' + Set-Format -WorkSheet $ws -Range "A10" -numberFormat 'Currency' + Set-Format -WorkSheet $ws -Range "A11" -numberFormat 'Text' + Set-Format -WorkSheet $ws -Range "A12" -numberFormat 'h:mm AM/PM' + Set-Format -WorkSheet $ws -Range "A13" -numberFormat 'h:mm:ss AM/PM' + Set-Format -WorkSheet $ws -Range "A14" -numberFormat 'mm:ss' + Set-Format -WorkSheet $ws -Range "A15" -numberFormat '[h]:mm:ss' + Set-Format -WorkSheet $ws -Range "A16" -numberFormat 'mmss.0' + Set-Format -WorkSheet $ws -Range "A17" -numberFormat 'd-mmm-yy' + Set-Format -WorkSheet $ws -Range "A18" -numberFormat 'd-mmm' + Set-Format -WorkSheet $ws -Range "A19" -numberFormat 'mmm-yy' + Set-Format -WorkSheet $ws -Range "A20" -numberFormat '0' + Set-Format -WorkSheet $ws -Range "A21" -numberFormat '0.00' + Set-Format -Address $ws.Cells[ "A22"] -NumberFormat '#,##0' + Set-Format -Address $ws.Cells[ "A23"] -NumberFormat '#,##0.00' + Set-Format -Address $ws.Cells[ "A24"] -NumberFormat '#,' + Set-Format -Address $ws.Cells[ "A25"] -NumberFormat '#.0,,' + Set-Format -Address $ws.Cells[ "A26"] -NumberFormat '0%' + Set-Format -Address $ws.Cells[ "A27"] -NumberFormat '0.00%' + Set-Format -Address $ws.Cells[ "A28"] -NumberFormat '0.00E+00' + Set-Format -Address $ws.Cells[ "A29"] -NumberFormat '# ?/?' + Set-Format -Address $ws.Cells[ "A30"] -NumberFormat '# ??/??' + Set-Format -Address $ws.Cells[ "A31"] -NumberFormat '@' + + Close-ExcelPackage -ExcelPackage $excel + + $excel = Open-ExcelPackage -Path $path + $ws = $excel.Workbook.Worksheets[1] + } + + It "Set formats which translate to the correct format ID " { + $ws.Cells[10,1].Style.Numberformat.format | # Set as "Currency" + Should match ("^" + ([regex]::Escape([cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol))) + $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 + } + } +} + Describe "Set-Column, Set-Row and Set Format" { BeforeAll { + Remove-Item -Path $path -ErrorAction SilentlyContinue $excel = $data| Export-Excel -Path $path -AutoNameRange -PassThru $ws = $excel.Workbook.Worksheets["Sheet1"] $c = Set-Column -PassThru -Worksheet $ws -Heading "Total" -Value "=Quantity*Price" -NumberFormat "£#,###.00" -FontColor Blue -Bold -HorizontalAlignment Right -VerticalAlignment Top $r = Set-Row -PassThru -Worksheet $ws -StartColumn 3 -BorderAround Thin -Italic -Underline -FontSize 14 -Value {"=sum($columnName`2:$columnName$endrow)" } -VerticalAlignment Bottom Set-Format -Address $excel.Workbook.Worksheets["Sheet1"].cells["b3"] -HorizontalAlignment Right -VerticalAlignment Center -BorderAround Thick -BorderColor Red -StrikeThru - Set-Format -Address $excel.Workbook.Worksheets["Sheet1"].cells["c3"] -BorderColor Red -BorderTop DashDot -BorderLeft DashDotDot -BorderBottom Dashed -BorderRight Dotted + Set-Format -Address $excel.Workbook.Worksheets["Sheet1"].cells["c3"] -BorderColor Red -BorderTop DashDot -BorderLeft DashDotDot -BorderBottom Dashed -BorderRight Dotted Set-Format -WorkSheet $ws -Range "E3" -Bold:$false -FontShift Superscript -HorizontalAlignment Left Set-Format -WorkSheet $ws -Range "E1" -ResetFont -HorizontalAlignment General Set-Format -Address $ws.cells["E7"] -ResetFont -WrapText -BackgroundColor AliceBlue -BackgroundPattern DarkTrellis -PatternColor Red -NumberFormat "£#,###.00" @@ -27,59 +147,119 @@ Describe "Set-Column, Set-Row and Set Format" { Set-Format -Address $ws.Column(2) -AutoFit Set-Format -Address $ws.Cells["E:E"] -AutoFit Set-Format -Address $ws.row(5) -Height 0 + $rr = $r.row + Set-Format -WorkSheet $ws -Range "B$rr" -Value "Total" + $BadHideWarnvar = $null + Set-Format -WorkSheet $ws -Range "D$rr" -Formula "=E$rr/C$rr" -Hidden -WarningVariable "BadHideWarnvar" -WarningAction SilentlyContinue + $rr ++ + Set-Format -WorkSheet $ws -Range "B$rr" -Value ([datetime]::Now) Close-ExcelPackage $excel + $excel = Open-ExcelPackage $path $ws = $excel.Workbook.Worksheets["Sheet1"] } - Context "Rows and Columns" { - 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 + Context "Set-Row and Set-Column" { + 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 } - it "Set a column formula, with numberformat, color, bold face and alignment" { - $ws.cells["e2"].Formula | Should be "=Quantity*Price" - $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" + it "Set a column formula, with numberformat, color, bold face and alignment " { + $ws.cells["e2"].Formula | Should be "=Quantity*Price" + $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 "Set 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"].style.Font.UnderLine | Should be $true - $ws.cells["C6"].style.Font.UnderLine | Should be $false + it "Trapped an attempt to hide a range instead of a Row/Column " { + $BadHideWarnvar | Should not beNullOrEmpty } + it "Set 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"].style.Font.UnderLine | Should be $true + $ws.cells["C6"].style.Font.UnderLine | Should be $false + } + it "Set custom text wrapping, alignment, superscript, border and Fill " { + $ws.cells["e3"].Style.HorizontalAlignment | Should be "Left" + $ws.cells["e3"].Style.Font.VerticalAlign | Should be "Superscript" + $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["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" + } + } - it "Set custom text wrapping, alignment, superscript, border and Fill " { - $ws.cells["e3"].Style.HorizontalAlignment | Should be "Left" - $ws.cells["e3"].Style.Font.VerticalAlign | Should be "Superscript" - $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["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-Format value setting " { + it "Inserted a formula " { + $ws.Cells["D7"].Formula | Should be "=E7/C7" + } + it "Inserted a value " { + $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 + } + } + + Context "Set-Column Value Setting" { + BeforeAll { + Remove-Item -Path $path -ErrorAction SilentlyContinue + + $excel = $DriverData | Export-Excel -PassThru -Path $path -AutoSize -AutoNameRange + $ws = $excel.Workbook.Worksheets[1] + + Set-Column -Worksheet $ws -Heading "Link" -AutoSize -Value {"https://en.wikipedia.org" + $worksheet.cells["B$Row"].value } + $c = Set-Column -PassThru -Worksheet $ws -Heading "NextBirthday" -Value { + $bmonth = $worksheet.cells["C$Row"].value.month ; $bDay = $worksheet.cells["C$Row"].value.day + $cMonth = [datetime]::Now.Month ; $cday = [datetime]::Now.day ; $cyear = [datetime]::Now.Year + if (($cmonth -gt $bmonth) -or (($cMonth -eq $bmonth) -and ($cday -ge $bDay))){ + [datetime]::new($cyear+1, $bmonth, $bDay) + } + else {[datetime]::new($cyear, $bmonth, $bday) } + } + Set-Column -Worksheet $ws -Heading "Age" -Value "=INT((NOW()-DateOfBirth)/365)" + Set-Format -Address $c,$ws.column(3) -NumberFormat 'Short Date' -AutoSize + + Close-ExcelPackage -ExcelPackage $excel + $excel = Open-ExcelPackage $path + $ws = $excel.Workbook.Worksheets["Sheet1"] + } + It "Inserted Hyperlinks " { + $ws.Cells["D2"].Hyperlink | Should not beNullorEmpty + $ws.Cells["D2"].Style.Font.UnderLine | Should be $true + + } + It "Inserted 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 + } + It "Inserted Formulas " { + $ws.Cells["F2"].Formula | Should not beNullorEmpty } } }