Compare commits

..

47 Commits

Author SHA1 Message Date
dfinke
343687c418 bump version 2018-08-18 06:29:08 -04:00
dfinke
d4d2b4a856 Spell check 2018-08-16 19:26:50 -04:00
Doug Finke
bed52d456d Merge pull request #416 from jhoneill/master
Fix for #415, auto extend ranges/tables on append, password fixes, wildcards in Exclude property
2018-08-16 13:23:30 -04:00
jhoneill
31e6eaf59b Clean-up of Set-Row/Column (value no long mandatory); support array formulas in set-format 2018-08-16 17:33:44 +01:00
jhoneill
d770646dc7 Fixed small bug with Append and simple data types 2018-08-15 23:44:00 +01:00
jhoneill
bc65699068 Improved behavior of -NumberFormat in Export-Excel 2018-08-15 22:52:22 +01:00
jhoneill
ce3fd2021f Fix currency parsing Test when "." isn't a seperator in local culture 2018-08-14 17:32:34 +01:00
jhoneill
10f670b4e6 Added timespan support to export Excel 2018-08-14 16:35:19 +01:00
jhoneill
c49b7b6db0 Epplus is not setting chart axis position properly, so disabled for now 2018-08-14 15:40:52 +01:00
jhoneill
f768634214 Refined fix for #419 2018-08-14 12:54:17 +01:00
jhoneill
07342235b9 Fixed bug exporting nested objects; removed = in cond fmt expressions 2018-08-14 10:53:50 +01:00
jhoneill
2793ff1c21 Added -Calculate, fixed formula creation to be EPPlus-friendly 2018-08-13 20:58:10 +01:00
jhoneill
121346f939 Merge branch 'master' of https://github.com/jhoneill/ImportExcel 2018-08-12 15:07:16 +01:00
jhoneill
dc8a096732 Reduced number of proccess in tests to be appveyor freindly 2018-08-12 15:03:33 +01:00
jhoneill
c63512e658 Further fix to DLL screw up 2018-08-12 14:37:09 +01:00
jhoneill
e46fe6d3e9 Updated tests (and resulting refinements) 2018-08-12 14:01:56 +01:00
jhoneill
6ae50c3193 Mistakenly committed renamed epplus.dll 2018-08-12 11:41:46 +01:00
jhoneill
ee2378150c Merge remote-tracking branch 'upstream/master' 2018-08-10 10:23:03 +01:00
jhoneill
259c7e8ae6 Export-Excel -append now automatically extends ranges & tables 2018-08-10 09:29:17 +01:00
dfinke
ae30bfe6c3 don't test ps core 2018-08-08 19:44:09 -04:00
dfinke
3756cd6ad8 set scope 2018-08-08 19:40:33 -04:00
dfinke
1014250e0b try it in PS Core 6 and on Linux 2018-08-08 19:32:15 -04:00
jhoneill
951364da51 Now supports more than 26 columns. 2018-08-08 15:48:53 +01:00
jhoneill
c1604fc08a Exclude Property in Export-Excel now supports wildcards 2018-08-07 16:16:45 +01:00
jhoneill
5a235e309e Tider errors for file open on import; password tests 2018-08-07 15:00:33 +01:00
jhoneill
af77580b5e Password support fixes 2018-08-06 14:30:10 +01:00
jhoneill
b06a5059c5 Updated test for better currency string 2018-08-06 14:21:35 +01:00
jhoneill
edab941c44 Bug fix Export list of dates and Title background color 2018-08-06 11:13:27 +01:00
jhoneill
91fb314bca Expand Number format now sets regional layout for currency 2018-08-06 11:12:41 +01:00
dfinke
d07affcd46 updated 2018-08-02 17:10:54 -04:00
Doug Finke
2b3228d041 Merge pull request #411 from jhoneill/master
Fixed Parameter issues in Add-ConditionalFormat & test for it
2018-08-02 17:07:35 -04:00
jhoneill
34c5177dfc readme fix 2018-08-02 14:01:16 +01:00
jhoneill
f52ba1c50a Merge remote-tracking branch 'upstream/master' 2018-08-02 13:56:21 +01:00
jhoneill
b50cc67bb3 warn instead of aborting when a property won't go into a cell. 2018-08-02 13:56:01 +01:00
jhoneill
42e2b11a88 Merge branch 'master' of https://github.com/jhoneill/ImportExcel 2018-08-02 13:49:58 +01:00
jhoneill
b6509d3f5c Generate warning instead of aborting when a property can't be inserted into a cell. 2018-08-02 13:49:35 +01:00
jhoneill
29503861fb Generate warning instead of aborting when a property can't be inserted into a cell. 2018-08-02 13:27:49 +01:00
jhoneill
196497e3a0 Applied fix for parameter issues already done for Set format to conditional format 2018-08-02 11:20:19 +01:00
dfinke
d9fe0a31c3 sorted file list 2018-08-01 11:22:30 -04:00
dfinke
26bf4b9a64 refactored the supporting file list that gets copied so it can be tested 2018-08-01 11:18:13 -04:00
dfinke
a0719b22f0 spell check 2018-08-01 10:49:02 -04:00
dfinke
42d56ac557 bump version 2018-08-01 10:48:53 -04:00
dfinke
9b9c1de8fd remove ps1 2018-08-01 10:48:45 -04:00
Doug Finke
e3fdbf9fcc Merge pull request #408 from jhoneill/master
Argument completers for Number format and Worksheetname, bug fix for hidden in set format & more
2018-08-01 10:32:26 -04:00
jhoneill
abb971be88 Argument completers, Fix hidden in Set format. More tests 2018-08-01 10:35:10 +01:00
jhoneill
77fb51da8d Argument completers for worksheet name & number format. Fixed bug with -hidden 2018-07-31 15:07:33 +01:00
Doug Finke
61c73461ca Update README.md 2018-07-29 20:36:44 -04:00
23 changed files with 1132 additions and 443 deletions

View File

@@ -26,3 +26,6 @@ EPPLus
intellisense intellisense
PivtoTableName PivtoTableName
New-Excelchart New-Excelchart
paypal
dll
enums

View File

@@ -101,35 +101,48 @@
#If specified pass the rule back to the caller to allow additional customization. #If specified pass the rule back to the caller to allow additional customization.
[switch]$Passthru [switch]$Passthru
) )
#Allow conditional formatting to work like Set-Format (with single ADDRESS parameter), split it to get worksheet and range of cells. #Allow conditional formatting to work like Set-Format (with single ADDRESS parameter), split it to get worksheet and range of cells.
If ($Address -and -not $WorkSheet -and -not $Range) { If ($Address -and -not $WorkSheet -and -not $Range) {
$WorkSheet = $Address.Worksheet[0] $WorkSheet = $Address.Worksheet[0]
$Range = $Address.Address $Range = $Address.Address
} }
If ($ThreeIconsSet) {$rule = $WorkSheet.ConditionalFormatting.AddThreeIconSet($Range , $ThreeIconsSet)} #region Create a rule of the right type
elseif ($FourIconsSet) {$rule = $WorkSheet.ConditionalFormatting.AddFourIconSet( $Range , $FourIconsSet) } if ($PSBoundParameters.ContainsKey("ThreeIconsSet" ) ) {$rule = $WorkSheet.ConditionalFormatting.AddThreeIconSet($Range , $ThreeIconsSet)}
elseif ($FiveIconsSet) {$rule = $WorkSheet.ConditionalFormatting.AddFiveIconSet( $Range , $IconType) } elseif ($PSBoundParameters.ContainsKey("FourIconsSet" ) ) {$rule = $WorkSheet.ConditionalFormatting.AddFourIconSet( $Range , $FourIconsSet) }
elseif ($DataBarColor) {$rule = $WorkSheet.ConditionalFormatting.AddDatabar( $Range , $DataBarColor) } elseif ($PSBoundParameters.ContainsKey("FiveIconsSet" ) ) {$rule = $WorkSheet.ConditionalFormatting.AddFiveIconSet( $Range , $FiveIconsSet) }
else {$rule = ($WorkSheet.ConditionalFormatting)."Add$RuleType"($Range)} elseif ($PSBoundParameters.ContainsKey("DataBarColor" ) ) {$rule = $WorkSheet.ConditionalFormatting.AddDatabar( $Range , $DataBarColor) }
if ($reverse) {$rule.reverse = $true} else {$rule = ($WorkSheet.ConditionalFormatting)."Add$RuleType"($Range)}
if ($ConditionValue -and $RuleType -match "Top|Botom") {$rule.Rank = $ConditionValue } if ($PSBoundParameters.ContainsKey("Reverse" ) ) {$rule.reverse = [boolean]$Reverse}
if ($ConditionValue -and $RuleType -match "StdDev") {$rule.StdDev = $ConditionValue } #endregion
if ($ConditionValue -and $RuleType -match "Than|Equal|Expression") {$rule.Formula = $ConditionValue } #region set the rule conditions
if ($ConditionValue -and $RuleType -match "Text|With") {$rule.Text = $ConditionValue } if ($PSBoundParameters.ContainsKey("ConditionValue") -and
if ($ConditionValue -and $RuleType -match "Top|Botom" ) {$rule.Rank = $ConditionValue }
$ConditionValue2 -and $RuleType -match "Between") { if ($PSBoundParameters.ContainsKey("ConditionValue") -and
$rule.Formula = $ConditionValue $RuleType -match "StdDev" ) {$rule.StdDev = $ConditionValue }
$rule.Formula2 = $ConditionValue2 if ($PSBoundParameters.ContainsKey("ConditionValue") -and
$RuleType -match "Than|Equal|Expression" ) {$rule.Formula = ($ConditionValue -replace '^=','') }
if ($PSBoundParameters.ContainsKey("ConditionValue") -and
$RuleType -match "Text|With" ) {$rule.Text = ($ConditionValue -replace '^=','') }
if ($PSBoundParameters.ContainsKey("ConditionValue") -and
$PSBoundParameters.ContainsKey("ConditionValue") -and
$RuleType -match "Between" ) {
$rule.Formula = ($ConditionValue -replace '^=','');
$rule.Formula2 = ($ConditionValue2 -replace '^=','')
} }
#endregion
if ($NumberFormat) {$rule.Style.NumberFormat.Format = $NumberFormat } #region set the rule format
if ($Underline) {$rule.Style.Font.Underline = [OfficeOpenXml.Style.ExcelUnderLineType]::Single } if ($PSBoundParameters.ContainsKey("NumberFormat" ) ) {$rule.Style.NumberFormat.Format = (Expand-NumberFormat $NumberFormat) }
if ($Bold) {$rule.Style.Font.Bold = $true } if ($Underline ) {$rule.Style.Font.Underline = [OfficeOpenXml.Style.ExcelUnderLineType]::Single }
if ($Italic) {$rule.Style.Font.Italic = $true } elseif ($PSBoundParameters.ContainsKey("Underline" ) ) {$rule.Style.Font.Underline = [OfficeOpenXml.Style.ExcelUnderLineType]::None }
if ($StrikeThru) {$rule.Style.Font.Strike = $true } if ($PSBoundParameters.ContainsKey("Bold" ) ) {$rule.Style.Font.Bold = [boolean]$Bold }
if ($ForeGroundColor) {$rule.Style.Font.Color.color = $ForeGroundColor } if ($PSBoundParameters.ContainsKey("Italic" ) ) {$rule.Style.Font.Italic = [boolean]$Italic }
if ($BackgroundColor) {$rule.Style.Fill.BackgroundColor.color = $BackgroundColor } if ($PSBoundParameters.ContainsKey("StrikeThru") ) {$rule.Style.Font.Strike = [boolean]$StrikeThru }
if ($BackgroundPattern) {$rule.Style.Fill.PatternType = $BackgroundPattern } if ($PSBoundParameters.ContainsKey("ForeGroundColor" ) ) {$rule.Style.Font.Color.color = $ForeGroundColor }
if ($PatternColor) {$rule.Style.Fill.PatternColor.color = $PatternColor } if ($PSBoundParameters.ContainsKey("BackgroundColor" ) ) {$rule.Style.Fill.BackgroundColor.color = $BackgroundColor }
if ($Passthru) {$rule} if ($PSBoundParameters.ContainsKey("BackgroundPattern") ) {$rule.Style.Fill.PatternType = $BackgroundPattern }
if ($PSBoundParameters.ContainsKey("PatternColor" ) ) {$rule.Style.Fill.PatternColor.color = $PatternColor }
#endregion
#Allow further tweaking by returning the rule, if passthru specified
if ($Passthru) {$rule}
} }

View File

@@ -8,7 +8,7 @@ $dest = "ImportExcel-{0}-{1}.zip" -f $ModuleVersion, (Get-Date).ToString("yyyyMM
Compress-Archive -Path . -DestinationPath .\$dest Compress-Archive -Path . -DestinationPath .\$dest
if ((Get-Module -ListAvailable pester) -eq $null) { if ((Get-Module -ListAvailable pester) -eq $null) {
Install-Module -Name Pester -Repository PSGallery -Force Install-Module -Name Pester -Repository PSGallery -Force -Scope CurrentUser
} }
$result = Invoke-Pester -Script $PSScriptRoot\__tests__ -Verbose -PassThru $result = Invoke-Pester -Script $PSScriptRoot\__tests__ -Verbose -PassThru

View File

@@ -8,7 +8,7 @@
Path to a new or existing .XLSX file. Path to a new or existing .XLSX file.
.PARAMETER ExcelPackage .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. 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. The name of a sheet within the workbook - "Sheet1" by default.
.PARAMETER ClearSheet .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). 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).
@@ -22,6 +22,8 @@
Some objects duplicate existing properties by adding aliases, or have Script properties which take a long time to return a value and slow the export down, if specified this removes these properties Some objects duplicate existing properties by adding aliases, or have Script properties which take a long time to return a value and slow the export down, if specified this removes these properties
.PARAMETER ExcludeProperty .PARAMETER ExcludeProperty
Specifies properties which may exist in the target data but should not be placed on the worksheet. Specifies properties which may exist in the target data but should not be placed on the worksheet.
.PARAMETER Calculate
If specified a recalculation of the worksheet will be requested before saving.
.PARAMETER Title .PARAMETER Title
Text of a title to be placed in the top left cell. Text of a title to be placed in the top left cell.
.PARAMETER TitleBold .PARAMETER TitleBold
@@ -123,6 +125,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. 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 .PARAMETER AutoSize
Sizes the width of the Excel column to the maximum width needed to display all the containing data in that cell. 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 .PARAMETER Now
The 'Now' switch is a shortcut that creates automatically a temporary file, enables 'AutoSize', 'AutoFiler' and 'Show', and opens the file immediately. The 'Now' switch is a shortcut that creates automatically a temporary file, enables 'AutoSize', 'AutoFiler' and 'Show', and opens the file immediately.
.PARAMETER NumberFormat .PARAMETER NumberFormat
@@ -287,15 +291,15 @@
$Array = $Obj1, $Obj2, $Obj3 $Array = $Obj1, $Obj2, $Obj3
$Array | Out-GridView -Title 'Not showing Member3 and Member4' $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. 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 .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 .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 .EXAMPLE
Get-Service | Export-Excel 'c:\temp\test.xlsx' -Show -IncludePivotTable -PivotRows status -PivotData @{status='count'} Get-Service | Export-Excel 'c:\temp\test.xlsx' -Show -IncludePivotTable -PivotRows status -PivotData @{status='count'}
@@ -316,7 +320,7 @@
} }
Remove-Item -Path .\test.xlsx Remove-Item -Path .\test.xlsx
Get-Service | Select-Object -Property Status,Name,DisplayName,StartType | Export-Excel -Path .\test.xlsx -AutoSize 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 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. 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 +343,7 @@
.EXAMPLE .EXAMPLE
Remove-Item -Path .\test.xlsx -ErrorAction Ignore 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 = $excel.Workbook.Worksheets["Processes"]
$sheet.Column(1) | Set-Format -Bold -AutoFit $sheet.Column(1) | Set-Format -Bold -AutoFit
$sheet.Column(2) | Set-Format -Width 29 -WrapText $sheet.Column(2) | Set-Format -Width 29 -WrapText
@@ -350,7 +354,7 @@
Add-ConditionalFormatting -WorkSheet $sheet -Range "D2:D1048576" -DataBarColor Red Add-ConditionalFormatting -WorkSheet $sheet -Range "D2:D1048576" -DataBarColor Red
Add-ConditionalFormatting -WorkSheet $sheet -Range "G2:G1048576" -RuleType GreaterThan -ConditionValue "104857600" -ForeGroundColor 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 } 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. 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. In the final command a Pivot chart is added and the workbook is opened in Excel.
@@ -370,13 +374,14 @@
[OfficeOpenXml.ExcelPackage]$ExcelPackage, [OfficeOpenXml.ExcelPackage]$ExcelPackage,
[Parameter(ValueFromPipeline = $true)] [Parameter(ValueFromPipeline = $true)]
$TargetData, $TargetData,
[Switch]$Calculate,
[Switch]$Show, [Switch]$Show,
[String]$WorkSheetname = 'Sheet1', [String]$WorksheetName = 'Sheet1',
[String]$Password, [String]$Password,
[switch]$ClearSheet, [switch]$ClearSheet,
[switch]$Append, [switch]$Append,
[String]$Title, [String]$Title,
[OfficeOpenXml.Style.ExcelFillStyle]$TitleFillPattern = 'None', [OfficeOpenXml.Style.ExcelFillStyle]$TitleFillPattern = 'Solid',
[Switch]$TitleBold, [Switch]$TitleBold,
[Int]$TitleSize = 22, [Int]$TitleSize = 22,
[System.Drawing.Color]$TitleBackgroundColor, [System.Drawing.Color]$TitleBackgroundColor,
@@ -445,14 +450,21 @@
[Object[]]$ConditionalFormat, [Object[]]$ConditionalFormat,
[Object[]]$ConditionalText, [Object[]]$ConditionalText,
[ScriptBlock]$CellStyleSB, [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')] [Parameter(ParameterSetName = 'Now')]
[Switch]$Now, [Switch]$Now,
[Switch]$ReturnRange, [Switch]$ReturnRange,
#By default Pivot tables have Totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected.
[ValidateSet("Both","Columns","Rows","None")]
[String]$PivotTotals = "Both",
#Included for compatibility - equivalent to -PivotTotals "None"
[Switch]$NoTotalsInPivot, [Switch]$NoTotalsInPivot,
[Switch]$ReZip [Switch]$ReZip
) )
Begin { Begin {
$numberRegex = [Regex]'\d'
function Add-CellValue { function Add-CellValue {
<# <#
.SYNOPSIS .SYNOPSIS
@@ -474,13 +486,19 @@
#The write-verbose commands have been commented out below - even if verbose is silenced they cause a significiant performance impact and if it's on they will cause a flood of messages. #The write-verbose commands have been commented out below - even if verbose is silenced they cause a significiant performance impact and if it's on they will cause a flood of messages.
Switch ($CellValue) { Switch ($CellValue) {
{ $_ -is [DateTime]} { { $_ -is [DateTime]} {
# Save a date with an international valid format # Save a date with one of Excel's built in formats format
$TargetCell.Value = $_ $TargetCell.Value = $_
$TargetCell.Style.Numberformat.Format = 'm/d/yy h:mm' # This is not a custom format, but a preset recognized as date and localized. $TargetCell.Style.Numberformat.Format = 'm/d/yy h:mm' # This is not a custom format, but a preset recognized as date and localized.
#Write-Verbose "Cell '$Row`:$ColumnIndex' header '$Name' add value '$_' as date" #Write-Verbose "Cell '$Row`:$ColumnIndex' header '$Name' add value '$_' as date"
break break
} }
{ $_ -is [TimeSpan]} {
#Save a timespans with a built in format for elapsed hours, minutes and seconds
$TargetCell.Value = $_
$TargetCell.Style.Numberformat.Format = '[h]:mm:ss'
break
}
{ $_ -is [System.ValueType]} { { $_ -is [System.ValueType]} {
# Save numerics, setting format if need be. # Save numerics, setting format if need be.
$TargetCell.Value = $_ $TargetCell.Value = $_
@@ -489,8 +507,8 @@
break break
} }
{($_ -is [String]) -and ($_[0] -eq '=')} { {($_ -is [String]) -and ($_[0] -eq '=')} {
#region Save an Excel formula #region Save an Excel formula - we need = to spot the formula but the EPPLUS won't like it if we include it (Excel doesn't care if is there or not)
$TargetCell.Formula = $_ $TargetCell.Formula = ($_ -replace '^=','')
if ($setNumformat) {$targetCell.Style.Numberformat.Format = $Numberformat } if ($setNumformat) {$targetCell.Style.Numberformat.Format = $Numberformat }
#Write-Verbose "Cell '$Row`:$ColumnIndex' header '$Name' add value '$_' as formula" #Write-Verbose "Cell '$Row`:$ColumnIndex' header '$Name' add value '$_' as formula"
break break
@@ -519,7 +537,7 @@
Default { Default {
#Save a value as a number if possible #Save a value as a number if possible
$number = $null $number = $null
if ([Double]::TryParse($_, [System.Globalization.NumberStyles]::Any, [System.Globalization.NumberFormatInfo]::CurrentInfo, [Ref]$number)) { if ($numberRegex.IsMatch($_) -and [Double]::TryParse($_, [System.Globalization.NumberStyles]::Any, [System.Globalization.NumberFormatInfo]::CurrentInfo, [Ref]$number)) {
# as simpler version using [Double]::TryParse( $_ , [ref]$number)) was found to cause problems reverted back to the longer version # as simpler version using [Double]::TryParse( $_ , [ref]$number)) was found to cause problems reverted back to the longer version
$TargetCell.Value = $number $TargetCell.Value = $number
if ($setNumformat) {$targetCell.Style.Numberformat.Format = $Numberformat } if ($setNumformat) {$targetCell.Style.Numberformat.Format = $Numberformat }
@@ -551,13 +569,21 @@
$pkg = $ExcelPackage $pkg = $ExcelPackage
$Path = $pkg.File $Path = $pkg.File
} }
Else { $pkg = Open-ExcelPackage -Path $Path -Create -KillExcel:$KillExcel} Else { $pkg = Open-ExcelPackage -Path $Path -Create -KillExcel:$KillExcel -Password:$Password}
}
$params = @{WorkSheetname=$worksheetName} Catch {throw "Could not open Excel Package $path"}
if ($NoClobber) {Write-Warning -Message "-NoClobber parameter is no longer used" } 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]}} Try {
$params = @{WorksheetName=$WorksheetName}
foreach ($p in @("ClearSheet", "MoveToStart", "MoveToEnd", "MoveBefore", "MoveAfter", "Activate")) {if ($PSBoundParameters[$p]) {$params[$p] = $PSBoundParameters[$p]}}
$ws = $pkg | Add-WorkSheet @params $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
}
}
Catch {throw "Could not get worksheet $worksheetname"}
try {
foreach ($format in $ConditionalFormat ) { foreach ($format in $ConditionalFormat ) {
switch ($format.formatter) { switch ($format.formatter) {
"ThreeIconSet" {Add-ConditionalFormatting -WorkSheet $ws -ThreeIconsSet $format.IconType -range $format.range -reverse:$format.reverse } "ThreeIconSet" {Add-ConditionalFormatting -WorkSheet $ws -ThreeIconsSet $format.IconType -range $format.range -reverse:$format.reverse }
@@ -565,12 +591,42 @@
"FiveIconSet" {Add-ConditionalFormatting -WorkSheet $ws -FiveIconsSet $format.IconType -range $format.range -reverse:$format.reverse } "FiveIconSet" {Add-ConditionalFormatting -WorkSheet $ws -FiveIconsSet $format.IconType -range $format.range -reverse:$format.reverse }
} }
} }
}
catch {throw "Error applying confitional formatting to worksheet"}
try {
if ($Append -and $ws.Dimension) { if ($Append -and $ws.Dimension) {
#if there is a title or anything else above the header row, append needs to be combined wih a suitable startrow parameter #if there is a title or anything else above the header row, append needs to be combined wih a suitable startrow parameter
$headerRange = $ws.Dimension.Address -replace "\d+$", $StartRow $headerRange = $ws.Dimension.Address -replace "\d+$", $StartRow
#using a slightly odd syntax otherwise header ends up as a 2D array #using a slightly odd syntax otherwise header ends up as a 2D array
$ws.Cells[$headerRange].Value | ForEach-Object -Begin {$Script:header = @()} -Process {$Script:header += $_ } $ws.Cells[$headerRange].Value | ForEach-Object -Begin {$Script:header = @()} -Process {$Script:header += $_ }
#if we did not get AutoNameRange, but headers have ranges of the same name make autoNameRange True, otherwise make it false
if (-not $AutoNameRange) {
$AutoNameRange = $true ; foreach ($h in $header) {if ($ws.names.name -notcontains $h) {$AutoNameRange = $false} }
}
#if we did not get a Rangename but there is a Range which covers the active part of the sheet, set Rangename to that.
if (-not $RangeName -and $ws.names.where({$_.name[0] -match '[a-z]'})) {
$theRange = $ws.names.where({
($_.Name[0] -match '[a-z]' ) -and
($_.Start.Row -eq $StartRow) -and
($_.Start.Column -eq $StartColumn) -and
($_.End.Row -eq $ws.Dimension.End.Row) -and
($_.End.Column -eq $ws.Dimension.End.column) } , 'First', 1)
if ($theRange) {$rangename = $theRange.name}
}
#if we did not get a table name but there is a table which covers the active part of the sheet, set table name to that, and don't do anything with autofilter
if (-not $TableName -and $ws.Tables.Where({$_.address.address -eq $ws.dimension.address})) {
$TableName = $ws.Tables.Where({$_.address.address -eq $ws.dimension.address},'First', 1).Name
$AutoFilter = $false
}
#if we did not get $autofilter but a filter range is set and it covers the right area, set autofilter to true
elseif (-not $AutoFilter -and $ws.Names["_xlnm._FilterDatabase"]) {
if ( ($ws.Names["_xlnm._FilterDatabase"].Start.Row -eq $StartRow) -and
($ws.Names["_xlnm._FilterDatabase"].Start.Column -eq $StartColumn) -and
($ws.Names["_xlnm._FilterDatabase"].End.Row -eq $ws.Dimension.End.Row) -and
($ws.Names["_xlnm._FilterDatabase"].End.Column -eq $ws.Dimension.End.Column) ) {$AutoFilter = $true}
}
$row = $ws.Dimension.End.Row $row = $ws.Dimension.End.Row
Write-Debug -Message ("Appending: headers are " + ($script:Header -join ", ") + " Start row is $row") Write-Debug -Message ("Appending: headers are " + ($script:Header -join ", ") + " Start row is $row")
} }
@@ -585,33 +641,33 @@
#Otherwise the default will be unbolded. #Otherwise the default will be unbolded.
$ws.Cells[$Row, $StartColumn].Style.Font.Bold = $True $ws.Cells[$Row, $StartColumn].Style.Font.Bold = $True
} }
#Can only set TitleBackgroundColor if TitleFillPattern is something other than None.
if ($TitleBackgroundColor -and ($TitleFillPattern -ne 'None')) {
$TitleFillPattern = [OfficeOpenXml.Style.ExcelFillStyle]::Solid
}
$ws.Cells[$Row, $StartColumn].Style.Fill.PatternType = $TitleFillPattern
if ($TitleBackgroundColor ) { if ($TitleBackgroundColor ) {
$ws.Cells[$Row, $StartColumn].Style.Fill.PatternType = $TitleFillPattern
$ws.Cells[$Row, $StartColumn].Style.Fill.BackgroundColor.SetColor($TitleBackgroundColor) $ws.Cells[$Row, $StartColumn].Style.Fill.BackgroundColor.SetColor($TitleBackgroundColor)
} }
$Row ++ ; $startRow ++ $Row ++ ; $startRow ++
} }
else { $Row = $StartRow } else { $Row = $StartRow }
$ColumnIndex = $StartColumn $ColumnIndex = $StartColumn
$setNumformat = ($numberformat -ne $ws.Cells.Style.Numberformat.Format) $Numberformat = Expand-NumberFormat -NumberFormat $Numberformat
if ($row -le 2 -and $ColumnIndex -eq 1 -and $Numberformat -ne $ws.Cells.Style.Numberformat.Format) {
$ws.Cells.Style.Numberformat.Format = $Numberformat
$setNumformat = $false
}
else { $setNumformat = ($Numberformat -ne $ws.Cells.Style.Numberformat.Format) }
$firstTimeThru = $true $firstTimeThru = $true
$isDataTypeValueType = $false $isDataTypeValueType = $false
} }
Catch { Catch {
if ($AlreadyExists) { if ($AlreadyExists) {
#Is this set anywhere ? #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 { else {
throw "Failed preparing to export to worksheet '$WorkSheetname' to '$Path': $_" throw "Failed preparing to export to worksheet '$WorksheetName' to '$Path': $_"
} }
} }
} }
Process { Process {
@@ -619,18 +675,19 @@
Try { Try {
if ($firstTimeThru) { if ($firstTimeThru) {
$firstTimeThru = $false $firstTimeThru = $false
$isDataTypeValueType = $TargetData.GetType().name -match 'string|bool|byte|char|decimal|double|float|int|long|sbyte|short|uint|ulong|ushort' $isDataTypeValueType = $TargetData.GetType().name -match 'string|timespan|datetime|bool|byte|char|decimal|double|float|int|long|sbyte|short|uint|ulong|ushort'
if ($isDataTypeValueType) {$row -= 1} #row incremented before adding values, so it is set to the number of rows inserted at the end if ($isDataTypeValueType -and -not $Append) {$row -= 1} #row incremented before adding values, so it is set to the number of rows inserted at the end
Write-Debug "DataTypeName is '$($TargetData.GetType().name)' isDataTypeValueType '$isDataTypeValueType'" Write-Debug "DataTypeName is '$($TargetData.GetType().name)' isDataTypeValueType '$isDataTypeValueType'"
} }
if ($isDataTypeValueType) { if ($isDataTypeValueType) {
$ColumnIndex = $StartColumn $ColumnIndex = $StartColumn
$Row += 1 $Row += 1
Add-CellValue -TargetCell $ws.Cells[$Row, $ColumnIndex] -CellValue $TargetData try {Add-CellValue -TargetCell $ws.Cells[$Row, $ColumnIndex] -CellValue $TargetData}
catch {Write-Warning "Could not insert value at Row $Row. "}
} }
else { else {
#region Add headers #region Add headers - if we are appending, or we have been through here once already we will have the headers
if (-not $script:Header) { if (-not $script:Header) {
$ColumnIndex = $StartColumn $ColumnIndex = $StartColumn
if ($DisplayPropertySet -and $TargetData.psStandardmembers.DefaultDisplayPropertySet.ReferencedPropertyNames) { if ($DisplayPropertySet -and $TargetData.psStandardmembers.DefaultDisplayPropertySet.ReferencedPropertyNames) {
@@ -638,8 +695,9 @@
} }
else { else {
if ($NoAliasOrScriptPropeties) {$propType = "Property"} else {$propType = "*"} if ($NoAliasOrScriptPropeties) {$propType = "Property"} else {$propType = "*"}
$script:Header = $TargetData.PSObject.Properties.where( {$_.MemberType -like $propType -and $_.Name -notin $ExcludeProperty}).Name $script:Header = $TargetData.PSObject.Properties.where( {$_.MemberType -like $propType}).Name
} }
foreach ($exclusion in $ExcludeProperty) {$script:Header = $script:Header -notlike $exclusion}
if ($NoHeader) { if ($NoHeader) {
# Don't push the headers to the spreadsheet # Don't push the headers to the spreadsheet
$Row -= 1 $Row -= 1
@@ -653,22 +711,21 @@
} }
} }
#endregion #endregion
#region Add non header values
$Row += 1 $Row += 1
$ColumnIndex = $StartColumn $ColumnIndex = $StartColumn
foreach ($Name in $script:Header) { foreach ($Name in $script:Header) {
#region Add non header values try {Add-CellValue -TargetCell $ws.Cells[$Row, $ColumnIndex] -CellValue $TargetData.$Name}
Add-CellValue -TargetCell $ws.Cells[$Row, $ColumnIndex] -CellValue $TargetData.$Name catch {Write-Warning -Message "Could not insert the $Name property at Row $Row, Column $Column"}
$ColumnIndex += 1 $ColumnIndex += 1
#endregion
} }
$ColumnIndex -= 1 # column index will be the last column whether isDataTypeValueType was true or false $ColumnIndex -= 1 # column index will be the last column whether isDataTypeValueType was true or false
#endregion
} }
} }
Catch { Catch {
throw "Failed exporting data to worksheet '$WorkSheetname' to '$Path': $_" throw "Failed exporting data to worksheet '$WorksheetName' to '$Path': $_"
} }
} }
} }
@@ -682,10 +739,10 @@
else { else {
$LastRow = $Row $LastRow = $Row
$LastCol = $ColumnIndex $LastCol = $ColumnIndex
$endAddress = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R[$LastRow]C[$LastCol]", 0, 0) $endAddress = [OfficeOpenXml.ExcelAddress]::GetAddress($LastRow , $LastCol)
} }
$startAddress = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R[$StartRow]C[$StartColumn]", 0, 0) $startAddress = [OfficeOpenXml.ExcelAddress]::GetAddress($StartRow, $StartColumn)
$dataRange = "{0}:{1}" -f $startAddress, $endAddress $dataRange = "{0}:{1}" -f $startAddress, $endAddress
Write-Debug "Data Range '$dataRange'" Write-Debug "Data Range '$dataRange'"
if ($AutoNameRange) { if ($AutoNameRange) {
@@ -719,7 +776,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) { if ($RangeName) {
@@ -732,7 +789,7 @@
if ($ws.Names[$RangeName]) { $ws.Names[$rangename].Address = $ws.Cells[$dataRange].FullAddressAbsolute } if ($ws.Names[$RangeName]) { $ws.Names[$rangename].Address = $ws.Cells[$dataRange].FullAddressAbsolute }
else {$ws.Names.Add($RangeName, $ws.Cells[$dataRange]) | Out-Null } 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) { if ($TableName) {
@@ -752,7 +809,7 @@
} }
Write-Verbose -Message "Defined table '$TableName' at $($targetRange.Address)" 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) { if ($AutoFilter) {
@@ -760,16 +817,18 @@
$ws.Cells[$dataRange].AutoFilter = $true $ws.Cells[$dataRange].AutoFilter = $true
Write-Verbose -Message "Enabeld autofilter. " 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) { if ($PivotTableDefinition) {
foreach ($item in $PivotTableDefinition.GetEnumerator()) { foreach ($item in $PivotTableDefinition.GetEnumerator()) {
$params = $item.value $params = $item.value
if ($Activate) {$params.Activate = $true }
if ($params.keys -notcontains "SourceRange" -and 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 "SourceWorkSheet") {$params.SourceWorkSheet = $ws }
if ($params.Keys -notcontains "NoTotalsInPivot" -and $NoTotalsInPivot ) {$params.NoTotalsInPivot = $true} if ($params.Keys -notcontains "NoTotalsInPivot" -and $NoTotalsInPivot ) {$params.PivotTotals = "None"}
if ($params.Keys -notcontains "PivotTotals" -and $PivotTotals ) {$params.PivotTotals = $PivotTotals}
if ($params.Keys -notcontains "PivotDataToColumn" -and $PivotDataToColumn) {$params.PivotDataToColumn = $true} if ($params.Keys -notcontains "PivotDataToColumn" -and $PivotDataToColumn) {$params.PivotDataToColumn = $true}
Add-PivotTable -ExcelPackage $pkg -PivotTableName $item.key @Params Add-PivotTable -ExcelPackage $pkg -PivotTableName $item.key @Params
@@ -779,13 +838,15 @@
$params = @{ $params = @{
"SourceRange" = $dataRange "SourceRange" = $dataRange
} }
if ($PivotTableName) {$params.PivotTableName = $PivotTableName} if ($PivotTableName) {$params.PivotTableName = $PivotTableName}
else {$params.PivotTableName = $WorkSheetname + 'PivotTable'} else {$params.PivotTableName = $WorksheetName + 'PivotTable'}
if ($PivotFilter) {$params.PivotFilter = $PivotFilter} if ($Activate) {$params.Activate = $true }
if ($PivotRows) {$params.PivotRows = $PivotRows} if ($PivotFilter) {$params.PivotFilter = $PivotFilter}
if ($PivotColumns) {$Params.PivotColumns = $PivotColumns} if ($PivotRows) {$params.PivotRows = $PivotRows}
if ($PivotData) {$Params.PivotData = $PivotData} if ($PivotColumns) {$Params.PivotColumns = $PivotColumns}
if ($NoTotalsInPivot) {$params.NoTotalsInPivot = $true} if ($PivotData) {$Params.PivotData = $PivotData}
if ($NoTotalsInPivot) {$params.PivotTotals = "None" }
Elseif ($PivotTotals) {$params.PivotTotals = $PivotTotals}
if ($PivotDataToColumn) {$params.PivotDataToColumn = $true} if ($PivotDataToColumn) {$params.PivotDataToColumn = $true}
if ($IncludePivotChart) { if ($IncludePivotChart) {
$params.IncludePivotChart = $true $params.IncludePivotChart = $true
@@ -824,7 +885,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 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 { try {
@@ -837,14 +898,14 @@
$ws.Cells[$range].Style.Font.Bold = $true $ws.Cells[$range].Style.Font.Bold = $true
Write-Verbose -Message "Set $range font style to bold." 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) { if ($AutoSize) {
try { try {
$ws.Cells.AutoFitColumns() $ws.Cells.AutoFitColumns()
Write-Verbose -Message "Auto-sized columns" 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) { foreach ($Sheet in $HideSheet) {
@@ -866,7 +927,7 @@
catch {Write-Warning -Message "Failed showing worksheet '$sheet': $_"} catch {Write-Warning -Message "Failed showing worksheet '$sheet': $_"}
} }
if (-not $pkg.Workbook.Worksheets.Where({$_.Hidden -eq 'visible'})) { 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' $ws.Hidden = 'Visible'
} }
@@ -879,13 +940,13 @@
if ($Barchart -or $PieChart -or $LineChart -or $ColumnChart) { if ($Barchart -or $PieChart -or $LineChart -or $ColumnChart) {
if ($NoHeader) {$FirstDataRow = $startRow} if ($NoHeader) {$FirstDataRow = $startRow}
else {$FirstDataRow = $startRow + 1 } else {$FirstDataRow = $startRow + 1 }
$range = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R[$FirstDataRow]C[$startColumn]:R[$FirstDataRow]C[$lastCol]",0,0) $range = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, $startColumn, $FirstDataRow, $lastCol )
$xCol = $ws.cells[$range] | Where-Object {$_.value -is [string] } | ForEach-Object {$_.start.column} | Sort-Object | Select-Object -first 1 $xCol = $ws.cells[$range] | Where-Object {$_.value -is [string] } | ForEach-Object {$_.start.column} | Sort-Object | Select-Object -first 1
$yCol = $ws.cells[$range] | Where-Object {$_.value -is [valueType] } | ForEach-Object {$_.start.column} | Sort-Object | Select-Object -first 1 $yCol = $ws.cells[$range] | Where-Object {$_.value -is [valueType] } | ForEach-Object {$_.start.column} | Sort-Object | Select-Object -first 1
$params = @{ $params = @{
xrange = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R[$FirstDataRow]C[$xcol]:R[$($lastrow)]C[$xcol]",0,0) ; XRange = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, $xcol , $lastrow, $xcol)
yrange = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R[$FirstDataRow]C[$ycol]:R[$($lastrow)]C[$ycol]",0,0) ; YRange = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, $ycol , $lastrow, $ycol)
title = ""; Title = "";
Column = ($lastCol +1) ; Column = ($lastCol +1) ;
Width = 800 Width = 800
} }
@@ -911,7 +972,7 @@
Add-ConditionalFormatting -WorkSheet $ws @cfParams Add-ConditionalFormatting -WorkSheet $ws @cfParams
Write-Verbose -Message "Added conditional formatting to range $($ct.range)" 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) { if ($CellStyleSB) {
@@ -920,7 +981,12 @@
$LastColumn = $ws.Dimension.Address -replace "^.*:(\w*)\d+$" , '$1' $LastColumn = $ws.Dimension.Address -replace "^.*:(\w*)\d+$" , '$1'
& $CellStyleSB $ws $TotalRows $LastColumn & $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 ($Calculate) {
try { [OfficeOpenXml.CalculationExtension]::Calculate($ws) }
Catch { Write-Warning "One or more errors occured while calculating, save will continue, but there may be errors in the workbook."}
} }
if ($Password) { if ($Password) {
@@ -929,14 +995,15 @@
Write-Verbose -Message "Set password on workbook" 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 } if ($PassThru) { $pkg }
else { else {
if ($ReturnRange) {$dataRange } if ($ReturnRange) {$dataRange }
$pkg.Save() if ($Password) { $pkg.Save($Password) }
else { $pkg.Save() }
Write-Verbose -Message "Saved workbook $($pkg.File)" Write-Verbose -Message "Saved workbook $($pkg.File)"
if ($ReZip) { if ($ReZip) {
Write-Verbose -Message "Re-Zipping $($pkg.file) using .NET ZIP library" Write-Verbose -Message "Re-Zipping $($pkg.file) using .NET ZIP library"
@@ -970,14 +1037,14 @@ function New-PivotTableDefinition {
Creates Pivot table definitons for Export-Excel Creates Pivot table definitons for Export-Excel
.Description .Description
Export-Excel allows a single Pivot table to be defined using the parameters -IncludePivotTable, -PivotColumns -PivotRows, Export-Excel allows a single Pivot table to be defined using the parameters -IncludePivotTable, -PivotColumns -PivotRows,
=PivotData, -PivotFilter, -NoTotalsInPivot, -PivotDataToColumn, -IncludePivotChart and -ChartType. =PivotData, -PivotFilter, -PivotTotals, -PivotDataToColumn, -IncludePivotChart and -ChartType.
Its -PivotTableDefintion paramater allows multiple pivot tables to be defined, with additional parameters. Its -PivotTableDefintion paramater allows multiple pivot tables to be defined, with additional parameters.
New-PivotTableDefinition is a convenient way to build these definitions. New-PivotTableDefinition is a convenient way to build these definitions.
.Example .Example
$pt = New-PivotTableDefinition -PivotTableName "PT1" -SourceWorkSheet "Sheet1" -PivotRows "Status" -PivotData @{Status='Count' } -PivotFilter 'StartType' -IncludePivotChart -ChartType BarClustered3D $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" $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-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 $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. 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.
@@ -1000,6 +1067,10 @@ function New-PivotTableDefinition {
#Fields to use to filter in the Pivot table #Fields to use to filter in the Pivot table
$PivotFilter, $PivotFilter,
[Switch]$PivotDataToColumn, [Switch]$PivotDataToColumn,
#By default Pivot tables have Totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected.
[ValidateSet("Both","Columns","Rows","None")]
[String]$PivotTotals = "Both",
#Included for compatibility - equivalent to -PivotTotals "None"
[Switch]$NoTotalsInPivot, [Switch]$NoTotalsInPivot,
#If specified a chart Will be included. #If specified a chart Will be included.
[Switch]$IncludePivotChart, [Switch]$IncludePivotChart,
@@ -1024,7 +1095,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. #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, [Switch]$ShowCategory,
#If specified attaches percentages to slices in a pie chart. #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]) $validDataFuntions = [system.enum]::GetNames([OfficeOpenXml.Table.PivotTable.DataFieldFunctions])
@@ -1033,6 +1106,10 @@ function New-PivotTableDefinition {
} }
$parameters = @{} + $PSBoundParameters $parameters = @{} + $PSBoundParameters
if ($NoTotalsInPivot) {
$parameters.Remove('NoTotalsInPivot')
$parameters["PivotTotals"] = "None"
}
$parameters.Remove('PivotTableName') $parameters.Remove('PivotTableName')
@{$PivotTableName = $parameters} @{$PivotTableName = $parameters}
@@ -1055,7 +1132,7 @@ function Add-WorkSheet {
[Parameter(Mandatory = $true, ParameterSetName = "WorkBook")] [Parameter(Mandatory = $true, ParameterSetName = "WorkBook")]
[OfficeOpenXml.ExcelWorkbook]$ExcelWorkbook, [OfficeOpenXml.ExcelWorkbook]$ExcelWorkbook,
#The name of the worksheet 'Sheet1' by default. #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. #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, [switch]$ClearSheet,
#If specified, the worksheet will be moved to the start of the workbook. #If specified, the worksheet will be moved to the start of the workbook.
@@ -1070,6 +1147,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 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. # 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 , $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. #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, [OfficeOpenXml.ExcelWorksheet]$CopySource,
#Ignored but retained for backwards compatibility. #Ignored but retained for backwards compatibility.
@@ -1078,43 +1157,43 @@ function Add-WorkSheet {
#if we were given a workbook use it, if we were given a package, use its workbook #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 ($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 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} if (-not $WorksheetName -and $CopySource -and -not $ExcelWorkbook[$CopySource.Name]) {$WorksheetName = $CopySource.Name}
elseif (-not $WorkSheetname) {$WorkSheetname = "Sheet" + (1 + $ExcelWorkbook.Worksheets.Count)} elseif (-not $WorksheetName) {$WorksheetName = "Sheet" + (1 + $ExcelWorkbook.Worksheets.Count)}
else {$ws = $ExcelWorkbook.Worksheets[$WorkSheetname]} else {$ws = $ExcelWorkbook.Worksheets[$WorksheetName]}
#If -clearsheet was specified and the named sheet exists, delete it #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 #copy or create new sheet as needed
if (-not $ws -and $CopySource) { if (-not $ws -and $CopySource) {
Write-Verbose -Message "Copying into worksheet '$WorkSheetname'." Write-Verbose -Message "Copying into worksheet '$WorksheetName'."
$ws = $ExcelWorkbook.Worksheets.Add($WorkSheetname, $CopySource) $ws = $ExcelWorkbook.Worksheets.Add($WorksheetName, $CopySource)
} }
elseif (-not $ws) { elseif (-not $ws) {
$ws = $ExcelWorkbook.Worksheets.Add($WorkSheetname) $ws = $ExcelWorkbook.Worksheets.Add($WorksheetName)
Write-Verbose -Message "Adding worksheet '$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 #region Move sheet if needed
if ($MoveToStart) {$ExcelWorkbook.Worksheets.MoveToStart($worksheetName) } if ($MoveToStart) {$ExcelWorkbook.Worksheets.MoveToStart($WorksheetName) }
elseif ($MoveToEnd ) {$ExcelWorkbook.Worksheets.MoveToEnd($worksheetName) } elseif ($MoveToEnd ) {$ExcelWorkbook.Worksheets.MoveToEnd($WorksheetName) }
elseif ($MoveBefore ) { elseif ($MoveBefore ) {
if ($ExcelWorkbook.Worksheets[$MoveBefore]) { if ($ExcelWorkbook.Worksheets[$MoveBefore]) {
if ($MoveBefore -is [int]) { if ($MoveBefore -is [int]) {
$ExcelWorkbook.Worksheets.MoveBefore($ws.Index, $MoveBefore) $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 ) { elseif ($MoveAfter ) {
if ($MoveAfter -eq "*") { 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 { else {
$i = 1 $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) $ExcelWorkbook.Worksheets.MoveAfter($ws.Index, $i)
} }
} }
@@ -1123,12 +1202,13 @@ function Add-WorkSheet {
$ExcelWorkbook.Worksheets.MoveAfter($ws.Index, $MoveAfter) $ExcelWorkbook.Worksheets.MoveAfter($ws.Index, $MoveAfter)
} }
else { 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 #endregion
if ($Activate) {Select-Worksheet -ExcelWorkbook $ExcelWorkbook -WorksheetName $ws.Name }
return $ws return $ws
} }
function Add-PivotTable { function Add-PivotTable {
@@ -1158,6 +1238,10 @@ function Add-PivotTable {
#Fields to use to filter in the Pivot table #Fields to use to filter in the Pivot table
$PivotFilter, $PivotFilter,
[Switch]$PivotDataToColumn, [Switch]$PivotDataToColumn,
#By default Pivot tables have Totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected.
[ValidateSet("Both","Columns","Rows","None")]
[String]$PivotTotals = "Both",
#Included for compatibility - equivalent to -PivotTotals "None"
[Switch]$NoTotalsInPivot, [Switch]$NoTotalsInPivot,
#If specified a chart Will be included. #If specified a chart Will be included.
[Switch]$IncludePivotChart, [Switch]$IncludePivotChart,
@@ -1182,24 +1266,25 @@ 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. #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, [Switch]$ShowCategory,
#If specified attaches percentages to slices in a pie chart. #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' $pivotTableDataName = $pivotTableName + 'PivotTableData'
[OfficeOpenXml.ExcelWorksheet]$wsPivot = Add-WorkSheet -ExcelPackage $ExcelPackage -WorkSheetname $pivotTableName [OfficeOpenXml.ExcelWorksheet]$wsPivot = Add-WorkSheet -ExcelPackage $ExcelPackage -WorksheetName $pivotTableName -Activate:$Activate
# $wsPivot.View.TabSelected = $true
#if the pivot doesn't exist, create it. #if the pivot doesn't exist, create it.
if (-not $wsPivot.PivotTables[$pivotTableDataName] ) { if (-not $wsPivot.PivotTables[$pivotTableDataName] ) {
try { try {
#Accept a string or a worksheet object as $Source Worksheet. #Accept a string or a worksheet object as $Source Worksheet.
if ($SourceWorkSheet -is [string]) { if ($SourceWorkSheet -is [string]) {
$SourceWorkSheet = $ExcelPackage.Workbook.Worksheets.where( {$_.name -match $SourceWorkSheet})[0] $SourceWorkSheet = $ExcelPackage.Workbook.Worksheets.where( {$_.name -Like $SourceWorkSheet})[0]
} }
elseif ($SourceWorkSheet -is [int]) { elseif ($SourceWorkSheet -is [int]) {
$SourceWorkSheet = $ExcelPackage.Workbook.Worksheets[$SourceWorkSheet] $SourceWorkSheet = $ExcelPackage.Workbook.Worksheets[$SourceWorkSheet]
} }
if (-not ($SourceWorkSheet -is [OfficeOpenXml.ExcelWorksheet])) {Write-Warning -Message "Could not find source Worksheet for pivot-table '$pivotTableName'." } if ($SourceWorkSheet -isnot [OfficeOpenXml.ExcelWorksheet]) {Write-Warning -Message "Could not find source Worksheet for pivot-table '$pivotTableName'." ; return }
else { else {
if ($PivotFilter) {$PivotTableStartCell = "A3"} else { $PivotTableStartCell = "A1"} if ($PivotFilter) {$PivotTableStartCell = "A3"} else { $PivotTableStartCell = "A1"}
if (-not $SourceRange) { $SourceRange = $SourceWorkSheet.Dimension.Address} if (-not $SourceRange) { $SourceRange = $SourceWorkSheet.Dimension.Address}
@@ -1235,8 +1320,12 @@ function Add-PivotTable {
try { $null = $pivotTable.PageFields.Add($pivotTable.Fields[$pFilter])} try { $null = $pivotTable.PageFields.Add($pivotTable.Fields[$pFilter])}
catch {Write-Warning -message "Could not add '$pFilter' to Filter/Page fields in PivotTable $pivotTableName." } catch {Write-Warning -message "Could not add '$pFilter' to Filter/Page fields in PivotTable $pivotTableName." }
} }
if ($NoTotalsInPivot) { $pivotTable.RowGrandTotals = $false } if ($NoTotalsInPivot) {$PivotTotals = "None" }
if ($PivotDataToColumn ) { $pivotTable.DataOnRows = $false } if ($PivotTotals -eq "None" -or $PivotTotals -eq "Columns") { $pivotTable.RowGrandTotals = $false }
elseif ($PivotTotals -eq "Both" -or $PivotTotals -eq "Rows") { $pivotTable.RowGrandTotals = $true }
if ($PivotTotals -eq "None" -or $PivotTotals -eq "Rows") { $pivotTable.ColumGrandTotals = $false } # Epplus spelling mistake, not mine!
elseif ($PivotTotals -eq "Both" -or $PivotTotals -eq "Columns") { $pivotTable.ColumGrandTotals = $true }
if ($PivotDataToColumn ) { $pivotTable.DataOnRows = $false }
} }
catch {Write-Warning -Message "Failed adding PivotTable '$pivotTableName': $_"} catch {Write-Warning -Message "Failed adding PivotTable '$pivotTableName': $_"}
} }
@@ -1332,24 +1421,26 @@ function Add-ExcelChart {
if ($XAxisTitleBold) {$chart.XAxis.Title.Font.Bold = $true} if ($XAxisTitleBold) {$chart.XAxis.Title.Font.Bold = $true}
if ($XAxisTitleSize) {$chart.XAxis.Title.Font.Size = $XAxisTitleSize} if ($XAxisTitleSize) {$chart.XAxis.Title.Font.Size = $XAxisTitleSize}
} }
if ($XAxisPosition) {$chart.ChartXml.chartSpace.chart.plotArea.catAx.axPos.val = $XAxisPosition.ToString().substring(0,1)} if ($XAxisPosition) {Write-Warning "X Axis position is not being set propertly at the moment, parameter ignored" }
if ($XMajorUnit) {$chart.XAxis.MajorUnit = $XMajorUnit} #$chart.ChartXml.chartSpace.chart.plotArea.catAx.axPos.val = $XAxisPosition.ToString().substring(0,1)}
if ($XMajorUnit) {$chart.XAxis.MajorUnit = $XMajorUnit}
if ($XMinorUnit) {$chart.XAxis.MinorUnit = $XMinorUnit} if ($XMinorUnit) {$chart.XAxis.MinorUnit = $XMinorUnit}
if ($null -ne $XMinValue) {$chart.XAxis.MinValue = $XMinValue} if ($null -ne $XMinValue) {$chart.XAxis.MinValue = $XMinValue}
if ($null -ne $XMaxValue) {$chart.XAxis.MaxValue = $XMaxValue} if ($null -ne $XMaxValue) {$chart.XAxis.MaxValue = $XMaxValue}
if ($XAxisNumberformat) {$chart.XAxis.Format = $XAxisNumberformat} if ($XAxisNumberformat) {$chart.XAxis.Format = (Expand-NumberFormat $XAxisNumberformat)}
if ($YAxisTitleText) { if ($YAxisTitleText) {
$chart.YAxis.Title.Text = $YAxisTitleText $chart.YAxis.Title.Text = $YAxisTitleText
if ($YAxisTitleBold) {$chart.YAxis.Title.Font.Bold = $true} if ($YAxisTitleBold) {$chart.YAxis.Title.Font.Bold = $true}
if ($YAxisTitleSize) {$chart.YAxis.Title.Font.Size = $YAxisTitleSize} if ($YAxisTitleSize) {$chart.YAxis.Title.Font.Size = $YAxisTitleSize}
} }
if ($YAxisPosition) {$chart.ChartXml.chartSpace.chart.plotArea.valAx.axPos.val= $YAxisPosition.ToString().substring(0,1)} if ($YAxisPosition) {Write-Warning "Y Axis position is not being set propertly at the moment, parameter ignored" }
#$chart.ChartXml.chartSpace.chart.plotArea.valAx.axPos.val= $YAxisPosition.ToString().substring(0,1)}
if ($YMajorUnit) {$chart.YAxis.MajorUnit = $YMajorUnit} if ($YMajorUnit) {$chart.YAxis.MajorUnit = $YMajorUnit}
if ($YMinorUnit) {$chart.YAxis.MinorUnit = $YMinorUnit} if ($YMinorUnit) {$chart.YAxis.MinorUnit = $YMinorUnit}
if ($null -ne $YMinValue){$chart.YAxis.MinValue = $YMinValue} if ($null -ne $YMinValue){$chart.YAxis.MinValue = $YMinValue}
if ($null -ne $YMaxValue){$chart.YAxis.MaxValue = $YMaxValue} 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) { if ($null -ne $chart.Datalabel) {
$chart.Datalabel.ShowCategory = [boolean]$ShowCategory $chart.Datalabel.ShowCategory = [boolean]$ShowCategory
$chart.Datalabel.ShowPercent = [boolean]$ShowPercent $chart.Datalabel.ShowPercent = [boolean]$ShowPercent
@@ -1374,3 +1465,24 @@ function Add-ExcelChart {
} }
catch {Write-Warning -Message "Failed adding Chart to worksheet '$($WorkSheet).name': $_"} 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
}
}

View File

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

View File

@@ -321,28 +321,25 @@ function Import-Excel {
} }
Process { Process {
Try { #region Open file
#region Open file try {
$Path = (Resolve-Path $Path).ProviderPath $Path = (Resolve-Path $Path).ProviderPath
Write-Verbose "Import Excel workbook '$Path' with worksheet '$Worksheetname'" Write-Verbose "Import Excel workbook '$Path' with worksheet '$Worksheetname'"
$Stream = New-Object -TypeName System.IO.FileStream -ArgumentList $Path, 'Open', 'Read', 'ReadWrite' $Stream = New-Object -TypeName System.IO.FileStream -ArgumentList $Path, 'Open', 'Read', 'ReadWrite'
}
Catch {throw "Could not open $Path ; $_ "}
if ($Password) { if ($Password) {
$Excel = New-Object -TypeName OfficeOpenXml.ExcelPackage Try {$Excel = New-Object -TypeName OfficeOpenXml.ExcelPackage
$excel.Load( $Stream,$Password)}
Try { Catch { throw "Could not read $Path with the provided password." }
$Excel.Load($Stream,$Password) }
} else {
Catch { try {$Excel = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Stream}
throw "Password '$Password' is not correct." Catch {throw "Failed to read $Path"}
} }
} #endregion
else { Try {
$Excel = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Stream
}
#endregion
#region Select worksheet #region Select worksheet
if ($WorksheetName) { if ($WorksheetName) {
if (-not ($Worksheet = $Excel.Workbook.Worksheets[$WorkSheetName])) { if (-not ($Worksheet = $Excel.Workbook.Worksheets[$WorkSheetName])) {
@@ -512,3 +509,20 @@ function Export-MultipleExcelSheets {
if($Show) {Invoke-Item $Path} 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
}

View File

@@ -18,49 +18,7 @@ Begin {
Try { Try {
Write-Verbose "$ModuleName module installation started" Write-Verbose "$ModuleName module installation started"
$Files = @( $Files = Get-Content $PSScriptRoot\filelist.txt
'*.dll',
'*.psd1',
'*.psm1',
'AddConditionalFormatting.ps1',
'Charting.ps1',
'ColorCompletion.ps1',
'Compare-Worksheet.ps1',
'ConvertFromExcelData.ps1',
'ConvertFromExcelToSQLInsert.ps1',
'ConvertExcelToImageFile.ps1',
'ConvertToExcelXlsx.ps1',
'Copy-ExcelWorkSheet.ps1',
'Export-Charts.ps1',
'Export-Excel.ps1',
'Export-ExcelSheet.ps1',
'formatting.ps1',
'Get-ExcelColumnName.ps1',
'Get-ExcelSheetInfo.ps1',
'Get-ExcelWorkbookInfo.ps1',
'Get-HtmlTable.ps1',
'Get-Range.ps1',
'Get-XYRange.ps1',
'Import-Html.ps1',
'InferData.ps1',
'Invoke-Sum.ps1',
'Join-Worksheet.ps1',
'Merge-Worksheet.ps1',
'New-ConditionalFormattingIconSet.ps1',
'New-ConditionalText.ps1',
'New-ExcelChart.ps1',
'New-PSItem.ps1',
'Open-ExcelPackage.ps1',
'Pivot.ps1',
'Plot.ps1',
'Send-SQLDataToExcel.ps1',
'Set-CellStyle.ps1',
'Set-Column.ps1',
'Set-Row.ps1',
'SetFormat.ps1',
'TrackingUtils.ps1',
'Update-FirstObjectProperties.ps1'
)
} }
Catch { Catch {
throw "Failed installing the module '$ModuleName': $_" throw "Failed installing the module '$ModuleName': $_"

View File

@@ -10,12 +10,15 @@
This will open the file at $xlPath, select sheet1 apply formatting to two blocks of the sheet and save the package, and launch it in Excel. This will open the file at $xlPath, select sheet1 apply formatting to two blocks of the sheet and save the package, and launch it in Excel.
#> #>
[CmdLetBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")]
[OutputType([OfficeOpenXml.ExcelPackage])] [OutputType([OfficeOpenXml.ExcelPackage])]
Param ( Param (
#The Path to the file to open #The Path to the file to open
[Parameter(Mandatory=$true)]$Path, [Parameter(Mandatory=$true)]$Path,
#If specified, any running instances of Excel will be terminated before opening the file. #If specified, any running instances of Excel will be terminated before opening the file.
[switch]$KillExcel, [switch]$KillExcel,
[String]$Password,
#By default open only opens an existing file; -Create instructs it to create a new file if required. #By default open only opens an existing file; -Create instructs it to create a new file if required.
[switch]$Create [switch]$Create
) )
@@ -27,7 +30,7 @@
$Path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path) $Path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
#If -Create was not specified only open the file if it exists already (send a warning if it doesn't exist). #If -Create was not specified only open the file if it exists already (send a warning if it doesn't exist).
if ($Create) { if ($Create -and -not (Test-Path -Path $path)) {
#Create the directory if required. #Create the directory if required.
$targetPath = Split-Path -Parent -Path $Path $targetPath = Split-Path -Parent -Path $Path
if (!(Test-Path -Path $targetPath)) { if (!(Test-Path -Path $targetPath)) {
@@ -36,7 +39,10 @@
} }
New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Path New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Path
} }
elseif (Test-Path -Path $path) {New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Path } elseif (Test-Path -Path $path) {
if ($Password) {New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Path , $Password }
else {New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Path }
}
else {Write-Warning "Could not find $path" } else {Write-Warning "Could not find $path" }
} }
@@ -45,6 +51,8 @@ Function Close-ExcelPackage {
.Synopsis .Synopsis
Closes an Excel Package, saving, saving under a new name or abandoning changes and opening the file in Excel as required. Closes an Excel Package, saving, saving under a new name or abandoning changes and opening the file in Excel as required.
#> #>
[CmdLetBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")]
Param ( Param (
#File to close. #File to close.
[parameter(Mandatory=$true, ValueFromPipeline=$true)] [parameter(Mandatory=$true, ValueFromPipeline=$true)]
@@ -54,14 +62,30 @@ Function Close-ExcelPackage {
#Abandon the file without saving. #Abandon the file without saving.
[Switch]$NoSave, [Switch]$NoSave,
#Save file with a new name (ignored if -NoSave Specified). #Save file with a new name (ignored if -NoSave Specified).
$SaveAs $SaveAs,
[ValidateNotNullOrEmpty()]
[String]$Password,
#Attempt to recalculation the workbook before saving
[switch]$Calculate
) )
if ( $NoSave) {$ExcelPackage.Dispose()} if ( $NoSave) {$ExcelPackage.Dispose()}
else { else {
if ($SaveAs) {$ExcelPackage.SaveAs( $SaveAs ) } if ($Calculate) {
Else {$ExcelPackage.Save(); $SaveAs = $ExcelPackage.File.FullName } try { [OfficeOpenXml.CalculationExtension]::Calculate($ExcelPackage.Workbook) }
Catch { Write-Warning "One or more errors occured while calculating, save will continue, but there may be errors in the workbook."}
}
if ($SaveAs) {
$SaveAs = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($SaveAs)
if ($Password) {$ExcelPackage.SaveAs( $SaveAs, $Password ) }
else {$ExcelPackage.SaveAs( $SaveAs)}
}
Else {
if ($Password) {$ExcelPackage.Save($Password) }
else {$ExcelPackage.Save() }
$SaveAs = $ExcelPackage.File.FullName
}
$ExcelPackage.Dispose() $ExcelPackage.Dispose()
if ($show) {Start-Process -FilePath $SaveAs } if ($Show) {Start-Process -FilePath $SaveAs }
} }
} }

View File

@@ -51,8 +51,35 @@ Install-Module ImportExcel -scope CurrentUser
```PowerShell ```PowerShell
Install-Module ImportExcel Install-Module ImportExcel
``` ```
# New to Aug 16th
- Value does not need to be mandatory in Set-Row or Set-Column, also tidied their parameters a little.
- Added support for array formulas in Set-Format (it really should be set range now that it sets values, formulas and hyperlinks - that can go on the to-do list )
- Fixed a bug with -Append in Export-Excel which caused it to overwrite the last row if the new data was a simple type.
- NumberFormat in Export-Excel now sets the default for on a new / blank sheet; but [still] sets individual cells when adding to a sheet
- Added support for timespans in Export excel ; set as elapsed hours, mins, secs [h]:mm:sss
- In Export-Excel improved the catch-all handler for insuring values to cope better with nested objects (#419) and reduce the number of parse operations
- Added -Calculate switch to Export-Excel and Close-Excel Package; EPPlus needs formulas to OMIT the leading = sign so where formula is set it now strips a leading = sign
- Added -PivotTotals parameter where there was already -NoTotalsInPivot new one allows None, Both, Rows, Columns. (#415)
- When appending Export-Excel only extended tables and ranges if they were explicitly specified. It now does it automatically.
- Compare and Merge worksheet originally had a problem with > 26 columns, I fixed merge turns out I hadn't fixed compare ... I have now
- Fixed bug where Export-Excel would not recognize it had to set $TitleFillPattern - made the default 'Solid'
- ExcludeProperty in Export-Excel now supports wildcards.
- Added DateTime to the list of types which can be exported as single column.
- Added Password support to Open- and Close-ExcelPackage (password was not doing anything in Export-Excel)
- Gave Expand-NumberFormat a better grasp of currency layouts - it follows .NET which is not always the same as Excel would set:-(
# What's new to 18th July 18 # What's new in Release 5.1.1
- 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 parameters (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
- Made the same changes to Add-Conditional format as set format so -switch:$false is processed, and 0 enums and values are processed correctly
- In Export-Excel, wrapped calls to Add-CellValue in a try catch so a value which causes an issue doesn't crash the whole export but generates a warning instead (#410) .
- Additional tests.
# What's new to July 18
- Changed parameter evaluation in Set-Format to support -bold:$false (and other switches so that if false is specified the attribute will be removed ), and to bug were enums with a value of zero, and other zero parameters were not set.
- 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 . - 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 .
- Added -BarChart -ColumnChart -LineChart -PieChart parameters to Export-Excel for quick charts without giving a full chart definition. - Added -BarChart -ColumnChart -LineChart -PieChart parameters to Export-Excel for quick charts without giving a full chart definition.
- Added parameters for managing chart Axes and legend - Added parameters for managing chart Axes and legend

View File

@@ -20,16 +20,16 @@
#The sheet to update can be a given as a name or an Excel Worksheet object - this sets it by name #The sheet to update can be a given as a name or an Excel Worksheet object - this sets it by name
[Parameter(ParameterSetName="Package")] [Parameter(ParameterSetName="Package")]
#The sheet to update can be a given as a name or an Excel Worksheet object - $workSheet contains the object #The sheet to update can be a given as a name or an Excel Worksheet object - $workSheet contains the object
$Worksheetname = "Sheet1", [String]$Worksheetname = "Sheet1",
[Parameter(ParameterSetName="sheet",Mandatory=$true)] [Parameter(ParameterSetName="sheet",Mandatory=$true)]
[OfficeOpenXml.ExcelWorksheet] [OfficeOpenXml.ExcelWorksheet]$Worksheet,
$Worksheet,
#Column to fill down - first column is 1. 0 will be interpreted as first unused column #Column to fill down - first column is 1. 0 will be interpreted as first unused column
[ValidateRange(0,16384)]
$Column = 0 , $Column = 0 ,
#First row to fill data in #First row to fill data in
[ValidateRange(1,1048576)]
[Int]$StartRow , [Int]$StartRow ,
#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 to fill in. Script block can use $row, $column [number], $columnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn
[parameter(Mandatory=$true)]
$Value , $Value ,
#Optional column heading #Optional column heading
$Heading , $Heading ,
@@ -41,15 +41,15 @@
#Colour for the text - if none specified it will be left as it it is #Colour for the text - if none specified it will be left as it it is
[System.Drawing.Color]$FontColor, [System.Drawing.Color]$FontColor,
#Make text bold; use -Bold:$false to remove bold #Make text bold; use -Bold:$false to remove bold
[switch]$Bold, [Switch]$Bold,
#Make text italic; use -Italic:$false to remove italic #Make text italic; use -Italic:$false to remove italic
[switch]$Italic, [Switch]$Italic,
#Underline the text using the underline style in -underline type; use -Underline:$false to remove underlining #Underline the text using the underline style in -underline type; use -Underline:$false to remove underlining
[switch]$Underline, [Switch]$Underline,
#Should Underline use single or double, normal or accounting mode : default is single normal #Should Underline use single or double, normal or accounting mode : default is single normal
[OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single, [OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single,
#Strike through text; use -Strikethru:$false to remove Strike through #Strike through text; use -Strikethru:$false to remove Strike through
[switch]$StrikeThru, [Switch]$StrikeThru,
#Subscript or superscript (or none) #Subscript or superscript (or none)
[OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift, [OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift,
#Font to use - Excel defaults to Calibri #Font to use - Excel defaults to Calibri
@@ -64,7 +64,7 @@
[Alias("PatternColour")] [Alias("PatternColour")]
[System.Drawing.Color]$PatternColor, [System.Drawing.Color]$PatternColor,
#Turn on text wrapping; use -WrapText:$false to turn off word wrapping #Turn on text wrapping; use -WrapText:$false to turn off word wrapping
[switch]$WrapText, [Switch]$WrapText,
#Position cell contents to left, right, center etc. default is 'General' #Position cell contents to left, right, center etc. default is 'General'
[OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment, [OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment,
#Position cell contents to top bottom or centre #Position cell contents to top bottom or centre
@@ -79,40 +79,53 @@
[float]$Width, [float]$Width,
#Set the inserted data to be a named range (ignored if header is not specified) #Set the inserted data to be a named range (ignored if header is not specified)
[Switch]$AutoNameRange, [Switch]$AutoNameRange,
#If Sepecified returns the range of cells which affected #If Sepecified returns the range of cells which were affected
[switch]$ReturnRange, [Switch]$ReturnRange,
#If Specified, return an ExcelPackage object to allow further work to be done on the file. #If Specified, return an ExcelPackage object to allow further work to be done on the file.
[switch]$PassThru [Switch]$PassThru
) )
#if we were passed a package object and a worksheet name , get the worksheet. #if we were passed a package object and a worksheet name , get the worksheet.
if ($ExcelPackage) {$Worksheet = $ExcelPackage.Workbook.Worksheets[$Worksheetname] } if ($ExcelPackage) {$Worksheet = $ExcelPackage.Workbook.Worksheets[$Worksheetname] }
#In a script block to build a formula, we may want any of corners or the columnname, #In a script block to build a formula, we may want any of corners or the column name,
#if column and startrow aren't specified, assume first unused column, and first row #if Column and Startrow aren't specified, assume first unused column, and first row
if (-not $StartRow) {$startRow = $Worksheet.Dimension.Start.Row } if (-not $StartRow) {$startRow = $Worksheet.Dimension.Start.Row }
$StartColumn = $Worksheet.Dimension.Start.Column $startColumn = $Worksheet.Dimension.Start.Column
$endColumn = $Worksheet.Dimension.End.Column $endColumn = $Worksheet.Dimension.End.Column
$endRow = $Worksheet.Dimension.End.Row $endRow = $Worksheet.Dimension.End.Row
if ($Column -lt 2 ) {$Column = $endColumn + 1 } if ($Column -eq 0 ) {$Column = $endColumn + 1 }
$ColumnName = [OfficeOpenXml.ExcelCellAddress]::new(1,$column).Address -replace "1","" $columnName = [OfficeOpenXml.ExcelCellAddress]::new(1,$column).Address -replace "1",""
Write-Verbose -Message "Updating Column $ColumnName" Write-Verbose -Message "Updating Column $columnName"
#If there is a heading, insert it and use it as the name for a range (if we're creating one) #If there is a heading, insert it and use it as the name for a range (if we're creating one)
if ($Heading) { if ($Heading) {
$Worksheet.Cells[$StartRow, $Column].Value = $heading $Worksheet.Cells[$StartRow, $Column].Value = $Heading
$startRow ++ $StartRow ++
if ($AutoNameRange) { $Worksheet.Names.Add( $heading, ($Worksheet.Cells[$startrow, $Column, $endRow, $Column]) ) | Out-Null } if ($AutoNameRange) { $Worksheet.Names.Add( $Heading, ($Worksheet.Cells[$StartRow, $Column, $endRow, $Column]) ) | Out-Null }
} }
#Fill in the data #Fill in the data
if ($PSBoundParameters.ContainsKey('value')) { foreach ($row in ($StartRow.. $endRow)) { if ($PSBoundParameters.ContainsKey('Value')) { foreach ($row in ($StartRow..$endRow)) {
if ($Value -is [scriptblock]) { #re-create the script block otherwise variables from this function are out of scope. if ($Value -is [scriptblock]) { #re-create the script block otherwise variables from this function are out of scope.
$cellData = & ([scriptblock]::create( $Value )) $cellData = & ([scriptblock]::create( $Value ))
Write-Verbose -Message $cellData Write-Verbose -Message $cellData
} }
else { $cellData = $Value} else { $cellData = $Value}
if ($cellData -match "^=") { $Worksheet.Cells[$Row, $Column].Formula = $cellData } if ($cellData -match "^=") { $Worksheet.Cells[$Row, $Column].Formula = ($cellData -replace '^=','') } #EPPlus likes formulas with no = sign; Excel doesn't care
else { $Worksheet.Cells[$Row, $Column].Value = $cellData } elseif ( [System.Uri]::IsWellFormedUriString($cellData , [System.UriKind]::Absolute)) {
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. # 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.
if ($cellData -is [timespan]) { $Worksheet.Cells[$Row, $Column].Style.Numberformat.Format = '[h]:mm:ss' }
}} }}
#region Apply formatting #region Apply formatting
$params = @{} $params = @{}
@@ -121,7 +134,7 @@
'BorderAround', 'BackgroundColor', 'BackgroundPattern', 'PatternColor')) { 'BorderAround', 'BackgroundColor', 'BackgroundPattern', 'PatternColor')) {
if ($PSBoundParameters.ContainsKey($p)) {$params[$p] = $PSBoundParameters[$p]} if ($PSBoundParameters.ContainsKey($p)) {$params[$p] = $PSBoundParameters[$p]}
} }
$theRange = "$ColumnName$startRow`:$ColumnName$endRow" $theRange = "$columnName$StartRow`:$columnName$endRow"
if ($params.Count) { if ($params.Count) {
Set-Format -WorkSheet $Worksheet -Range $theRange @params Set-Format -WorkSheet $Worksheet -Range $theRange @params
} }

View File

@@ -25,15 +25,13 @@
[Parameter(ParameterSetName="Package")] [Parameter(ParameterSetName="Package")]
$Worksheetname = "Sheet1", $Worksheetname = "Sheet1",
#A worksheet object #A worksheet object
[Parameter(ParameterSetName="sheet",Mandatory=$true)] [Parameter(ParameterSetName="Sheet",Mandatory=$true)]
[OfficeOpenXml.Excelworksheet] [OfficeOpenXml.Excelworksheet] $Worksheet,
$Worksheet,
#Row to fill right - first row is 1. 0 will be interpreted as first unused row #Row to fill right - first row is 1. 0 will be interpreted as first unused row
$Row = 0 , $Row = 0 ,
#Position in the row to start from #Position in the row to start from
[Int]$StartColumn, [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 to fill in. Script block can use $worksheet, $row, $Column [number], $ColumnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn
[parameter(Mandatory=$true)]
$Value, $Value,
#Optional Row heading #Optional Row heading
$Heading , $Heading ,
@@ -45,15 +43,15 @@
#Colour for the text - if none specified it will be left as it it is #Colour for the text - if none specified it will be left as it it is
[System.Drawing.Color]$FontColor, [System.Drawing.Color]$FontColor,
#Make text bold; use -Bold:$false to remove bold #Make text bold; use -Bold:$false to remove bold
[switch]$Bold, [Switch]$Bold,
#Make text italic; use -Italic:$false to remove italic #Make text italic; use -Italic:$false to remove italic
[switch]$Italic, [Switch]$Italic,
#Underline the text using the underline style in -underline type; use -Underline:$false to remove underlining #Underline the text using the underline style in -underline type; use -Underline:$false to remove underlining
[switch]$Underline, [Switch]$Underline,
#Should Underline use single or double, normal or accounting mode : default is single normal #Should Underline use single or double, normal or accounting mode : default is single normal
[OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single, [OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single,
#Strike through text; use -Strikethru:$false to remove Strike through #Strike through text; use -Strikethru:$false to remove Strike through
[switch]$StrikeThru, [Switch]$StrikeThru,
#Subscript or superscript (or none) #Subscript or superscript (or none)
[OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift, [OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift,
[String]$FontName, [String]$FontName,
@@ -67,7 +65,7 @@
[Alias("PatternColour")] [Alias("PatternColour")]
[System.Drawing.Color]$PatternColor, [System.Drawing.Color]$PatternColor,
#Turn on text wrapping; use -WrapText:$false to turn off word wrapping #Turn on text wrapping; use -WrapText:$false to turn off word wrapping
[switch]$WrapText, [Switch]$WrapText,
#Position cell contents to left, right, center etc. default is 'General' #Position cell contents to left, right, center etc. default is 'General'
[OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment, [OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment,
#Position cell contents to top bottom or centre #Position cell contents to top bottom or centre
@@ -77,10 +75,10 @@
[int]$TextRotation , [int]$TextRotation ,
#Set cells to a fixed hieght #Set cells to a fixed hieght
[float]$Height, [float]$Height,
#If Sepecified returns the range of cells which affected #If Sepecified returns the range of cells which were affected
[switch]$ReturnRange, [Switch]$ReturnRange,
#If Specified, return a row object to allow further work to be done #If Specified, return a row object to allow further work to be done
[switch]$PassThru [Switch]$PassThru
) )
#if we were passed a package object and a worksheet name , get the worksheet. #if we were passed a package object and a worksheet name , get the worksheet.
@@ -92,7 +90,7 @@
$startRow = $Worksheet.Dimension.Start.Row + 1 $startRow = $Worksheet.Dimension.Start.Row + 1
$endColumn = $Worksheet.Dimension.End.Column $endColumn = $Worksheet.Dimension.End.Column
$endRow = $Worksheet.Dimension.End.Row $endRow = $Worksheet.Dimension.End.Row
if ($Row -lt 2 ) {$Row = $endRow + 1 } if ($Row -eq 0 ) {$Row = $endRow + 1 }
Write-Verbose -Message "Updating Row $Row" Write-Verbose -Message "Updating Row $Row"
#Add a row label #Add a row label
if ($Heading) { if ($Heading) {
@@ -100,18 +98,31 @@
$StartColumn ++ $StartColumn ++
} }
#Fill in the data #Fill in the data
if ($PSBoundParameters.ContainsKey('Value')) {foreach ($column in ($StartColumn..$EndColumn)) { if ($PSBoundParameters.ContainsKey('Value')) {foreach ($column in ($StartColumn..$endColumn)) {
#We might want the column name in a script block #We might want the column name in a script block
$ColumnName = [OfficeOpenXml.ExcelCellAddress]::new(1,$column).Address -replace "1","" $columnName = [OfficeOpenXml.ExcelCellAddress]::new(1,$column).Address -replace "1",""
if ($Value -is [scriptblock] ) { if ($Value -is [scriptblock] ) {
#re-create the script block otherwise variables from this function are out of scope. #re-create the script block otherwise variables from this function are out of scope.
$cellData = & ([scriptblock]::create( $Value )) $cellData = & ([scriptblock]::create( $Value ))
Write-Verbose -Message $cellData Write-Verbose -Message $cellData
} }
else{$cellData = $Value} else{$cellData = $Value}
if ($cellData -match "^=") { $Worksheet.Cells[$Row, $column].Formula = $cellData } if ($cellData -match "^=") { $Worksheet.Cells[$Row, $column].Formula = ($cellData -replace '^=','') } #EPPlus likes formulas with no = sign; Excel doesn't care
else { $Worksheet.Cells[$Row, $column].Value = $cellData } elseif ( [System.Uri]::IsWellFormedUriString($cellData , [System.UriKind]::Absolute)) {
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. # 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.
if ($cellData -is [timespan]) { $Worksheet.Cells[$Row, $Column].Style.Numberformat.Format = '[h]:mm:ss' }
}} }}
#region Apply formatting #region Apply formatting
$params = @{} $params = @{}
@@ -120,7 +131,7 @@
'BorderAround', 'BackgroundColor', 'BackgroundPattern', 'PatternColor')) { 'BorderAround', 'BackgroundColor', 'BackgroundPattern', 'PatternColor')) {
if ($PSBoundParameters.ContainsKey($p)) {$params[$p] = $PSBoundParameters[$p]} if ($PSBoundParameters.ContainsKey($p)) {$params[$p] = $PSBoundParameters[$p]}
} }
$theRange = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R[$Row]C[$StartColumn]:R[$Row]C[$EndColumn]",0,0) $theRange = [OfficeOpenXml.ExcelAddress]::New($Row, $StartColumn, $Row, $endColumn)
if ($params.Count) { if ($params.Count) {
Set-Format -WorkSheet $Worksheet -Range $theRange @params Set-Format -WorkSheet $Worksheet -Range $theRange @params
} }

View File

@@ -20,7 +20,7 @@
#The area of the worksheet where the format is to be applied #The area of the worksheet where the format is to be applied
[Parameter(ParameterSetName="SheetAndRange",Mandatory=$True)] [Parameter(ParameterSetName="SheetAndRange",Mandatory=$True)]
[OfficeOpenXml.ExcelAddress]$Range, [OfficeOpenXml.ExcelAddress]$Range,
#Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc #Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc
[Alias("NFormat")] [Alias("NFormat")]
$NumberFormat, $NumberFormat,
#Style of border to draw around the range #Style of border to draw around the range
@@ -36,18 +36,20 @@
$Value, $Value,
#Formula for the cell #Formula for the cell
$Formula, $Formula,
#Specifies formula should be an array formula (a.k.a CSE [ctrl-shift-enter] formula )
[Switch]$ArrayFormula,
#Clear Bold, Italic, StrikeThrough and Underline and set colour to black #Clear Bold, Italic, StrikeThrough and Underline and set colour to black
[switch]$ResetFont, [Switch]$ResetFont,
#Make text bold; use -Bold:$false to remove bold #Make text bold; use -Bold:$false to remove bold
[switch]$Bold, [Switch]$Bold,
#Make text italic; use -Italic:$false to remove italic #Make text italic; use -Italic:$false to remove italic
[switch]$Italic, [Switch]$Italic,
#Underline the text using the underline style in -underline type; use -Underline:$false to remove underlining #Underline the text using the underline style in -underline type; use -Underline:$false to remove underlining
[switch]$Underline, [Switch]$Underline,
#Should Underline use single or double, normal or accounting mode : default is single normal #Should Underline use single or double, normal or accounting mode : default is single normal
[OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single, [OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single,
#Strike through text; use -Strikethru:$false to remove Strike through #Strike through text; use -Strikethru:$false to remove Strike through
[switch]$StrikeThru, [Switch]$StrikeThru,
#Subscript or superscript (or none) #Subscript or superscript (or none)
[OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift, [OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift,
#Font to use - Excel defaults to Calibri #Font to use - Excel defaults to Calibri
@@ -62,7 +64,7 @@
[Alias("PatternColour")] [Alias("PatternColour")]
[System.Drawing.Color]$PatternColor, [System.Drawing.Color]$PatternColor,
#Turn on text wrapping; use -WrapText:$false to turn off word wrapping #Turn on text wrapping; use -WrapText:$false to turn off word wrapping
[switch]$WrapText, [Switch]$WrapText,
#Position cell contents to left, right, center etc. default is 'General' #Position cell contents to left, right, center etc. default is 'General'
[OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment, [OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment,
#Position cell contents to top bottom or center #Position cell contents to top bottom or center
@@ -78,7 +80,7 @@
#Set cells to a fixed hieght (rows or ranges only) #Set cells to a fixed hieght (rows or ranges only)
[float]$Height, [float]$Height,
#Hide a row or column (not a range); use -Hidden:$false to unhide #Hide a row or column (not a range); use -Hidden:$false to unhide
[switch]$Hidden [Switch]$Hidden
) )
begin { begin {
#Allow Set-Format to take Worksheet and range parameters (like Add Contitional formatting) - convert them to an address #Allow Set-Format to take Worksheet and range parameters (like Add Contitional formatting) - convert them to an address
@@ -120,9 +122,6 @@
if ($PSBoundParameters.ContainsKey('FontColor')){ if ($PSBoundParameters.ContainsKey('FontColor')){
$Address.Style.Font.Color.SetColor( $FontColor) $Address.Style.Font.Color.SetColor( $FontColor)
} }
if ($PSBoundParameters.ContainsKey('NumberFormat')) {
$Address.Style.Numberformat.Format = $NumberFormat
}
if ($PSBoundParameters.ContainsKey('TextRotation')) { if ($PSBoundParameters.ContainsKey('TextRotation')) {
$Address.Style.TextRotation = $TextRotation $Address.Style.TextRotation = $TextRotation
} }
@@ -136,10 +135,19 @@
$Address.Style.VerticalAlignment = $VerticalAlignment $Address.Style.VerticalAlignment = $VerticalAlignment
} }
if ($PSBoundParameters.ContainsKey('Value')) { if ($PSBoundParameters.ContainsKey('Value')) {
$Address.Value = $Value if ($Value -like '=*') {$PSBoundParameters["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 ($Value -is [timespan]) { $Address.Style.Numberformat.Format = '[h]:mm:ss' }
}
} }
if ($PSBoundParameters.ContainsKey('Formula')) { if ($PSBoundParameters.ContainsKey('Formula')) {
$Address.Formula = $Formula if ($ArrayFormula) {$Address.CreateArrayFormula(($Formula -replace '^=','')) }
else {$Address.Formula = ($Formula -replace '^=','') }
}
if ($PSBoundParameters.ContainsKey('NumberFormat')) {
$Address.Style.Numberformat.Format = (Expand-NumberFormat $NumberFormat)
} }
if ($PSBoundParameters.ContainsKey('BorderAround')) { if ($PSBoundParameters.ContainsKey('BorderAround')) {
$Address.Style.Border.BorderAround($BorderAround, $BorderColor) $Address.Style.Border.BorderAround($BorderAround, $BorderColor)
@@ -194,12 +202,107 @@
} }
else {Write-Warning -Message ("Can set the width of a column or a range but not a {0} object" -f ($Address.GetType().name)) } 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 if ($Address -is [OfficeOpenXml.ExcelRow] -or
$Address -is [OfficeOpenXml.ExcelColumn] ) {$Address.Hidden = [boolean]$Hidden} $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)) } else {Write-Warning -Message ("Can hide a row or a column but not a {0} object" -f ($Address.GetType().name)) }
} }
} }
} }
} }
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" {
#https://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencynegativepattern(v=vs.110).aspx
$sign = [cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol
switch ([cultureinfo]::CurrentCulture.NumberFormat.CurrencyPositivePattern) {
0 {$pos = "$Sign#,##0.00" ; break }
1 {$pos = "#,##0.00$Sign" ; break }
2 {$pos = "$Sign #,##0.00" ; break }
3 {$pos = "#,##0.00 $Sign" ; break }
}
switch ([cultureinfo]::CurrentCulture.NumberFormat.CurrencyPositivePattern) {
0 {return "$pos;($Sign#,##0.00)" }
1 {return "$pos;-$Sign#,##0.00" }
2 {return "$pos;$Sign-#,##0.00" }
3 {return "$pos;$Sign#,##0.00-" }
4 {return "$pos;(#,##0.00$Sign)" }
5 {return "$pos;-#,##0.00$Sign" }
6 {return "$pos;#,##0.00-$Sign" }
7 {return "$pos;#,##0.00$Sign-" }
8 {return "$pos;-#,##0.00 $Sign" }
9 {return "$pos;-$Sign #,##0.00" }
10 {return "$pos;#,##0.00 $Sign-" }
11 {return "$pos;$Sign #,##0.00-" }
12 {return "$pos;$Sign -#,##0.00" }
13 {return "$pos;#,##0.00- $Sign" }
14 {return "$pos;($Sign #,##0.00)" }
15 {return "$pos;(#,##0.00 $Sign)" }
}
}
"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}
}
}

26
ToDo.md
View File

@@ -1,11 +1,19 @@
- [ ] 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
- [x] Allow Exclude property to take wildcards
- [ ] 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 - [ ] 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 - [ ] 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). - [ ] Add examples to add-ConditionalFormat, set-format,set-Row and Set-column (e.g. from tests)
- [ ] Test Add PivotTable selecting source sheet by position , UnhideSheet, and Wildcard support for hideSheet - [ ] 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).
- [ ] 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) - [X] Test password behaviour in Export-Excel Open & Close-Excel Package
- [ ] Increase code covereage for import-excel and Set-Format - [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

View File

@@ -1,6 +1,8 @@
#Requires -Modules Pester #Requires -Modules Pester
Import-Module $PSScriptRoot\..\ImportExcel.psd1 -Force Import-Module $PSScriptRoot\..\ImportExcel.psd1 -Force
Add-Type -AssemblyName System.Windows.Forms
Describe "Compare Worksheet" { Describe "Compare Worksheet" {
Context "Simple comparison output" { Context "Simple comparison output" {
BeforeAll { BeforeAll {
@@ -235,7 +237,7 @@ Describe "Merge Worksheet" {
} }
} }
Context "Wider data set" { 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 { Merge-Worksheet -Referencefile "$env:temp\server1.xlsx" -Differencefile "$env:temp\Server2.xlsx" -OutputFile "$env:temp\combined2.xlsx" } | Should not throw
} }
} }

View File

@@ -4,8 +4,8 @@ Remove-item -Path $path1, $path2 -ErrorAction SilentlyContinue
$ProcRange = Get-Process | Export-Excel $path1 -DisplayPropertySet -WorkSheetname Processes -ReturnRange $ProcRange = Get-Process | Export-Excel $path1 -DisplayPropertySet -WorkSheetname Processes -ReturnRange
if ((Get-Culture).NumberFormat.CurrencySymbol -eq "£") {$OtherCurrencySymbol = "$"} if ((Get-Culture).NumberFormat.CurrencySymbol -eq "<EFBFBD>") {$OtherCurrencySymbol = "$"}
else {$OtherCurrencySymbol = "£"} else {$OtherCurrencySymbol = "<EFBFBD>"}
[PSCustOmobject][Ordered]@{ [PSCustOmobject][Ordered]@{
Date = Get-Date Date = Get-Date
Formula1 = '=SUM(F2:G2)' Formula1 = '=SUM(F2:G2)'
@@ -25,8 +25,8 @@ else {$OtherCurrencySymbol = "
StrE164Phone = '+32 (444) 444 4444' StrE164Phone = '+32 (444) 444 4444'
StrAltPhone1 = '+32 4 4444 444' StrAltPhone1 = '+32 4 4444 444'
StrAltPhone2 = '+3244444444' StrAltPhone2 = '+3244444444'
StrLeadSpace = ' 123' StrLeadSpace = ' 123'
StrTrailSpace = '123 ' StrTrailSpace = '123 '
Link1 = [uri]"https://github.com/dfinke/ImportExcel" Link1 = [uri]"https://github.com/dfinke/ImportExcel"
Link2 = "https://github.com/dfinke/ImportExcel" # Links are not copied correctly, hopefully this will be fixed at some future date Link2 = "https://github.com/dfinke/ImportExcel" # Links are not copied correctly, hopefully this will be fixed at some future date
} | Export-Excel -NoNumberConversion IPAddress, StrLeadZero, StrAltPhone2 -WorkSheetname MixedTypes -Path $path2 } | Export-Excel -NoNumberConversion IPAddress, StrLeadZero, StrAltPhone2 -WorkSheetname MixedTypes -Path $path2
@@ -37,7 +37,7 @@ Describe "Copy-Worksheet" {
$excel = Open-ExcelPackage -Path $path2 $excel = Open-ExcelPackage -Path $path2
$ws = $excel.Workbook.Worksheets["Processes"] $ws = $excel.Workbook.Worksheets["Processes"]
} }
it "inserted a worksheet " { it "Inserted a worksheet " {
$Excel.Workbook.Worksheets.count | Should be 2 $Excel.Workbook.Worksheets.count | Should be 2
$ws | Should not benullorEmpty $ws | Should not benullorEmpty
$ws.Dimension.Address | should be $ProcRange $ws.Dimension.Address | should be $ProcRange
@@ -50,14 +50,16 @@ Describe "Copy-Worksheet" {
$excel = Open-ExcelPackage -Path $path2 $excel = Open-ExcelPackage -Path $path2
$ws = $Excel.Workbook.Worksheets[3] $ws = $Excel.Workbook.Worksheets[3]
} }
it "inserted a worksheet with the expected name, number of rows and number of columns " { it "Copied a worksheet, giving the expected name, number of rows and number of columns " {
$Excel.Workbook.Worksheets.count | Should be 3 $Excel.Workbook.Worksheets.count | Should be 3
$ws | Should not benullorEmpty $ws | Should not benullorEmpty
$ws.Name | Should be "CopyOfMixedTypes" $ws.Name | Should be "CopyOfMixedTypes"
$ws.Dimension.Columns | Should be 22 $ws.Dimension.Columns | Should be 22
$ws.Dimension.Rows | Should be 2 $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, 1].Value.Gettype().name | Should be 'DateTime'
$ws.Cells[2, 2].Formula | Should be '=SUM(F2:G2)' $ws.Cells[2, 2].Formula | Should be 'SUM(F2:G2)'
$ws.Cells[2, 5].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, 6].Value.GetType().name | Should be 'String'
$ws.Cells[2, 18].Value.GetType().name | Should be 'String' $ws.Cells[2, 18].Value.GetType().name | Should be 'String'

View File

@@ -1,8 +1,6 @@
#Requires -Modules Pester #Requires -Modules Pester
# $here = Split-Path -Parent $MyInvocation.MyCommand.Path #Import-Module $PSScriptRoot\..\ImportExcel.psd1 -Force
# Import-Module $here -Force -Verbose
Import-Module $PSScriptRoot\..\ImportExcel.psd1 -Force
if (Get-process -Name Excel,xlim -ErrorAction SilentlyContinue) { Write-Warning -Message "You need to close Excel before running the tests." ; return} if (Get-process -Name Excel,xlim -ErrorAction SilentlyContinue) { Write-Warning -Message "You need to close Excel before running the tests." ; return}
Describe ExportExcel { Describe ExportExcel {
@@ -10,7 +8,8 @@ Describe ExportExcel {
Context "#Example 1 # Creates and opens a file with the right number of rows and columns" { Context "#Example 1 # Creates and opens a file with the right number of rows and columns" {
$path = "$env:TEMP\Test.xlsx" $path = "$env:TEMP\Test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue Remove-item -Path $path -ErrorAction SilentlyContinue
$processes = Get-Process #Test with a maximum of 100 processes for speed; export all properties, then export smaller subsets.
$processes = Get-Process | select-object -first 100
$propertyNames = $Processes[0].psobject.properties.name $propertyNames = $Processes[0].psobject.properties.name
$rowcount = $Processes.Count $rowcount = $Processes.Count
$Processes | Export-Excel $path #-show $Processes | Export-Excel $path #-show
@@ -50,7 +49,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] $STHeader = $ws.cells["1:1"].where( {$_.Value -eq "StartTime"})[0]
$STCell = $STHeader.Address -replace '1$', '2' $STCell = $STHeader.Address -replace '1$', '2'
$ws.cells[$stcell].Style.Numberformat.NumFmtID | Should be 22 $ws.cells[$stcell].Style.Numberformat.NumFmtID | Should be 22
@@ -66,16 +65,16 @@ Describe ExportExcel {
Context " # NoAliasOrScriptPropeties -ExcludeProperty and -DisplayPropertySet work" { Context " # NoAliasOrScriptPropeties -ExcludeProperty and -DisplayPropertySet work" {
$path = "$env:TEMP\Test.xlsx" $path = "$env:TEMP\Test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue Remove-item -Path $path -ErrorAction SilentlyContinue
$processes = Get-Process $processes = Get-Process | Select-Object -First 100
$propertyNames = $Processes[0].psobject.properties.where( {$_.MemberType -eq 'Property'}).name $propertyNames = $Processes[0].psobject.properties.where( {$_.MemberType -eq 'Property'}).name
$rowcount = $Processes.Count $rowcount = $Processes.Count
#TestCreating a range with a name which needs illegal chars removing #Test -NoAliasOrScriptPropeties option and creating a range with a name which needs illegal chars removing - check this sends back a warning
$warnVar = $null $warnVar = $null
$Processes | Export-Excel $path -NoAliasOrScriptPropeties -RangeName "No Spaces" -WarningVariable warnvar -WarningAction SilentlyContinue $Processes | Export-Excel $path -NoAliasOrScriptPropeties -RangeName "No Spaces" -WarningVariable warnvar -WarningAction SilentlyContinue
$Excel = Open-ExcelPackage -Path $path $Excel = Open-ExcelPackage -Path $path
$ws = $Excel.Workbook.Worksheets[1] $ws = $Excel.Workbook.Worksheets[1]
it "Created a new file with alias & Script Properties removed. " { it "Created a new file with Alias & Script Properties removed. " {
$ws.Name | Should be "sheet1" $ws.Name | Should be "sheet1"
$ws.Dimension.Columns | Should be $propertyNames.Count $ws.Dimension.Columns | Should be $propertyNames.Count
$ws.Dimension.Rows | Should be ($rowcount + 1 ) # +1 for the header. $ws.Dimension.Rows | Should be ($rowcount + 1 ) # +1 for the header.
@@ -86,19 +85,20 @@ Describe ExportExcel {
$ws.names["No_spaces"].End.Row | Should be ($rowcount + 1 ) # +1 for the header. $ws.names["No_spaces"].End.Row | Should be ($rowcount + 1 ) # +1 for the header.
$warnVar.Count | Should be 1 $warnVar.Count | Should be 1
} }
#This time use clearsheet instead of deleting the file #This time use clearsheet instead of deleting the file test -Exclude properties, including wildcards.
$Processes | Export-Excel $path -NoAliasOrScriptPropeties -ExcludeProperty SafeHandle, modules, MainModule, StartTime, Threads -ClearSheet $Processes | Export-Excel $path -ClearSheet -NoAliasOrScriptPropeties -ExcludeProperty SafeHandle, threads, modules, MainModule, StartInfo, MachineName, MainWindow*, M*workingSet
$Excel = Open-ExcelPackage -Path $path $Excel = Open-ExcelPackage -Path $path
$ws = $Excel.Workbook.Worksheets[1] $ws = $Excel.Workbook.Worksheets[1]
it "Created a new file with a further 5 properties excluded and cleared the old sheet " { it "Created a new file with further properties excluded and cleared the old sheet " {
$ws.Name | Should be "sheet1" $ws.Name | Should be "sheet1"
$ws.Dimension.Columns | Should be ($propertyNames.Count - 5) $ws.Dimension.Columns | Should be ($propertyNames.Count - 10)
$ws.Dimension.Rows | Should be ($rowcount + 1) # +1 for the header $ws.Dimension.Rows | Should be ($rowcount + 1) # +1 for the header
} }
$propertyNames = $Processes[0].psStandardmembers.DefaultDisplayPropertySet.ReferencedPropertyNames $propertyNames = $Processes[0].psStandardmembers.DefaultDisplayPropertySet.ReferencedPropertyNames
Remove-item -Path $path -ErrorAction SilentlyContinue Remove-item -Path $path -ErrorAction SilentlyContinue
#Test -DisplayPropertySet
$Processes | Export-Excel $path -DisplayPropertySet $Processes | Export-Excel $path -DisplayPropertySet
$Excel = Open-ExcelPackage -Path $path $Excel = Open-ExcelPackage -Path $path
@@ -114,7 +114,7 @@ Describe ExportExcel {
$path = "$env:TEMP\Test.xlsx" $path = "$env:TEMP\Test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue Remove-item -Path $path -ErrorAction SilentlyContinue
#testing -ReturnRange switch #testing -ReturnRange switch and applying number format to Formulas as well as values.
$returnedRange = Write-Output -1 668 34 777 860 -0.5 119 -0.1 234 788,"=A9+A10" | Export-Excel -NumberFormat '[Blue]$#,##0.00;[Red]-$#,##0.00' -Path $path -ReturnRange $returnedRange = Write-Output -1 668 34 777 860 -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 " { it "Created a new file and returned the expected range " {
Test-Path -Path $path -ErrorAction SilentlyContinue | Should be $true Test-Path -Path $path -ErrorAction SilentlyContinue | Should be $true
@@ -143,15 +143,38 @@ Describe ExportExcel {
} }
} }
Context " # Number format parameter" {
BeforeAll {
$path = "$env:temp\test.xlsx"
Remove-Item -Path $path -ErrorAction SilentlyContinue
1..10 | Export-Excel -Path $path -Numberformat 'Number'
1..10 | Export-Excel -Path $path -Numberformat 'Percentage' -Append
21..30 | Export-Excel -Path $path -Numberformat 'Currency' -StartColumn 3
$excel = Open-ExcelPackage -Path $path
$ws = $excel.Workbook.Worksheets[1]
}
it "Set the worksheet default number format correctly " {
$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")
}
}
Context "#Examples 3 & 4 # Setting cells for different data types Also added test for URI type" { Context "#Examples 3 & 4 # Setting cells for different data types Also added test for URI type" {
if ((Get-Culture).NumberFormat.CurrencySymbol -eq "£") {$OtherCurrencySymbol = "$"} if ((Get-Culture).NumberFormat.CurrencySymbol -eq "£") {$OtherCurrencySymbol = "$"}
else {$OtherCurrencySymbol = "£"} else {$OtherCurrencySymbol = "£"}
$path = "$env:TEMP\Test.xlsx" $path = "$env:TEMP\Test.xlsx"
$warnVar = $null
#Test correct export of different data types and number formats; test hyperlinks, test -NoNumberConversion test object is converted to a string with no warnings, test calcuation of formula
Remove-item -Path $path -ErrorAction SilentlyContinue Remove-item -Path $path -ErrorAction SilentlyContinue
[PSCustOmobject][Ordered]@{ [PSCustOmobject][Ordered]@{
Date = Get-Date Date = Get-Date
Formula1 = '=SUM(F2:G2)' Formula1 = '=SUM(S2:T2)'
String1 = 'My String' String1 = 'My String'
Float = [math]::pi Float = [math]::pi
IPAddress = '10.10.25.5' IPAddress = '10.10.25.5'
@@ -163,8 +186,8 @@ Describe ExportExcel {
StrNegInt = '-31' StrNegInt = '-31'
StrTrailingNeg = '31-' StrTrailingNeg = '31-'
StrParens = '(123)' StrParens = '(123)'
strLocalCurrency = ('{0}123.45' -f (Get-Culture).NumberFormat.CurrencySymbol ) strLocalCurrency = ('{0}123{1}45' -f (Get-Culture).NumberFormat.CurrencySymbol,(Get-Culture).NumberFormat.CurrencyDecimalSeparator)
strOtherCurrency = ('{0}123.45' -f $OtherCurrencySymbol ) strOtherCurrency = ('{0}123{1}45' -f $OtherCurrencySymbol ,(Get-Culture).NumberFormat.CurrencyDecimalSeparator)
StrE164Phone = '+32 (444) 444 4444' StrE164Phone = '+32 (444) 444 4444'
StrAltPhone1 = '+32 4 4444 444' StrAltPhone1 = '+32 4 4444 444'
StrAltPhone2 = '+3244444444' StrAltPhone2 = '+3244444444'
@@ -174,30 +197,36 @@ Describe ExportExcel {
Link2 = "https://github.com/dfinke/ImportExcel" Link2 = "https://github.com/dfinke/ImportExcel"
Link3 = "xl://internal/sheet1!A1" Link3 = "xl://internal/sheet1!A1"
Link4 = "xl://internal/sheet1!C5" Link4 = "xl://internal/sheet1!C5"
} | Export-Excel -NoNumberConversion IPAddress, StrLeadZero, StrAltPhone2 -Path $path Process = (Get-Process -Id $PID)
TimeSpan = [datetime]::Now.Subtract([datetime]::Today)
} | Export-Excel -NoNumberConversion IPAddress, StrLeadZero, StrAltPhone2 -Path $path -Calculate -WarningVariable $warnVar
it "Created a new file " { 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 $Excel = Open-ExcelPackage -Path $path
it "Created 1 worksheet " { it "Created 1 worksheet with no warnings " {
$Excel.Workbook.Worksheets.count | Should be 1 $Excel.Workbook.Worksheets.count | Should be 1
$warnVar | Should beNullorEmpty
} }
$ws = $Excel.Workbook.Worksheets[1] $ws = $Excel.Workbook.Worksheets[1]
it "Created the worksheet with the expected name, number of rows and number of columns " { it "Created the worksheet with the expected name, number of rows and number of columns " {
$ws.Name | Should be "sheet1" $ws.Name | Should be "sheet1"
$ws.Dimension.Columns | Should be 24 $ws.Dimension.Columns | Should be 26
$ws.Dimension.Rows | Should be 2 $ws.Dimension.Rows | Should be 2
} }
it "Set a date in Cell A2 " { 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 " { it "Set a formula in Cell B2 " {
$ws.Cells[2, 2].Formula | Should be '=SUM(F2:G2)' $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
} }
it "Set strings in Cells E2, F2 and R2 (no number conversion) " { 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, 5].Value.GetType().name | Should be 'String'
$ws.Cells[2, 6].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, 18].Value.GetType().name | Should be 'String'
} }
it "Set numbers in Cells K2,L2,M2 (diferent Negative integer formats) " { 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, 11].Value -is [valuetype] ) | Should be $true
@@ -241,12 +270,21 @@ Describe ExportExcel {
($ws.Cells[2, 19].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 ($ws.Cells[2, 20].Value -is [valuetype] ) | Should be $true
} }
it "Converted a nested object to a string (Y2) " {
$ws.Cells[2, 25].Value | should match '^System\.Diagnostics\.Process\s+\(.*\)$'
}
it "Processed a timespan object (Z2) " {
$ws.cells[2, 26].Value.ToOADate() | should beGreaterThan 0
$ws.cells[2, 26].Value.ToOADate() | should beLessThan 1
$ws.cells[2, 26].Style.Numberformat.Format | should be '[h]:mm:ss'
}
} }
Context "# # Setting cells for different data types with -noHeader" { Context "# # Setting cells for different data types with -noHeader" {
$path = "$env:TEMP\Test.xlsx" $path = "$env:TEMP\Test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue Remove-item -Path $path -ErrorAction SilentlyContinue
#Test -NoHeader & -NoNumberConversion
[PSCustOmobject][Ordered]@{ [PSCustOmobject][Ordered]@{
Date = Get-Date Date = Get-Date
Formula1 = '=SUM(F1:G1)' Formula1 = '=SUM(F1:G1)'
@@ -280,11 +318,11 @@ Describe ExportExcel {
} }
it "Set a date in Cell A1 " { 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 " { 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 " { it "Set strings in Cells E1 and F1 " {
@@ -302,23 +340,25 @@ Describe ExportExcel {
} }
Context "#Example 5 # Adding a single conditional format " { Context "#Example 5 # Adding a single conditional format " {
#Test New-ConditionalText builds correctly
$ct = New-ConditionalText -ConditionalType GreaterThan 525 -ConditionalTextColor DarkRed -BackgroundColor LightPink $ct = New-ConditionalText -ConditionalType GreaterThan 525 -ConditionalTextColor DarkRed -BackgroundColor LightPink
it "Created a Conditional format description " { it "Created a Conditional format description " {
$ct.BackgroundColor -is [System.Drawing.Color] | Should be $true $ct.BackgroundColor -is [System.Drawing.Color] | Should be $true
$ct.ConditionalTextColor -is [System.Drawing.Color] | Should be $true $ct.ConditionalTextColor -is [System.Drawing.Color] | Should be $true
$ct.ConditionalType -in [enum]::GetNames( [OfficeOpenXml.ConditionalFormatting.eExcelConditionalFormattingRuleType] ) | $ct.ConditionalType -in [enum]::GetNames( [OfficeOpenXml.ConditionalFormatting.eExcelConditionalFormattingRuleType] ) |
Should be $true Should be $true
} }
$path = "$env:TEMP\Test.xlsx" $path = "$env:TEMP\Test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue Remove-item -Path $path -ErrorAction SilentlyContinue
#Test -ConditionalText with a single conditional spec.
Write-Output 489 668 299 777 860 151 119 497 234 788 | Export-Excel -Path $path -ConditionalText $ct Write-Output 489 668 299 777 860 151 119 497 234 788 | Export-Excel -Path $path -ConditionalText $ct
it "Created a new file " { 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 #ToDo need to test applying conitional formatting to a pre-existing worksheet and removing = from formula
$Excel = Open-ExcelPackage -Path $path $Excel = Open-ExcelPackage -Path $path
$ws = $Excel.Workbook.Worksheets[1] $ws = $Excel.Workbook.Worksheets[1]
@@ -333,13 +373,11 @@ Describe ExportExcel {
$cf.Type.ToString() | Should be $ct.ConditionalType $cf.Type.ToString() | Should be $ct.ConditionalType
#$cf.Style.Fill.BackgroundColor | Should be $ct.BackgroundColor #$cf.Style.Fill.BackgroundColor | Should be $ct.BackgroundColor
# $cf.Style.Font.Color | Should be $ct.ConditionalTextColor - have to compare r.g.b # $cf.Style.Font.Color | Should be $ct.ConditionalTextColor - have to compare r.g.b
} }
} }
Context "#Example 6 # Adding multiple conditional formats using short form syntax. " { Context "#Example 6 # Adding multiple conditional formats using short form syntax. " {
#this is a test of adding more than one conditional block and using the minimal syntax for new-ConditionalText = #Test adding mutliple conditional blocks and using the minimal syntax for new-ConditionalText
$path = "$env:TEMP\Test.xlsx" $path = "$env:TEMP\Test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue Remove-item -Path $path -ErrorAction SilentlyContinue
@@ -387,6 +425,7 @@ Describe ExportExcel {
} }
$Array = $Obj1, $Obj2, $Obj3 $Array = $Obj1, $Obj2, $Obj3
#test Update-FirstObjectProperties
$newarray = $Array | Update-FirstObjectProperties $newarray = $Array | Update-FirstObjectProperties
it "Outputs as many objects as it input " { it "Outputs as many objects as it input " {
$newarray.Count | Should be $Array.Count $newarray.Count | Should be $Array.Count
@@ -402,9 +441,9 @@ Describe ExportExcel {
Context "#Examples 8 & 9 # Adding Pivot tables and charts from parameters" { Context "#Examples 8 & 9 # Adding Pivot tables and charts from parameters" {
$path = "$env:TEMP\Test.xlsx" $path = "$env:TEMP\Test.xlsx"
#This time we are not deleting the XLSX file so this Should create a new, named, sheet. #Test -passthru and -worksheetName creating a new, named, sheet in an existing file.
$Excel = Get-Process | Select-Object -first 50 -Property Name, cpu, pm, handles, company | Export-Excel $path -WorkSheetname Processes -PassThru $Excel = Get-Process | Select-Object -first 20 -Property Name, cpu, pm, handles, company | Export-Excel $path -WorkSheetname Processes -PassThru
#Testing -passthru and adding the Pivot as a second step. Want to save and re-open it ... #Testing -Excel Pacakage and adding a Pivot-table as a second step. Want to save and re-open it ...
Export-Excel -ExcelPackage $Excel -WorkSheetname Processes -IncludePivotTable -PivotRows Company -PivotData PM -NoTotalsInPivot Export-Excel -ExcelPackage $Excel -WorkSheetname Processes -IncludePivotTable -PivotRows Company -PivotData PM -NoTotalsInPivot
$Excel = Open-ExcelPackage $path $Excel = Open-ExcelPackage $path
@@ -415,7 +454,7 @@ Describe ExportExcel {
$PTws.PivotTables.Count | Should be 1 $PTws.PivotTables.Count | Should be 1
$Excel.Workbook.Worksheets["Processes"] | Should not beNullOrEmpty $Excel.Workbook.Worksheets["Processes"] | Should not beNullOrEmpty
$Excel.Workbook.Worksheets.Count | Should beGreaterThan 2 $Excel.Workbook.Worksheets.Count | Should beGreaterThan 2
# $excel.Workbook.Worksheets["Processes"].Dimension.rows | Should be 51 #50 data + 1 header $excel.Workbook.Worksheets["Processes"].Dimension.rows | Should be 21 #20 data + 1 header
} }
$pt = $PTws.PivotTables[0] $pt = $PTws.PivotTables[0]
it "Built the expected Pivot table " { it "Built the expected Pivot table " {
@@ -426,7 +465,7 @@ Describe ExportExcel {
$pt.DataFields[0].Field.Name | Should be "PM" $pt.DataFields[0].Field.Name | Should be "PM"
$PTws.Drawings.Count | Should be 0 $PTws.Drawings.Count | Should be 0
} }
#using the already open sheet add the pivot chart #test adding pivot chart using the already open sheet
$warnvar = $null $warnvar = $null
Export-Excel -ExcelPackage $Excel -WorkSheetname Processes -IncludePivotTable -PivotRows Company -PivotData PM -IncludePivotChart -ChartType PieExploded3D -ShowCategory -NoLegend -WarningAction SilentlyContinue -WarningVariable warnvar Export-Excel -ExcelPackage $Excel -WorkSheetname Processes -IncludePivotTable -PivotRows Company -PivotData PM -IncludePivotChart -ChartType PieExploded3D -ShowCategory -NoLegend -WarningAction SilentlyContinue -WarningVariable warnvar
$Excel = Open-ExcelPackage $path $Excel = Open-ExcelPackage $path
@@ -439,15 +478,16 @@ Describe ExportExcel {
it "Generated a message on re-processing the Pivot table " { 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 $warnVar = $null
Get-Process | Select-Object -Last 50 -Property Name, cpu, pm, handles, company | Export-Excel $path -WorkSheetname Processes -Append -IncludePivotTable -PivotRows Company -PivotData PM -IncludePivotChart -ChartType PieExploded3D -WarningAction SilentlyContinue -WarningVariable warnvar Get-Process | Select-Object -Last 20 -Property Name, cpu, pm, handles, company | Export-Excel $path -WorkSheetname Processes -Append -IncludePivotTable -PivotRows Company -PivotData PM -IncludePivotChart -ChartType PieExploded3D -WarningAction SilentlyContinue -WarningVariable warnvar
$Excel = Open-ExcelPackage $path $Excel = Open-ExcelPackage $path
$pt = $Excel.Workbook.Worksheets["ProcessesPivotTable"].PivotTables[0] $pt = $Excel.Workbook.Worksheets["ProcessesPivotTable"].PivotTables[0]
it "Appended to the Worksheet and Extended the Pivot table " { it "Appended to the Worksheet and Extended the Pivot table " {
$Excel.Workbook.Worksheets.Count | Should be $wCount $Excel.Workbook.Worksheets.Count | Should be $wCount
# $excel.Workbook.Worksheets["Processes"].Dimension.rows | Should be 101 #appended 50 rows to the previous total $excel.Workbook.Worksheets["Processes"].Dimension.rows | Should be 41 #appended 20 rows to the previous total
# $pt.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref | $pt.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref |
# Should be "A1:E101" Should be "A1:E41"
} }
it "Generated a message on extending the Pivot table " { it "Generated a message on extending the Pivot table " {
$warnVar | Should not beNullOrEmpty $warnVar | Should not beNullOrEmpty
@@ -456,7 +496,7 @@ Describe ExportExcel {
Context " # Add-Worksheet inserted sheets, moved them correctly, and copied a sheet" { Context " # Add-Worksheet inserted sheets, moved them correctly, and copied a sheet" {
$path = "$env:TEMP\Test.xlsx" $path = "$env:TEMP\Test.xlsx"
#Test the -CopySource and -Movexxxx parameters for Add-WorkSheet
$Excel = Open-ExcelPackage $path $Excel = Open-ExcelPackage $path
#At this point Sheets Should be in the order Sheet1, Processes, ProcessesPivotTable #At this point Sheets Should be in the order Sheet1, Processes, ProcessesPivotTable
$null = Add-WorkSheet -ExcelPackage $Excel -WorkSheetname "Processes" -MoveToEnd # order now Sheet1, ProcessesPivotTable, Processes $null = Add-WorkSheet -ExcelPackage $Excel -WorkSheetname "Processes" -MoveToEnd # order now Sheet1, ProcessesPivotTable, Processes
@@ -489,11 +529,12 @@ Describe ExportExcel {
Context " # Create and append with Start row and Start Column, inc ranges and Pivot table. " { Context " # Create and append with Start row and Start Column, inc ranges and Pivot table. " {
$path = "$env:TEMP\Test.xlsx" $path = "$env:TEMP\Test.xlsx"
remove-item -Path $path -ErrorAction SilentlyContinue
#Catch warning #Catch warning
$warnVar = $null $warnVar = $null
#Test Append with no existing sheet. Test adding a named pivot table from a command line parameter #Test -Append with no existing sheet. Test adding a named pivot table from command line parameters and extending ranges when they're not specified explictly
Get-Process | Select-Object -first 10 -Property Name, cpu, pm, handles, company | Export-Excel -StartRow 3 -StartColumn 3 -AutoFilter -AutoNameRange -BoldTopRow -IncludePivotTable -PivotRows Company -PivotData PM -PivotTableName 'PTOffset' -Path $path -WorkSheetname withOffset -Append -PivotFilter Name -NoTotalsInPivot Get-Process | Select-Object -first 10 -Property Name, cpu, pm, handles, company | Export-Excel -StartRow 3 -StartColumn 3 -BoldTopRow -IncludePivotTable -PivotRows Company -PivotData PM -PivotTableName 'PTOffset' -Path $path -WorkSheetname withOffset -Append -PivotFilter Name -NoTotalsInPivot -RangeName procs -AutoFilter -AutoNameRange
Get-Process | Select-Object -last 10 -Property Name, cpu, pm, handles, company | Export-Excel -StartRow 3 -StartColumn 3 -AutoFilter -AutoNameRange -BoldTopRow -IncludePivotTable -PivotRows Company -PivotData PM -PivotTableName 'PTOffset' -Path $path -WorkSheetname withOffset -Append -WarningAction SilentlyContinue -WarningVariable warnvar Get-Process | Select-Object -last 10 -Property Name, cpu, pm, handles, company | Export-Excel -StartRow 3 -StartColumn 3 -BoldTopRow -IncludePivotTable -PivotRows Company -PivotData PM -PivotTableName 'PTOffset' -Path $path -WorkSheetname withOffset -Append -WarningAction SilentlyContinue -WarningVariable warnvar
$Excel = Open-ExcelPackage $path $Excel = Open-ExcelPackage $path
$dataWs = $Excel.Workbook.Worksheets["withOffset"] $dataWs = $Excel.Workbook.Worksheets["withOffset"]
$pt = $Excel.Workbook.Worksheets["PTOffset"].PivotTables[0] $pt = $Excel.Workbook.Worksheets["PTOffset"].PivotTables[0]
@@ -505,21 +546,71 @@ Describe ExportExcel {
$dataWs.Dimension.End.Row | Should be 23 $dataWs.Dimension.End.Row | Should be 23
$dataWs.names[0].end.row | Should be 23 $dataWs.names[0].end.row | Should be 23
$dataWs.names[0].name | Should be 'Name' $dataWs.names[0].name | Should be 'Name'
$dataWs.names.Count | Should be 6 $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[$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
}
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
}
it "Created and extended the pivot table " {
$pt.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref | $pt.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref |
Should be "C3:G23" 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
} }
it "Generated a message on extending the Pivot table " { it "Generated a message on extending the Pivot table " {
$warnVar | Should not beNullOrEmpty $warnVar | Should not beNullOrEmpty
} }
} }
Context " # Create and append explicit and auto table and range extension" {
$path = "$env:TEMP\Test.xlsx"
#Test -Append automatically extends a table, even when it is not specified in the append command
Get-Process | Select-Object -first 10 -Property Name, cpu, pm, handles, company | Export-Excel -Path $path -TableName ProcTab -AutoNameRange -WorkSheetname NoOffset -ClearSheet
Get-Process | Select-Object -last 10 -Property Name, cpu, pm, handles, company | Export-Excel -Path $path -AutoNameRange -WorkSheetname NoOffset -Append
$Excel = Open-ExcelPackage $path
$dataWs = $Excel.Workbook.Worksheets["NoOffset"]
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
}
#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
Get-Process | Select-Object -last 10 -Property Name, cpu, pm, handles, company | Export-Excel -ExcelPackage $excel -RangeName procs -AutoFilter -WorkSheetname NoOffset -Append
$Excel = Open-ExcelPackage $path
$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
}
}
Context "#Example 11 # Create and append with title, inc ranges and Pivot table" { Context "#Example 11 # Create and append with title, inc ranges and Pivot table" {
$path = "$env:TEMP\Test.xlsx" $path = "$env:TEMP\Test.xlsx"
#Test New-PivotTableDefinition builds definition using -Pivotfilter and -PivotTotals options.
$ptDef = [ordered]@{} $ptDef = [ordered]@{}
$ptDef += New-PivotTableDefinition -PivotTableName "PT1" -SourceWorkSheet 'Sheet1' -PivotRows "Status" -PivotData @{'Status' = 'Count'} -PivotFilter "StartType" -IncludePivotChart -ChartType BarClustered3D -ChartTitle "Services by status" -ChartHeight 512 -ChartWidth 768 -ChartRow 10 -ChartColumn 0 -NoLegend $ptDef += New-PivotTableDefinition -PivotTableName "PT1" -SourceWorkSheet 'Sheet1' -PivotRows "Status" -PivotData @{'Status' = 'Count'} -PivotTotals Columns -PivotFilter "StartType" -IncludePivotChart -ChartType BarClustered3D -ChartTitle "Services by status" -ChartHeight 512 -ChartWidth 768 -ChartRow 10 -ChartColumn 0 -NoLegend -PivotColumns CanPauseAndContinue
$ptDef += New-PivotTableDefinition -PivotTableName "PT2" -SourceWorkSheet 'Sheet2' -PivotRows "Company" -PivotData @{'Company' = 'Count'} -IncludePivotChart -ChartType PieExploded3D -ShowPercent -WarningAction SilentlyContinue $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 " { it "Built a pivot definition using New-PivotTableDefinition " {
$ptDef.PT1.SourceWorkSheet | Should be 'Sheet1' $ptDef.PT1.SourceWorkSheet | Should be 'Sheet1'
@@ -528,11 +619,13 @@ Describe ExportExcel {
$ptDef.PT1.PivotFilter | Should be 'StartType' $ptDef.PT1.PivotFilter | Should be 'StartType'
$ptDef.PT1.IncludePivotChart | Should be $true $ptDef.PT1.IncludePivotChart | Should be $true
$ptDef.PT1.ChartType.tostring() | Should be 'BarClustered3D' $ptDef.PT1.ChartType.tostring() | Should be 'BarClustered3D'
$ptDef.PT1.PivotTotals | Should be 'Columns'
} }
Remove-Item -Path $path Remove-Item -Path $path
#Catch warning #Catch warning
$warnvar = $null $warnvar = $null
Get-Service | Select-Object -Property Status, Name, DisplayName, StartType | Export-Excel -Path $path -AutoSize -TableName "All Services" -TableStyle Medium1 -WarningAction SilentlyContinue -WarningVariable warnvar #Test create two data pages; as part of adding the second give both their own pivot table, test -autosize switch
Get-Service | Select-Object -Property Status, Name, DisplayName, StartType, CanPauseAndContinue | Export-Excel -Path $path -AutoSize -TableName "All Services" -TableStyle Medium1 -WarningAction SilentlyContinue -WarningVariable warnvar
Get-Process | Select-Object -Property Name, Company, Handles, CPU, VM | Export-Excel -Path $path -AutoSize -WorkSheetname 'sheet2' -TableName "Processes" -TableStyle Light1 -Title "Processes" -TitleFillPattern Solid -TitleBackgroundColor AliceBlue -TitleBold -TitleSize 22 -PivotTableDefinition $ptDef Get-Process | Select-Object -Property Name, Company, Handles, CPU, VM | Export-Excel -Path $path -AutoSize -WorkSheetname 'sheet2' -TableName "Processes" -TableStyle Light1 -Title "Processes" -TitleFillPattern Solid -TitleBackgroundColor AliceBlue -TitleBold -TitleSize 22 -PivotTableDefinition $ptDef
$Excel = Open-ExcelPackage $path $Excel = Open-ExcelPackage $path
$ws1 = $Excel.Workbook.Worksheets["Sheet1"] $ws1 = $Excel.Workbook.Worksheets["Sheet1"]
@@ -567,17 +660,21 @@ Describe ExportExcel {
$PT2 = $ptsheet2.PivotTables[0] $PT2 = $ptsheet2.PivotTables[0]
$PC1 = $ptsheet1.Drawings[0] $PC1 = $ptsheet1.Drawings[0]
$PC2 = $ptsheet2.Drawings[0] $PC2 = $ptsheet2.Drawings[0]
it "Created the correct pivot tables and charts from the definitions. " { it "Created the pivot tables linked to the right data. " {
$PT1.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref | $PT1.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref |
Should be ("A1:" + $ws1.Dimension.End.Address) Should be ("A1:" + $ws1.Dimension.End.Address)
$PT2.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref | $PT2.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref |
Should be ("A2:" + $ws2.Dimension.End.Address) #Title in row 1 Should be ("A2:" + $ws2.Dimension.End.Address) #Title in row 1
}
it "Set the other pivot tables and chart options from the definitions. " {
$pt1.PageFields[0].Name | Should be 'StartType' $pt1.PageFields[0].Name | Should be 'StartType'
$pt1.RowFields[0].Name | Should be 'Status' $pt1.RowFields[0].Name | Should be 'Status'
$pt1.DataFields[0].Field.name | Should be 'Status' $pt1.DataFields[0].Field.name | Should be 'Status'
$pt1.DataFields[0].Function | Should be 'Count' $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.ChartType | Should be 'BarClustered3D'
$pc1.From.Column | Should be 0 #chart 1 at 0,10 chart 2 at 4,0 (default) $pc1.From.Column | Should be 0 #chart 1 at 0,10 chart 2 at 4,0 (default)
$pc2.From.Column | Should be 4 $pc2.From.Column | Should be 4
@@ -593,6 +690,7 @@ Describe ExportExcel {
Context "#Example 13 # Formatting and another way to do a pivot. " { Context "#Example 13 # Formatting and another way to do a pivot. " {
$path = "$env:TEMP\Test.xlsx" $path = "$env:TEMP\Test.xlsx"
Remove-Item $path Remove-Item $path
#Test freezing top row/first column, adding formats and a pivot table - from Add-Pivot table not a specification variable - after the export
$excel = Get-Process | Select-Object -Property Name, Company, Handles, CPU, PM, NPM, WS | Export-Excel -Path $path -ClearSheet -WorkSheetname "Processes" -FreezeTopRowFirstColumn -PassThru $excel = Get-Process | Select-Object -Property Name, Company, Handles, CPU, PM, NPM, WS | Export-Excel -Path $path -ClearSheet -WorkSheetname "Processes" -FreezeTopRowFirstColumn -PassThru
$sheet = $excel.Workbook.Worksheets["Processes"] $sheet = $excel.Workbook.Worksheets["Processes"]
$sheet.Column(1) | Set-Format -Bold -AutoFit $sheet.Column(1) | Set-Format -Bold -AutoFit
@@ -605,7 +703,7 @@ Describe ExportExcel {
$rule = Add-ConditionalFormatting -passthru -Address $sheet.cells["C:C"] -RuleType TopPercent -ConditionValue 20 -Bold -StrikeThru $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 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 } 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 Close-ExcelPackage $excel
$excel = Open-ExcelPackage $path $excel = Open-ExcelPackage $path
@@ -659,14 +757,15 @@ Describe ExportExcel {
Context " # Chart from MultiSeries.ps1 in the Examples\charts Directory" { Context " # Chart from MultiSeries.ps1 in the Examples\charts Directory" {
$path = "$env:TEMP\Test.xlsx" $path = "$env:TEMP\Test.xlsx"
Remove-Item -Path $path -ErrorAction SilentlyContinue Remove-Item -Path $path -ErrorAction SilentlyContinue
$data = invoke-sum (Get-Process) Company Handles, PM, VirtualMemorySize #Test Invoke-Sum
$data = Invoke-Sum (Get-Process) Company Handles, PM, VirtualMemorySize
it "used Invoke-Sum to create a data set " { it "used Invoke-Sum to create a data set " {
$data | Should not beNullOrEmpty $data | Should not beNullOrEmpty
$data.count | Should beGreaterThan 1 $data.count | Should beGreaterThan 1
$data[1].Name | Should not beNullOrEmpty $data[1].Name | Should not beNullOrEmpty
$data[1].Handles | Should not beNullOrEmpty $data[1].Handles | Should not beNullOrEmpty
$data[1].PM | Should not beNullOrEmpty $data[1].PM | Should not beNullOrEmpty
$data[1].VirtualMemorySize | 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' $c = New-ExcelChartDefinition -Title Stats -ChartType LineMarkersStacked -XRange "Processes[Name]" -YRange "Processes[PM]", "Processes[VirtualMemorySize]" -SeriesHeader 'PM', 'VMSize'
@@ -684,6 +783,7 @@ Describe ExportExcel {
$c.ShowCategory | Should not be $true $c.ShowCategory | Should not be $true
$c.ShowPercent | 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 $data | Export-Excel $path -AutoSize -TableName Processes -ExcelChartDefinition $c
$excel = Open-ExcelPackage -Path $path $excel = Open-ExcelPackage -Path $path
$drawings = $excel.Workbook.Worksheets[1].drawings $drawings = $excel.Workbook.Worksheets[1].drawings
@@ -702,11 +802,16 @@ Describe ExportExcel {
Context " # variation of plot.ps1 from Examples Directory using Add chart outside ExportExcel" { Context " # variation of plot.ps1 from Examples Directory using Add chart outside ExportExcel" {
$path = "$env:TEMP\Test.xlsx" $path = "$env:TEMP\Test.xlsx"
#Test inserting a fomual
$excel = 0..360 | ForEach-Object {[pscustomobject][ordered]@{x = $_; Sinx = "=Sin(Radians(x)) "}} | Export-Excel -AutoNameRange -Path $path -WorkSheetname SinX -ClearSheet -FreezeFirstColumn -PassThru $excel = 0..360 | ForEach-Object {[pscustomobject][ordered]@{x = $_; Sinx = "=Sin(Radians(x)) "}} | Export-Excel -AutoNameRange -Path $path -WorkSheetname SinX -ClearSheet -FreezeFirstColumn -PassThru
#Test-Add Excel Chart to existing data. Test add Conditional formatting with a formula
Add-ExcelChart -Worksheet $excel.Workbook.Worksheets["Sinx"] -ChartType line -XRange "X" -YRange "Sinx" -SeriesHeader "Sin(x)" -Title "Graph of Sine X" -TitleBold -TitleSize 14 ` Add-ExcelChart -Worksheet $excel.Workbook.Worksheets["Sinx"] -ChartType line -XRange "X" -YRange "Sinx" -SeriesHeader "Sin(x)" -Title "Graph of Sine X" -TitleBold -TitleSize 14 `
-Column 2 -ColumnOffSetPixels 35 -Width 800 -XAxisTitleText "Degrees" -XAxisTitleBold -XAxisTitleSize 12 -XMajorUnit 30 -XMinorUnit 10 -XMinValue 0 -XMaxValue 361 -XAxisNumberformat "000" -XAxisPosition Bottom ` -Column 2 -ColumnOffSetPixels 35 -Width 800 -XAxisTitleText "Degrees" -XAxisTitleBold -XAxisTitleSize 12 -XMajorUnit 30 -XMinorUnit 10 -XMinValue 0 -XMaxValue 361 -XAxisNumberformat "000" `
-YMinValue -1.25 -YMaxValue 1.25 -YMajorUnit 0.25 -YAxisNumberformat "0.00" -YAxisTitleText "Sine" -YAxisTitleBold -YAxisTitleSize 12 -YAxisPosition Left -LegendPostion Bottom -LegendSize 8 -legendBold -YMinValue -1.25 -YMaxValue 1.25 -YMajorUnit 0.25 -YAxisNumberformat "0.00" -YAxisTitleText "Sine" -YAxisTitleBold -YAxisTitleSize 12 `
$d = $excel.Workbook.Worksheets["Sinx"].Drawings[0] -LegendSize 8 -legendBold -LegendPostion Bottom
Add-ConditionalFormatting -WorkSheet $excel.Workbook.Worksheets["Sinx"] -Range "B2:B362" -RuleType LessThan -ConditionValue "=B1" -ForeGroundColor Red
$ws = $Excel.Workbook.Worksheets["Sinx"]
$d = $ws.Drawings[0]
It "Controled the axes and title and legend of the chart " { It "Controled the axes and title and legend of the chart " {
$d.XAxis.MaxValue | Should be 361 $d.XAxis.MaxValue | Should be 361
$d.XAxis.MajorUnit | Should be 30 $d.XAxis.MajorUnit | Should be 30
@@ -731,6 +836,9 @@ Describe ExportExcel {
$d.ChartType.tostring() | Should be "line" $d.ChartType.tostring() | Should be "line"
$d.From.Column | Should be 2 $d.From.Column | Should be 2
} }
It "Appplied conditional formatting to the data " {
$ws.ConditionalFormatting[0].Formula | Should be "B1"
}
Close-ExcelPackage -ExcelPackage $excel -nosave Close-ExcelPackage -ExcelPackage $excel -nosave
} }
@@ -753,7 +861,7 @@ Describe ExportExcel {
$ct.ConditionalType | Should be "ContainsText" $ct.ConditionalType | Should be "ContainsText"
$ct.Text | Should be "Microsoft" $ct.Text | Should be "Microsoft"
} }
#Test -ConditionalFormat & -ConditionalText
Export-Excel -Path $path -ConditionalFormat $cf -ConditionalText $ct Export-Excel -Path $path -ConditionalFormat $cf -ConditionalText $ct
$excel = Open-ExcelPackage -Path $path $excel = Open-ExcelPackage -Path $path
$rows = $range -replace "^.*?(\d+)$", '$1' $rows = $range -replace "^.*?(\d+)$", '$1'
@@ -774,6 +882,7 @@ Describe ExportExcel {
Context " # Awkward multiple tables" { Context " # Awkward multiple tables" {
$path = "$Env:TEMP\test.xlsx" $path = "$Env:TEMP\test.xlsx"
#Test creating 3 on overlapping tables on the same page. Create rightmost the left most then middle.
remove-item -Path $path -ErrorAction SilentlyContinue remove-item -Path $path -ErrorAction SilentlyContinue
$r = Get-ChildItem -path C:\WINDOWS\system32 -File $r = Get-ChildItem -path C:\WINDOWS\system32 -File
@@ -798,7 +907,7 @@ Describe ExportExcel {
$ws.Tables["FileSize"].StyleName | should be "TableStyleMedium2" $ws.Tables["FileSize"].StyleName | should be "TableStyleMedium2"
} }
it "Created the ExtSize table in the right place with the right size " { it "Created the ExtSize table in the right place with the right size " {
$ws.Tables["ExtSize"].Address.Address | should be "A2:B14" #tile, then 12 rows x 2 columns of data $ws.Tables["ExtSize"].Address.Address | should be "A2:B14" #tile, then 12 rows x 2 columns of data
} }
it "Created the ExtCount table in the right place with the right size " { 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

View File

@@ -0,0 +1,10 @@
Describe "ImportExcel File List" {
It "All files should exist" {
$fileList = Get-Content "$PSScriptRoot\..\filelist.txt"
foreach ($file in $fileList) {
$targetFile = "$PSScriptRoot\..\$file"
Test-Path $targetFile | Should Be $true
}
}
}

View File

@@ -31,39 +31,58 @@ Describe "Join Worksheet" {
$data3 | Export-Excel -Path $path -WorkSheetname Banbury $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 $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 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"] $ws = $excel.Workbook.Worksheets["Total"]
$pt = $excel.Workbook.Worksheets["Summary"].pivottables[0] $pt = $excel.Workbook.Worksheets["Summary"].pivottables[0]
$pc = $excel.Workbook.Worksheets["Summary"].Drawings[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 " { it "Created sheet of the right size with a title and a table " {
$ws.Dimension.Address | Should be "A1:F16" $ws.Dimension.Address | Should be "A1:F16"
$ws.Tables[0].Address.Address | Should be "A2:F16" $ws.Tables[0].Address.Address | Should be "A2:F16"
$ws.cells["A1"].Value | Should be "Store Sales Summary" $ws.cells["A1"].Value | Should be "Store Sales Summary"
$ws.cells["A1"].Style.Font.Size | Should be 14 $ws.cells["A1"].Style.Font.Size | Should be 14
$ws.Tables[0].StyleName | Should be "TableStyleLight1" $ws.Tables[0].StyleName | Should be "TableStyleLight1"
$ws.cells["A2:F2"].Style.Font.Bold | Should be $True $ws.cells["A2:F2"].Style.Font.Bold | Should be $True
} }
it "Added a from column with the right heading " { it "Added a from column with the right heading " {
$ws.cells["F2" ].Value | Should be "Store" $ws.cells["F2" ].Value | Should be "Store"
$ws.cells["F3" ].Value | Should be "Oxford" $ws.cells["F3" ].Value | Should be "Oxford"
$ws.cells["F8" ].Value | Should be "Abingdon" $ws.cells["F8" ].Value | Should be "Abingdon"
$ws.cells["F13"].Value | Should be "Banbury" $ws.cells["F13"].Value | Should be "Banbury"
} }
it "Filled in the data " { it "Filled in the data " {
$ws.cells["C3" ].Value | Should be $data1[0].quantity $ws.cells["C3" ].Value | Should be $data1[0].quantity
$ws.cells["C8" ].Value | Should be $data2[0].quantity $ws.cells["C8" ].Value | Should be $data2[0].quantity
$ws.cells["C13"].Value | Should be $data3[0].quantity $ws.cells["C13"].Value | Should be $data3[0].quantity
} }
it "Created the pivot table " { it "Created the pivot table " {
$pt | Should not beNullOrEmpty $pt | Should not beNullOrEmpty
$pt.StyleName | Should be "PivotStyleMedium9" $pt.StyleName | Should be "PivotStyleMedium9"
$pt.RowFields[0].Name | Should be "Store" $pt.RowFields[0].Name | Should be "Store"
$pt.ColumnFields[0].name | Should be "Product" $pt.ColumnFields[0].name | Should be "Product"
$pt.DataFields[0].name | Should be "Sum of Total" $pt.DataFields[0].name | Should be "Sum of Total"
$pc.ChartType | Should be "ColumnStacked" $pc.ChartType | Should be "ColumnStacked"
$pc.Title.text | Should be "Sales Breakdown" $pc.Title.text | Should be "Sales Breakdown"
} }
} }
$path = "$env:TEMP\Test.xlsx" $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 Join-Worksheet -Path $path -HideSource -WorkSheetName Summary -NoHeader -LabelBlocks -AutoSize -Title "Summary" -TitleBold -TitleSize 22
$excel = Open-ExcelPackage -Path $path $excel = Open-ExcelPackage -Path $path
$ws = $excel.Workbook.Worksheets["Summary"] $ws = $excel.Workbook.Worksheets["Summary"]
Context "3 Unlinked blocks" { Context "Bringing 3 Unlinked blocks onto one page" {
it "Hid the source worksheets " { it "Hid the source worksheets " {
$excel.Workbook.Worksheets[1].Hidden.tostring() | should be "Hidden" $excel.Workbook.Worksheets[1].Hidden.tostring() | Should be "Hidden"
$excel.Workbook.Worksheets[2].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 " { it "Created the Summary sheet with title, and block labels, and copied the correct data " {
$ws.Cells["A1"].Value | should be "Summary" $ws.Cells["A1"].Value | Should be "Summary"
$ws.Cells["A2"].Value | should be $excel.Workbook.Worksheets[1].name $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["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["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["B4"].Value | Should be $excel.Workbook.Worksheets[1].Cells["B2"].value
$nextRow = $excel.Workbook.Worksheets[1].Dimension.Rows + 3 $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 ++ $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 ++ $nextRow ++
$ws.Cells["A$NextRow"].Value | should be $excel.Workbook.Worksheets[2].Cells["A2"].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 $ws.Cells["B$NextRow"].Value | Should be $excel.Workbook.Worksheets[2].Cells["B2"].value
} }
} }
} }

View File

@@ -0,0 +1,24 @@
Describe "Password Support" {
Context "Password protected sheet" {
BeforeAll {
$password = "YouMustRememberThis"
$path = "$env:TEMP\Test.xlsx"
Remove-Item $path -ErrorAction SilentlyContinue
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
}
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
}
it "Kept the password on the file when it was saved " {
{Import-Excel $Path } | should throw
}
it "Could read the file when the password was included " {
(import-excel $path -Password $password).count | should be 20
}
}
}

View File

@@ -1,6 +1,5 @@

$path = "$Env:TEMP\test.xlsx" $path = "$Env:TEMP\test.xlsx"
Remove-Item -Path $path -ErrorAction SilentlyContinue
$data = ConvertFrom-Csv -InputObject @" $data = ConvertFrom-Csv -InputObject @"
ID,Product,Quantity,Price ID,Product,Quantity,Price
@@ -11,13 +10,134 @@ ID,Product,Quantity,Price
12011,Crowbar,7,23.48 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 " {
$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 "@"
}
}
Context "Apply-NumberFormat" {
BeforeAll {
Remove-Item -Path $path -ErrorAction SilentlyContinue
$n = [datetime]::Now.ToOADate()
$excel = 1..32 | ForEach-Object {$n} | Export-Excel -Path $path -show -WorksheetName s2 -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[ 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" { Describe "Set-Column, Set-Row and Set Format" {
BeforeAll { BeforeAll {
Remove-Item -Path $path -ErrorAction SilentlyContinue
$excel = $data| Export-Excel -Path $path -AutoNameRange -PassThru $excel = $data| Export-Excel -Path $path -AutoNameRange -PassThru
$ws = $excel.Workbook.Worksheets["Sheet1"] $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 $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 $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["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 "E3" -Bold:$false -FontShift Superscript -HorizontalAlignment Left
@@ -27,63 +147,141 @@ Describe "Set-Column, Set-Row and Set Format" {
Set-Format -Address $ws.Column(2) -AutoFit Set-Format -Address $ws.Column(2) -AutoFit
Set-Format -Address $ws.Cells["E:E"] -AutoFit Set-Format -Address $ws.Cells["E:E"] -AutoFit
Set-Format -Address $ws.row(5) -Height 0 Set-Format -Address $ws.row(5) -Height 0
Close-ExcelPackage $excel $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 -Calculate
$excel = Open-ExcelPackage $path $excel = Open-ExcelPackage $path
$ws = $excel.Workbook.Worksheets["Sheet1"] $ws = $excel.Workbook.Worksheets["Sheet1"]
} }
Context "Rows and Columns" { Context "Set-Row and Set-Column" {
it "Set a row and a column to have zero width/height " { it "Set a row and a column to have zero width/height " {
$r | should not beNullorEmpty $r | Should not beNullorEmpty
# $c | should not beNullorEmpty ## can't see why but this test breaks in appveyor # $c | Should not beNullorEmpty ## can't see why but this test breaks in appveyor
$ws.Column(1).width | should be 0 $ws.Column(1).width | Should be 0
$ws.Row(5).height | should be 0 $ws.Row(5).height | Should be 0
} }
it "Set a column formula, with numberformat, color, bold face and alignment" { it "Set a column formula, with numberformat, color, bold face and alignment " {
$ws.cells["e2"].Formula | Should be "=Quantity*Price" $ws.cells["e2"].Formula | Should be "Quantity*Price"
$ws.cells["e2"].Style.Font.Color.rgb | Should be "FF0000FF" $ws.cells["e2"].Value | Should be 147.63
$ws.cells["e2"].Style.Font.Bold | Should be $true $ws.cells["e2"].Style.Font.Color.rgb | Should be "FF0000FF"
$ws.cells["e2"].Style.Font.VerticalAlign | Should be "None" $ws.cells["e2"].Style.Font.Bold | Should be $true
$ws.cells["e2"].Style.Numberformat.format | Should be "£#,###.00" $ws.cells["e2"].Style.Font.VerticalAlign | Should be "None"
$ws.cells["e2"].Style.HorizontalAlignment | Should be "Right" $ws.cells["e2"].Style.Numberformat.format | Should be "£#,###.00"
$ws.cells["e2"].Style.HorizontalAlignment | Should be "Right"
} }
} }
Context "Other formatting" { Context "Other formatting" {
it "Set a row formula with border font size and underline " { it "Trapped an attempt to hide a range instead of a Row/Column " {
$ws.cells["b7"].style.Border.Top.Style | Should be "None" $BadHideWarnvar | Should not beNullOrEmpty
$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 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
}
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 " { Context "Set-Format value setting " {
$ws.cells["e3"].Style.HorizontalAlignment | Should be "Left" it "Inserted a formula " {
$ws.cells["e3"].Style.Font.VerticalAlign | Should be "Superscript" $ws.Cells["D7"].Formula | Should be "E7/C7"
$ws.cells["b3"].style.Border.Left.Color.Rgb | Should be "FFFF0000" }
$ws.cells["b3"].style.Border.Left.Style | Should be "Thick" it "Inserted a value " {
$ws.cells["b3"].style.Border.Right.Style | Should be "Thick" $ws.Cells["B7"].Value | Should be "Total"
$ws.cells["b3"].style.Border.Top.Style | Should be "Thick" }
$ws.cells["b3"].style.Border.Bottom.Style | Should be "Thick" it "Inserted a date with localized date-time format " {
$ws.cells["b3"].style.Font.Strike | Should be $true $ws.Cells["B8"].Style.Numberformat.NumFmtID | Should be 22
$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 Context "Set-Column Value Setting" {
$ws.cells["e7"].Style.Fill.BackgroundColor.Rgb| Should be "FFF0F8FF" BeforeAll {
$ws.cells["e7"].Style.Fill.PatternColor.Rgb | Should be "FFFF0000" Remove-Item -Path $path -ErrorAction SilentlyContinue
$ws.cells["e7"].Style.Fill.PatternType | Should be "DarkTrellis"
$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 -Calculate
$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
} }
} }
} }
Describe "Conditional Formatting" {
BeforeAll {
Remove-Item $path
$data = Get-Process | where company | select company,name,pm,handles,*mem*
$cfmt = New-ConditionalFormattingIconSet -Range "c:c" -ConditionalFormat ThreeIconSet -IconType Arrows
$data | Export-Excel -path $Path -AutoSize -ConditionalFormat $cfmt
$excel = Open-ExcelPackage -Path $path
$ws = $excel.Workbook.Worksheets[1]
}
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"
}
}
}

Binary file not shown.

View File

@@ -93,29 +93,29 @@ Function Compare-WorkSheet {
try { $oneFile = ((Resolve-Path -Path $Referencefile -ErrorAction Stop).path -eq (Resolve-Path -Path $Differencefile -ErrorAction Stop).path)} try { $oneFile = ((Resolve-Path -Path $Referencefile -ErrorAction Stop).path -eq (Resolve-Path -Path $Differencefile -ErrorAction Stop).path)}
Catch { Write-Warning -Message "Could not Resolve the filenames." ; return } Catch { Write-Warning -Message "Could not Resolve the filenames." ; return }
#If we have one file , we mush have two different worksheet names. If we have two files we can a single string or two strings. #If we have one file , we must have two different worksheet names. If we have two files we can have a single string or two strings.
if ($onefile -and ( ($WorkSheetName.count -ne 2) -or $WorkSheetName[0] -eq $WorkSheetName[1] ) ) { if ($onefile -and ( ($WorkSheetName.count -ne 2) -or $WorkSheetName[0] -eq $WorkSheetName[1] ) ) {
Write-Warning -Message "If both the Reference and difference file are the same then worksheet name must provide 2 different names" Write-Warning -Message "If both the Reference and difference file are the same then worksheet name must provide 2 different names"
return return
} }
if ($WorkSheetName.count -eq 2) {$worksheet1 = $WorkSheetName[0] ; $WorkSheet2 = $WorkSheetName[1]} if ($WorkSheetName.count -eq 2) {$worksheet1 = $WorkSheetName[0] ; $workSheet2 = $WorkSheetName[1]}
elseif ($WorkSheetName -is [string]) {$worksheet1 = $WorkSheet2 = $WorkSheetName} elseif ($WorkSheetName -is [string]) {$worksheet1 = $workSheet2 = $WorkSheetName}
else {Write-Warning -Message "You must provide either a single worksheet name or two names." ; return } else {Write-Warning -Message "You must provide either a single worksheet name or two names." ; return }
$params= @{ ErrorAction = [System.Management.Automation.ActionPreference]::Stop } $params= @{ ErrorAction = [System.Management.Automation.ActionPreference]::Stop }
foreach ($p in @("HeaderName","NoHeader","StartRow")) {if ($PSBoundParameters[$p]) {$params[$p] = $PSBoundParameters[$p]}} foreach ($p in @("HeaderName","NoHeader","StartRow")) {if ($PSBoundParameters[$p]) {$params[$p] = $PSBoundParameters[$p]}}
try { try {
$Sheet1 = Import-Excel -Path $Referencefile -WorksheetName $WorkSheet1 @params $sheet1 = Import-Excel -Path $Referencefile -WorksheetName $WorkSheet1 @params
$Sheet2 = Import-Excel -Path $Differencefile -WorksheetName $WorkSheet2 @Params $sheet2 = Import-Excel -Path $Differencefile -WorksheetName $WorkSheet2 @Params
} }
Catch {Write-Warning -Message "Could not read the worksheet from $Referencefile and/or $Differencefile." ; return } Catch {Write-Warning -Message "Could not read the worksheet from $Referencefile and/or $Differencefile." ; return }
#Get Column headings and create a hash table of Name to column letter. #Get Column headings and create a hash table of Name to column letter.
$headings = $Sheet1[-1].psobject.Properties.name # This preserves the sequence - using get-member would sort them alphabetically! $headings = $Sheet1[-1].psobject.Properties.name # This preserves the sequence - using get-member would sort them alphabetically!
$headings | ForEach-Object -Begin {$columns = @{} ; $i=65 } -Process {$Columns[$_] = [char]($i ++) } $headings | ForEach-Object -Begin {$columns = @{} ; $i= 1 } -Process {$Columns[$_] = [OfficeOpenXml.ExcelAddress]::GetAddress(1,($i ++)) -replace "\d","" }
#Make a list of property headings using the Property (default "*") and ExcludeProperty parameters #Make a list of property headings using the Property (default "*") and ExcludeProperty parameters
if ($Key -eq "Name" -and $NoHeader) {$key = "p1"} if ($Key -eq "Name" -and $NoHeader) {$Key = "p1"}
$propList = @() $propList = @()
foreach ($p in $Property) {$propList += ($headings.where({$_ -like $p}) )} foreach ($p in $Property) {$propList += ($headings.where({$_ -like $p}) )}
foreach ($p in $ExcludeProperty) {$propList = $propList.where({$_ -notlike $p}) } foreach ($p in $ExcludeProperty) {$propList = $propList.where({$_ -notlike $p}) }
@@ -124,12 +124,12 @@ Function Compare-WorkSheet {
if ($propList.Count -eq 0) {Write-Warning -Message "No Columns are selected with -Property = '$Property' and -excludeProperty = '$ExcludeProperty'." ; return} if ($propList.Count -eq 0) {Write-Warning -Message "No Columns are selected with -Property = '$Property' and -excludeProperty = '$ExcludeProperty'." ; return}
#Add RowNumber, Sheetname and file name to every row #Add RowNumber, Sheetname and file name to every row
$FirstDataRow = $startRow + 1 $firstDataRow = $startRow + 1
if ($Headername -or $NoHeader) {$FirstDataRow -- } if ($Headername -or $NoHeader) {$firstDataRow -- }
$i = $FirstDataRow ; foreach ($row in $Sheet1) {Add-Member -InputObject $row -MemberType NoteProperty -Name "_Row" -Value ($i ++) $i = $firstDataRow ; foreach ($row in $Sheet1) {Add-Member -InputObject $row -MemberType NoteProperty -Name "_Row" -Value ($i ++)
Add-Member -InputObject $row -MemberType NoteProperty -Name "_Sheet" -Value $worksheet1 Add-Member -InputObject $row -MemberType NoteProperty -Name "_Sheet" -Value $worksheet1
Add-Member -InputObject $row -MemberType NoteProperty -Name "_File" -Value $Referencefile} Add-Member -InputObject $row -MemberType NoteProperty -Name "_File" -Value $Referencefile}
$i = $FirstDataRow ; foreach ($row in $Sheet2) {Add-Member -InputObject $row -MemberType NoteProperty -Name "_Row" -Value ($i ++) $i = $firstDataRow ; foreach ($row in $Sheet2) {Add-Member -InputObject $row -MemberType NoteProperty -Name "_Row" -Value ($i ++)
Add-Member -InputObject $row -MemberType NoteProperty -Name "_Sheet" -Value $worksheet2 Add-Member -InputObject $row -MemberType NoteProperty -Name "_Sheet" -Value $worksheet2
Add-Member -InputObject $row -MemberType NoteProperty -Name "_File" -Value $Differencefile} Add-Member -InputObject $row -MemberType NoteProperty -Name "_File" -Value $Differencefile}
@@ -198,7 +198,7 @@ Function Compare-WorkSheet {
#if nothing was found write a message which wont be redirected #if nothing was found write a message which wont be redirected
if (-not $diff) {Write-Host "Comparison of $Referencefile::$worksheet1 and $Differencefile::$WorkSheet2 returned no results." } if (-not $diff) {Write-Host "Comparison of $Referencefile::$worksheet1 and $Differencefile::$WorkSheet2 returned no results." }
if ($show) { if ($Show) {
Start-Process -FilePath $Referencefile Start-Process -FilePath $Referencefile
if (-not $oneFile) { Start-Process -FilePath $Differencefile } if (-not $oneFile) { Start-Process -FilePath $Differencefile }
if ($GridView) { Write-Warning -Message "-GridView is ignored when -Show is specified" } if ($GridView) { Write-Warning -Message "-GridView is ignored when -Show is specified" }

40
filelist.txt Normal file
View File

@@ -0,0 +1,40 @@
*.dll
*.psd1
*.psm1
AddConditionalFormatting.ps1
Charting.ps1
ColorCompletion.ps1
Compare-Worksheet.ps1
ConvertExcelToImageFile.ps1
ConvertFromExcelData.ps1
ConvertFromExcelToSQLInsert.ps1
ConvertToExcelXlsx.ps1
Copy-ExcelWorkSheet.ps1
Export-Charts.ps1
Export-Excel.ps1
Export-ExcelSheet.ps1
Get-ExcelColumnName.ps1
Get-ExcelSheetInfo.ps1
Get-ExcelWorkbookInfo.ps1
Get-HtmlTable.ps1
Get-Range.ps1
Get-XYRange.ps1
Import-Html.ps1
InferData.ps1
Invoke-Sum.ps1
Join-Worksheet.ps1
Merge-Worksheet.ps1
New-ConditionalFormattingIconSet.ps1
New-ConditionalText.ps1
New-ExcelChart.ps1
New-PSItem.ps1
Open-ExcelPackage.ps1
Pivot.ps1
Plot.ps1
Send-SQLDataToExcel.ps1
Set-CellStyle.ps1
Set-Column.ps1
Set-Row.ps1
SetFormat.ps1
TrackingUtils.ps1
Update-FirstObjectProperties.ps1