Compare commits

..

18 Commits

Author SHA1 Message Date
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
18 changed files with 636 additions and 230 deletions

View File

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

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) }
elseif ($PSBoundParameters.ContainsKey("DataBarColor" ) ) {$rule = $WorkSheet.ConditionalFormatting.AddDatabar( $Range , $DataBarColor) }
else {$rule = ($WorkSheet.ConditionalFormatting)."Add$RuleType"($Range)} else {$rule = ($WorkSheet.ConditionalFormatting)."Add$RuleType"($Range)}
if ($reverse) {$rule.reverse = $true} if ($PSBoundParameters.ContainsKey("Reverse" ) ) {$rule.reverse = [boolean]$Reverse}
if ($ConditionValue -and $RuleType -match "Top|Botom") {$rule.Rank = $ConditionValue } #endregion
if ($ConditionValue -and $RuleType -match "StdDev") {$rule.StdDev = $ConditionValue } #region set the rule conditions
if ($ConditionValue -and $RuleType -match "Than|Equal|Expression") {$rule.Formula = $ConditionValue } if ($PSBoundParameters.ContainsKey("ConditionValue") -and
if ($ConditionValue -and $RuleType -match "Text|With") {$rule.Text = $ConditionValue } $RuleType -match "Top|Botom" ) {$rule.Rank = $ConditionValue }
if ($ConditionValue -and if ($PSBoundParameters.ContainsKey("ConditionValue") -and
$ConditionValue2 -and $RuleType -match "Between") { $RuleType -match "StdDev" ) {$rule.StdDev = $ConditionValue }
$rule.Formula = $ConditionValue if ($PSBoundParameters.ContainsKey("ConditionValue") -and
$RuleType -match "Than|Equal|Expression" ) {$rule.Formula = $ConditionValue }
if ($PSBoundParameters.ContainsKey("ConditionValue") -and
$RuleType -match "Text|With" ) {$rule.Text = $ConditionValue }
if ($PSBoundParameters.ContainsKey("ConditionValue") -and
$PSBoundParameters.ContainsKey("ConditionValue") -and
$RuleType -match "Between" ) {
$rule.Formula = $ConditionValue;
$rule.Formula2 = $ConditionValue2 $rule.Formula2 = $ConditionValue2
} }
#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 ($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} if ($Passthru) {$rule}
} }

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).
@@ -123,6 +123,8 @@
Enables the 'Filter' in Excel on the complete header row. So users can easily sort, filter and/or search the data in the selected column from within Excel. 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 +289,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 +318,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 +341,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 +352,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.
@@ -371,7 +373,7 @@
[Parameter(ValueFromPipeline = $true)] [Parameter(ValueFromPipeline = $true)]
$TargetData, $TargetData,
[Switch]$Show, [Switch]$Show,
[String]$WorkSheetname = 'Sheet1', [String]$WorksheetName = 'Sheet1',
[String]$Password, [String]$Password,
[switch]$ClearSheet, [switch]$ClearSheet,
[switch]$Append, [switch]$Append,
@@ -445,6 +447,8 @@
[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,
@@ -553,11 +557,14 @@
} }
Else { $pkg = Open-ExcelPackage -Path $Path -Create -KillExcel:$KillExcel} Else { $pkg = Open-ExcelPackage -Path $Path -Create -KillExcel:$KillExcel}
$params = @{WorkSheetname=$worksheetName} $params = @{WorksheetName=$WorksheetName}
if ($NoClobber) {Write-Warning -Message "-NoClobber parameter is no longer used" } if ($NoClobber) {Write-Warning -Message "-NoClobber parameter is no longer used" }
foreach ($p in @("ClearSheet", "MoveToStart", "MoveToEnd", "MoveBefore", "MoveAfter")) {if ($PSBoundParameters[$p]) {$params[$p] = $PSBoundParameters[$p]}} foreach ($p in @("ClearSheet", "MoveToStart", "MoveToEnd", "MoveBefore", "MoveAfter", "Activate")) {if ($PSBoundParameters[$p]) {$params[$p] = $PSBoundParameters[$p]}}
$ws = $pkg | Add-WorkSheet @params $ws = $pkg | Add-WorkSheet @params
if ($ws.Name -ne $WorksheetName) {
Write-Warning -Message "The Worksheet name has been changed from $WorksheetName to $($ws.Name), this may cause errors later."
$WorksheetName = $ws.Name
}
foreach ($format in $ConditionalFormat ) { 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 }
@@ -598,7 +605,8 @@
} }
else { $Row = $StartRow } else { $Row = $StartRow }
$ColumnIndex = $StartColumn $ColumnIndex = $StartColumn
$setNumformat = ($numberformat -ne $ws.Cells.Style.Numberformat.Format) $Numberformat = Expand-NumberFormat -NumberFormat $Numberformat
$setNumformat = ($Numberformat -ne $ws.Cells.Style.Numberformat.Format)
$firstTimeThru = $true $firstTimeThru = $true
$isDataTypeValueType = $false $isDataTypeValueType = $false
@@ -606,10 +614,10 @@
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': $_"
} }
} }
} }
@@ -627,7 +635,8 @@
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
@@ -659,8 +668,8 @@
foreach ($Name in $script:Header) { foreach ($Name in $script:Header) {
#region Add non header values #region Add non header values
Add-CellValue -TargetCell $ws.Cells[$Row, $ColumnIndex] -CellValue $TargetData.$Name try {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 #endregion
} }
@@ -668,7 +677,7 @@
} }
} }
Catch { Catch {
throw "Failed exporting data to worksheet '$WorkSheetname' to '$Path': $_" throw "Failed exporting data to worksheet '$WorksheetName' to '$Path': $_"
} }
} }
} }
@@ -719,7 +728,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 +741,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 +761,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,14 +769,15 @@
$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.NoTotalsInPivot = $true}
if ($params.Keys -notcontains "PivotDataToColumn" -and $PivotDataToColumn) {$params.PivotDataToColumn = $true} if ($params.Keys -notcontains "PivotDataToColumn" -and $PivotDataToColumn) {$params.PivotDataToColumn = $true}
@@ -780,7 +790,8 @@
"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 ($Activate) {$params.Activate = $true }
if ($PivotFilter) {$params.PivotFilter = $PivotFilter} if ($PivotFilter) {$params.PivotFilter = $PivotFilter}
if ($PivotRows) {$params.PivotRows = $PivotRows} if ($PivotRows) {$params.PivotRows = $PivotRows}
if ($PivotColumns) {$Params.PivotColumns = $PivotColumns} if ($PivotColumns) {$Params.PivotColumns = $PivotColumns}
@@ -824,7 +835,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 +848,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 +877,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'
} }
@@ -911,7 +922,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 +931,7 @@
$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 ($Password) { if ($Password) {
@@ -929,7 +940,7 @@
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 }
@@ -977,7 +988,7 @@ function New-PivotTableDefinition {
$pt = New-PivotTableDefinition -PivotTableName "PT1" -SourceWorkSheet "Sheet1" -PivotRows "Status" -PivotData @{Status='Count' } -PivotFilter 'StartType' -IncludePivotChart -ChartType BarClustered3D $pt = New-PivotTableDefinition -PivotTableName "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.
@@ -1024,7 +1035,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])
@@ -1055,7 +1068,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 +1083,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 +1093,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 +1138,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 {
@@ -1182,12 +1198,13 @@ function Add-PivotTable {
#if specified attaches the category to slices in a pie chart : not supported on all chart types, this may give errors if applied to an unsupported type. #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] ) {
@@ -1337,7 +1354,7 @@ function Add-ExcelChart {
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
@@ -1349,7 +1366,7 @@ function Add-ExcelChart {
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 +1391,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.1.1'
# 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

@@ -512,3 +512,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

@@ -51,8 +51,16 @@ Install-Module ImportExcel -scope CurrentUser
```PowerShell ```PowerShell
Install-Module ImportExcel Install-Module ImportExcel
``` ```
# What's new to Aug 2018
- Set-Row and Set-Column will now create hyperlinks and insert dates correctly
- Import-Excel now has an argument completer for Worksheet name - this can be slow on large files
- The NumberFormat parameter (in Export-Excel, Set-Row, Set-Column, Set-Format and Add-ConditionalFormat) and X&YAxisNumberFormat 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
- Additional tests.
# What's new to 18th July 18 # 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

@@ -111,6 +111,18 @@
} }
else { $cellData = $Value} else { $cellData = $Value}
if ($cellData -match "^=") { $Worksheet.Cells[$Row, $Column].Formula = $cellData } if ($cellData -match "^=") { $Worksheet.Cells[$Row, $Column].Formula = $cellData }
elseif ( [System.Uri]::IsWellFormedUriString($cellData , [System.UriKind]::Absolute)) {
# Save a hyperlink : internal links can be in the form xl://sheet!E419 (use A1 as goto sheet), or xl://RangeName
if ($cellData -match "^xl://internal/") {
$referenceAddress = $cellData -replace "^xl://internal/" , ""
$display = $referenceAddress -replace "!A1$" , ""
$h = New-Object -TypeName OfficeOpenXml.ExcelHyperLink -ArgumentList $referenceAddress , $display
$Worksheet.Cells[$Row, $Column].HyperLink = $h
}
else {$Worksheet.Cells[$Row, $Column].HyperLink = $cellData }
$Worksheet.Cells[$Row, $Column].Style.Font.Color.SetColor([System.Drawing.Color]::Blue)
$Worksheet.Cells[$Row, $Column].Style.Font.UnderLine = $true
}
else { $Worksheet.Cells[$Row, $Column].Value = $cellData } 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 [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.
}} }}

View File

@@ -32,7 +32,7 @@
$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 for to fill in. Script block can use $worksheet, $row, $column [number], $ColumnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn
[parameter(Mandatory=$true)] [parameter(Mandatory=$true)]
$Value, $Value,
#Optional Row heading #Optional Row heading
@@ -110,6 +110,18 @@
} }
else{$cellData = $Value} else{$cellData = $Value}
if ($cellData -match "^=") { $Worksheet.Cells[$Row, $column].Formula = $cellData } if ($cellData -match "^=") { $Worksheet.Cells[$Row, $column].Formula = $cellData }
elseif ( [System.Uri]::IsWellFormedUriString($cellData , [System.UriKind]::Absolute)) {
# Save a hyperlink : internal links can be in the form xl://sheet!E419 (use A1 as goto sheet), or xl://RangeName
if ($cellData -match "^xl://internal/") {
$referenceAddress = $cellData -replace "^xl://internal/" , ""
$display = $referenceAddress -replace "!A1$" , ""
$h = New-Object -TypeName OfficeOpenXml.ExcelHyperLink -ArgumentList $referenceAddress , $display
$Worksheet.Cells[$Row, $Column].HyperLink = $h
}
else {$Worksheet.Cells[$Row, $Column].HyperLink = $cellData }
$Worksheet.Cells[$Row, $Column].Style.Font.Color.SetColor([System.Drawing.Color]::Blue)
$Worksheet.Cells[$Row, $Column].Style.Font.UnderLine = $true
}
else { $Worksheet.Cells[$Row, $column].Value = $cellData } 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 [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.
}} }}

View File

@@ -120,9 +120,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,11 +133,21 @@
$Address.Style.VerticalAlignment = $VerticalAlignment $Address.Style.VerticalAlignment = $VerticalAlignment
} }
if ($PSBoundParameters.ContainsKey('Value')) { if ($PSBoundParameters.ContainsKey('Value')) {
if ($Value -like '=*') {$Address.Formula = $Value}
else {
$Address.Value = $Value $Address.Value = $Value
if ($Value -is [DateTime]) {
$Address.Style.Numberformat.Format = 'm/d/yy h:mm' # This is not a custom format, but a preset recognized as date and localized. It might be overwritten in a moment
} }
}
}
if ($PSBoundParameters.ContainsKey('Formula')) { if ($PSBoundParameters.ContainsKey('Formula')) {
$Address.Formula = $Formula $Address.Formula = $Formula
} }
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,7 +201,7 @@
} }
else {Write-Warning -Message ("Can set the width of a column or a range but not a {0} object" -f ($Address.GetType().name)) } 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)) }
@@ -203,3 +210,72 @@
} }
} }
} }
Function NumberFormatCompletion {
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
$numformats = [ordered]@{
"General" = "General" # format ID 0
"Number" = "0.00" # format ID 2
"Percentage" = "0.00%" # format ID 10
"Scientific" = "0.00E+00" # format ID 11
"Fraction" = "# ?/?" # format ID 12
"Short Date" = "Localized" # format ID 14 - will be translated to "mm-dd-yy" which is localized on load by Excel.
"Short Time" = "Localized" # format ID 20 - will be translated to "h:mm" which is localized on load by Excel.
"Long Time" = "Localized" # format ID 21 - will be translated to "h:mm:ss" which is localized on load by Excel.
"Date-Time" = "Localized" # format ID 22 - will be translated to "m/d/yy h:mm" which is localized on load by Excel.
"Currency" = [cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol + "#,##0.00"
"Text" = "@" # format ID 49
"h:mm AM/PM" = "h:mm AM/PM" # format ID 18
"h:mm:ss AM/PM" = "h:mm:ss AM/PM" # format ID 19
"mm:ss" = "mm:ss" # format ID 45
"[h]:mm:ss" = "Elapsed hours" # format ID 46
"mm:ss.0" = "mm:ss.0" # format ID 47
"d-mmm-yy" = "Localized" # format ID 15 which is localized on load by Excel.
"d-mmm" = "Localized" # format ID 16 which is localized on load by Excel.
"mmm-yy" = "mmm-yy" # format ID 17 which is localized on load by Excel.
"0" = "Whole number" # format ID 1
"0.00" = "Number, 2 decimals" # format ID 2 or "number"
"#,##0" = "Thousand separators" # format ID 3
"#,##0.00" = "Thousand separators and 2 decimals" # format ID 4
"#," = "Whole thousands"
"#.0,," = "Millions, 1 Decimal"
"0%" = "Nearest whole percentage" # format ID 9
"0.00%" = "Percentage with decimals" # format ID 10 or "Percentage"
"00E+00" = "Scientific" # format ID 11 or "Scientific"
"# ?/?" = "One Digit fraction" # format ID 12 or "Fraction"
"# ??/??" = "Two Digit fraction" # format ID 13
"@" = "Text" # format ID 49 or "Text"
}
$numformats.keys.where({$_ -like "$wordToComplete*"} ) | ForEach-Object {
New-Object -TypeName System.Management.Automation.CompletionResult -ArgumentList "'$_'" , $_ ,
([System.Management.Automation.CompletionResultType]::ParameterValue) , $numformats[$_]
}
}
if (Get-Command -ErrorAction SilentlyContinue -name Register-ArgumentCompleter) {
Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion
Register-ArgumentCompleter -CommandName Export-Excel -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion
Register-ArgumentCompleter -CommandName Set-Format -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion
Register-ArgumentCompleter -CommandName Set-Column -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion
Register-ArgumentCompleter -CommandName Set-Row -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion
Register-ArgumentCompleter -CommandName New-ExcelChartDefinition -ParameterName XAxisNumberformat -ScriptBlock $Function:NumberFormatCompletion
Register-ArgumentCompleter -CommandName New-ExcelChartDefinition -ParameterName YAxisNumberformat -ScriptBlock $Function:NumberFormatCompletion
Register-ArgumentCompleter -CommandName Add-ExcelChart -ParameterName XAxisNumberformat -ScriptBlock $Function:NumberFormatCompletion
Register-ArgumentCompleter -CommandName Add-ExcelChart -ParameterName YAxisNumberformat -ScriptBlock $Function:NumberFormatCompletion
}
Function Expand-NumberFormat {
param ($NumberFormat)
switch ($NumberFormat) {
"Currency" {return [cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol + "#,##0.00"}
"Number" {return "0.00" } # format id 2
"Percentage" {return "0.00%" } # format id 10
"Scientific" {return "0.00E+00" } # format id 11
"Fraction" {return "# ?/?" } # format id 12
"Short Date" {return "mm-dd-yy" } # format id 14 localized on load by Excel.
"Short Time" {return "h:mm" } # format id 20 localized on load by Excel.
"Long Time" {return "h:mm:ss" } # format id 21 localized on load by Excel.
"Date-Time" {return "m/d/yy h:mm"} # format id 22 localized on load by Excel.
"Text" {return "@" } # format ID 49
Default {return $NumberFormat}
}
}

24
ToDo.md
View File

@@ -1,11 +1,17 @@
- [ ] Create an autocomplete for WorkSheetName param on ImportExcel and for number format ; where number format exists Translate "Date", "DateTime", "Currency" - [x] Create an autocomplete for WorkSheetName param on ImportExcel and for number format ; where number format exists Translate "Date", "DateTime", "Currency"
- [x] Support "make worksheet active"
- [X] Add checks for valid worksheet names
- [ ] Improve checking of worksheet, pivot names, range names and table names
- [ ] Investigate regional support for number conversion & possible date conversion. Also investigate feasablity of preserving number format when converting string to number
- [ ] Add help text for parmaters which don't have it ( PivotDataToColumn , NoClobber and CellStyleSB ) in Export Excel, copy to Send-SQLDataToExcel - [ ] 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 Add PivotTable selecting source sheet by position
- [ ] Increase code covereage for import-excel and Set-Format -[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

@@ -235,7 +235,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

@@ -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,7 +50,7 @@ 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 "Inserted a worksheet with 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"

View File

@@ -50,7 +50,7 @@ Describe ExportExcel {
} }
} }
it "Formatted the process StartTime field as 'local short date' " { it "Formatted the process StartTime field as 'localized Date-Time' " {
$STHeader = $ws.cells["1:1"].where( {$_.Value -eq "StartTime"})[0] $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
@@ -605,7 +605,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

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,12 +31,31 @@ 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"
@@ -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

@@ -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,8 +10,129 @@ 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 " {
Expand-NumberFormat 'Number' | Should be "0.00"
Expand-NumberFormat 'Percentage' | Should be "0.00%"
Expand-NumberFormat 'Scientific' | Should be "0.00E+00"
Expand-NumberFormat 'Currency' | Should be ([cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol + "#,##0.00")
Expand-NumberFormat 'Fraction' | Should be "# ?/?"
Expand-NumberFormat 'Short Date' | Should be "mm-dd-yy"
Expand-NumberFormat 'Short Time' | Should be "h:mm"
Expand-NumberFormat 'Long Time' | Should be "h:mm:ss"
Expand-NumberFormat 'Date-Time' | Should be "m/d/yy h:mm"
Expand-NumberFormat 'Text' | Should be "@"
}
}
Context "Apply-NumberFormat" {
BeforeAll {
Remove-Item -Path $path -ErrorAction SilentlyContinue
$n = [datetime]::Now.ToOADate()
$excel = 1..32 | ForEach-Object {$n} | Export-Excel -Path $path -PassThru
$ws = $excel.Workbook.Worksheets[1]
Set-Format -WorkSheet $ws -Range "A1" -numberFormat 'General'
Set-Format -WorkSheet $ws -Range "A2" -numberFormat 'Number'
Set-Format -WorkSheet $ws -Range "A3" -numberFormat 'Percentage'
Set-Format -WorkSheet $ws -Range "A4" -numberFormat 'Scientific'
Set-Format -WorkSheet $ws -Range "A5" -numberFormat 'Fraction'
Set-Format -WorkSheet $ws -Range "A6" -numberFormat 'Short Date'
Set-Format -WorkSheet $ws -Range "A7" -numberFormat 'Short Time'
Set-Format -WorkSheet $ws -Range "A8" -numberFormat 'Long Time'
Set-Format -WorkSheet $ws -Range "A9" -numberFormat 'Date-Time'
Set-Format -WorkSheet $ws -Range "A10" -numberFormat 'Currency'
Set-Format -WorkSheet $ws -Range "A11" -numberFormat 'Text'
Set-Format -WorkSheet $ws -Range "A12" -numberFormat 'h:mm AM/PM'
Set-Format -WorkSheet $ws -Range "A13" -numberFormat 'h:mm:ss AM/PM'
Set-Format -WorkSheet $ws -Range "A14" -numberFormat 'mm:ss'
Set-Format -WorkSheet $ws -Range "A15" -numberFormat '[h]:mm:ss'
Set-Format -WorkSheet $ws -Range "A16" -numberFormat 'mmss.0'
Set-Format -WorkSheet $ws -Range "A17" -numberFormat 'd-mmm-yy'
Set-Format -WorkSheet $ws -Range "A18" -numberFormat 'd-mmm'
Set-Format -WorkSheet $ws -Range "A19" -numberFormat 'mmm-yy'
Set-Format -WorkSheet $ws -Range "A20" -numberFormat '0'
Set-Format -WorkSheet $ws -Range "A21" -numberFormat '0.00'
Set-Format -Address $ws.Cells[ "A22"] -NumberFormat '#,##0'
Set-Format -Address $ws.Cells[ "A23"] -NumberFormat '#,##0.00'
Set-Format -Address $ws.Cells[ "A24"] -NumberFormat '#,'
Set-Format -Address $ws.Cells[ "A25"] -NumberFormat '#.0,,'
Set-Format -Address $ws.Cells[ "A26"] -NumberFormat '0%'
Set-Format -Address $ws.Cells[ "A27"] -NumberFormat '0.00%'
Set-Format -Address $ws.Cells[ "A28"] -NumberFormat '0.00E+00'
Set-Format -Address $ws.Cells[ "A29"] -NumberFormat '# ?/?'
Set-Format -Address $ws.Cells[ "A30"] -NumberFormat '# ??/??'
Set-Format -Address $ws.Cells[ "A31"] -NumberFormat '@'
Close-ExcelPackage -ExcelPackage $excel
$excel = Open-ExcelPackage -Path $path
$ws = $excel.Workbook.Worksheets[1]
}
It "Set formats which translate to the correct format ID " {
$ws.Cells[10,1].Style.Numberformat.format | # Set as "Currency"
Should match ("^" + ([regex]::Escape([cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol)))
$ws.Cells[ 1,1].Style.Numberformat.NumFmtID | Should be 0 # Set as General
$ws.Cells[20,1].Style.Numberformat.NumFmtID | Should be 1 # Set as 0
$ws.Cells[ 2,1].Style.Numberformat.NumFmtID | Should be 2 # Set as "Number"
$ws.Cells[21,1].Style.Numberformat.NumFmtID | Should be 2 # Set as 0.00
$ws.Cells[22,1].Style.Numberformat.NumFmtID | Should be 3 # Set as #,##0
$ws.Cells[23,1].Style.Numberformat.NumFmtID | Should be 4 # Set as #,##0.00
$ws.Cells[26,1].Style.Numberformat.NumFmtID | Should be 9 # Set as 0%
$ws.Cells[27,1].Style.Numberformat.NumFmtID | Should be 10 # Set as 0.00%
$ws.Cells[ 3,1].Style.Numberformat.NumFmtID | Should be 10 # Set as "Percentage"
$ws.Cells[28,1].Style.Numberformat.NumFmtID | Should be 11 # Set as 0.00E+00
$ws.Cells[ 4,1].Style.Numberformat.NumFmtID | Should be 11 # Set as "Scientific"
$ws.Cells[ 5,1].Style.Numberformat.NumFmtID | Should be 12 # Set as "Fraction"
$ws.Cells[29,1].Style.Numberformat.NumFmtID | Should be 12 # Set as # ?/?
$ws.Cells[30,1].Style.Numberformat.NumFmtID | Should be 13 # Set as # ??/?
$ws.Cells[ 6,1].Style.Numberformat.NumFmtID | Should be 14 # Set as "Short date"
$ws.Cells[17,1].Style.Numberformat.NumFmtID | Should be 15 # Set as d-mmm-yy
$ws.Cells[18,1].Style.Numberformat.NumFmtID | Should be 16 # Set as d-mmm
$ws.Cells[19,1].Style.Numberformat.NumFmtID | Should be 17 # Set as mmm-yy
$ws.Cells[12,1].Style.Numberformat.NumFmtID | Should be 18 # Set as h:mm AM/PM
$ws.Cells[13,1].Style.Numberformat.NumFmtID | Should be 19 # Set as h:mm:ss AM/PM
$ws.Cells[ 7,1].Style.Numberformat.NumFmtID | Should be 20 # Set as "Short time"
$ws.Cells[ 8,1].Style.Numberformat.NumFmtID | Should be 21 # Set as "Long time"
$ws.Cells[ 9,1].Style.Numberformat.NumFmtID | Should be 22 # Set as "Date-time"
$ws.Cells[14,1].Style.Numberformat.NumFmtID | Should be 45 # Set as mm:ss
$ws.Cells[15,1].Style.Numberformat.NumFmtID | Should be 46 # Set as [h]:mm:ss
$ws.Cells[16,1].Style.Numberformat.NumFmtID | Should be 47 # Set as mmss.0
$ws.Cells[11,1].Style.Numberformat.NumFmtID | Should be 49 # Set as "Text"
$ws.Cells[31,1].Style.Numberformat.NumFmtID | Should be 49 # Set as @
$ws.Cells[24,1].Style.Numberformat.Format | Should be '#,' # Whole thousands
$ws.Cells[25,1].Style.Numberformat.Format | Should be '#.0,,' # Millions
}
}
}
Describe "Set-Column, Set-Row and Set Format" { 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"]
@@ -27,19 +147,26 @@ 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
$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 Close-ExcelPackage $excel
$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"].Style.Font.Color.rgb | Should be "FF0000FF"
$ws.cells["e2"].Style.Font.Bold | Should be $true $ws.cells["e2"].Style.Font.Bold | Should be $true
@@ -49,6 +176,9 @@ Describe "Set-Column, Set-Row and Set Format" {
} }
} }
Context "Other formatting" { Context "Other formatting" {
it "Trapped an attempt to hide a range instead of a Row/Column " {
$BadHideWarnvar | Should not beNullOrEmpty
}
it "Set a row formula with border font size and underline " { it "Set a row formula with border font size and underline " {
$ws.cells["b7"].style.Border.Top.Style | Should be "None" $ws.cells["b7"].style.Border.Top.Style | Should be "None"
$ws.cells["F7"].style.Border.Top.Style | Should be "None" $ws.cells["F7"].style.Border.Top.Style | Should be "None"
@@ -63,7 +193,6 @@ Describe "Set-Column, Set-Row and Set Format" {
$ws.cells["C7"].style.Font.UnderLine | Should be $true $ws.cells["C7"].style.Font.UnderLine | Should be $true
$ws.cells["C6"].style.Font.UnderLine | Should be $false $ws.cells["C6"].style.Font.UnderLine | Should be $false
} }
it "Set custom text wrapping, alignment, superscript, border and Fill " { it "Set custom text wrapping, alignment, superscript, border and Fill " {
$ws.cells["e3"].Style.HorizontalAlignment | Should be "Left" $ws.cells["e3"].Style.HorizontalAlignment | Should be "Left"
$ws.cells["e3"].Style.Font.VerticalAlign | Should be "Superscript" $ws.cells["e3"].Style.Font.VerticalAlign | Should be "Superscript"
@@ -77,13 +206,80 @@ Describe "Set-Column, Set-Row and Set Format" {
$ws.cells["e1"].Style.Font.Bold | Should be $false $ws.cells["e1"].Style.Font.Bold | Should be $false
$ws.cells["C6"].style.WrapText | Should be $false $ws.cells["C6"].style.WrapText | Should be $false
$ws.cells["e7"].style.WrapText | Should be $true $ws.cells["e7"].style.WrapText | Should be $true
$ws.cells["e7"].Style.Fill.BackgroundColor.Rgb| Should be "FFF0F8FF" $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.PatternColor.Rgb | Should be "FFFF0000"
$ws.cells["e7"].Style.Fill.PatternType | Should be "DarkTrellis" $ws.cells["e7"].Style.Fill.PatternType | Should be "DarkTrellis"
} }
} }
Context "Set-Format value setting " {
it "Inserted a formula " {
$ws.Cells["D7"].Formula | Should be "=E7/C7"
}
it "Inserted a value " {
$ws.Cells["B7"].Value | Should be "Total"
}
it "Inserted a date with localized date-time format " {
$ws.Cells["B8"].Style.Numberformat.NumFmtID | Should be 22
}
}
Context "Set-Column Value Setting" {
BeforeAll {
Remove-Item -Path $path -ErrorAction SilentlyContinue
$excel = $DriverData | Export-Excel -PassThru -Path $path -AutoSize -AutoNameRange
$ws = $excel.Workbook.Worksheets[1]
Set-Column -Worksheet $ws -Heading "Link" -AutoSize -Value {"https://en.wikipedia.org" + $worksheet.cells["B$Row"].value }
$c = Set-Column -PassThru -Worksheet $ws -Heading "NextBirthday" -Value {
$bmonth = $worksheet.cells["C$Row"].value.month ; $bDay = $worksheet.cells["C$Row"].value.day
$cMonth = [datetime]::Now.Month ; $cday = [datetime]::Now.day ; $cyear = [datetime]::Now.Year
if (($cmonth -gt $bmonth) -or (($cMonth -eq $bmonth) -and ($cday -ge $bDay))){
[datetime]::new($cyear+1, $bmonth, $bDay)
}
else {[datetime]::new($cyear, $bmonth, $bday) }
}
Set-Column -Worksheet $ws -Heading "Age" -Value "=INT((NOW()-DateOfBirth)/365)"
Set-Format -Address $c,$ws.column(3) -NumberFormat 'Short Date' -AutoSize
Close-ExcelPackage -ExcelPackage $excel
$excel = Open-ExcelPackage $path
$ws = $excel.Workbook.Worksheets["Sheet1"]
}
It "Inserted Hyperlinks " {
$ws.Cells["D2"].Hyperlink | Should not beNullorEmpty
$ws.Cells["D2"].Style.Font.UnderLine | Should be $true
}
It "Inserted Dates " {
$ws.Cells["C2"].Value.GetType().name | should be "DateTime"
$ws.Cells["C2"].Style.Numberformat.NumFmtID | should be 14
$ws.Cells["E2"].Value.GetType().name | should be "DateTime"
$ws.Cells["E2"].Style.Numberformat.NumFmtID | should be 14
}
It "Inserted Formulas " {
$ws.Cells["F2"].Formula | Should not beNullorEmpty
}
}
} }
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"
}
}
}

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