Re-work of parameters in Set-Format (#400)

This commit is contained in:
jhoneill
2018-07-25 21:36:14 +01:00
parent 51c6a98360
commit 7995503bd3
15 changed files with 283 additions and 156 deletions

View File

@@ -9,7 +9,7 @@ function DoChart {
) )
if($targetData[0] -is [System.ValueType]) { if($targetData[0] -is [System.ValueType]) {
$chart = New-ExcelChart -YRange "A1:A$($targetData.count)" -Title $title -ChartType $ChartType $chart = New-ExcelChartDefinition -YRange "A1:A$($targetData.count)" -Title $title -ChartType $ChartType
} else { } else {
$xyRange = Get-XYRange $targetData $xyRange = Get-XYRange $targetData
@@ -19,7 +19,7 @@ function DoChart {
$Y = $xyRange.YRange.ExcelColumn $Y = $xyRange.YRange.ExcelColumn
$YRange = "{0}2:{0}{1}" -f $Y,($targetData.count+1) $YRange = "{0}2:{0}{1}" -f $Y,($targetData.count+1)
$chart = New-ExcelChart -XRange $xRange -YRange $yRange -Title $title -ChartType $ChartType ` $chart = New-ExcelChartDefinition -XRange $xRange -YRange $yRange -Title $title -ChartType $ChartType `
-NoLegend:$NoLegend -ShowCategory:$ShowCategory -ShowPercent:$ShowPercent -NoLegend:$NoLegend -ShowCategory:$ShowCategory -ShowPercent:$ShowPercent
} }

View File

@@ -7,10 +7,11 @@
if (Get-Command -Name register-argumentCompleter -ErrorAction SilentlyContinue) { if (Get-Command -Name register-argumentCompleter -ErrorAction SilentlyContinue) {
Register-ArgumentCompleter -CommandName Export-Excel -ParameterName TitleBackgroundColor -ScriptBlock $Function:ColorCompletion Register-ArgumentCompleter -CommandName Export-Excel -ParameterName TitleBackgroundColor -ScriptBlock $Function:ColorCompletion
Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion
Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName DataBarColor -ScriptBlock $Function:ColorCompletion Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName DataBarColor -ScriptBlock $Function:ColorCompletion
Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName ForeGroundColor -ScriptBlock $Function:ColorCompletion Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName ForeGroundColor -ScriptBlock $Function:ColorCompletion
Register-ArgumentCompleter -CommandName Compare-Worksheet -ParameterName AllDataBackgroundColor -ScriptBlock $Function:ColorCompletion Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName PatternColor -ScriptBlock $Function:ColorCompletion
Register-ArgumentCompleter -CommandName Compare-Worksheet -ParameterName AllDataBackgroundColor -ScriptBlock $Function:ColorCompletion
Register-ArgumentCompleter -CommandName Compare-Worksheet -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion Register-ArgumentCompleter -CommandName Compare-Worksheet -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion
Register-ArgumentCompleter -CommandName Compare-Worksheet -ParameterName FontColor -ScriptBlock $Function:ColorCompletion Register-ArgumentCompleter -CommandName Compare-Worksheet -ParameterName FontColor -ScriptBlock $Function:ColorCompletion
Register-ArgumentCompleter -CommandName Compare-Worksheet -ParameterName TabColor -ScriptBlock $Function:ColorCompletion Register-ArgumentCompleter -CommandName Compare-Worksheet -ParameterName TabColor -ScriptBlock $Function:ColorCompletion
@@ -22,6 +23,8 @@ if (Get-Command -Name register-argumentCompleter -ErrorAction SilentlyContinue)
Register-ArgumentCompleter -CommandName Merge-MulipleSheets -ParameterName ChangeBackgroundColor -ScriptBlock $Function:ColorCompletion Register-ArgumentCompleter -CommandName Merge-MulipleSheets -ParameterName ChangeBackgroundColor -ScriptBlock $Function:ColorCompletion
Register-ArgumentCompleter -CommandName Merge-MulipleSheets ` -ParameterName DeleteBackgroundColor -ScriptBlock $Function:ColorCompletion Register-ArgumentCompleter -CommandName Merge-MulipleSheets ` -ParameterName DeleteBackgroundColor -ScriptBlock $Function:ColorCompletion
Register-ArgumentCompleter -CommandName Merge-MulipleSheets -ParameterName KeyFontColor -ScriptBlock $Function:ColorCompletion Register-ArgumentCompleter -CommandName Merge-MulipleSheets -ParameterName KeyFontColor -ScriptBlock $Function:ColorCompletion
Register-ArgumentCompleter -CommandName New-ConditionalText -ParameterName PatternColor -ScriptBlock $Function:ColorCompletion
Register-ArgumentCompleter -CommandName New-ConditionalText -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion
Register-ArgumentCompleter -CommandName Set-Format -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion Register-ArgumentCompleter -CommandName Set-Format -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion
Register-ArgumentCompleter -CommandName Set-Format -ParameterName FontColor -ScriptBlock $Function:ColorCompletion Register-ArgumentCompleter -CommandName Set-Format -ParameterName FontColor -ScriptBlock $Function:ColorCompletion
Register-ArgumentCompleter -CommandName Set-Format -ParameterName PatternColor -ScriptBlock $Function:ColorCompletion Register-ArgumentCompleter -CommandName Set-Format -ParameterName PatternColor -ScriptBlock $Function:ColorCompletion

View File

@@ -2,13 +2,13 @@ try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {}
Remove-Item temp.xlsx -ErrorAction Ignore Remove-Item temp.xlsx -ErrorAction Ignore
$data = invoke-sum (Get-Process) company handles,pm,VirtualMemorySize $data = Invoke-Sum -data (Get-Process) -dimension Company -measure Handles, PM, VirtualMemorySize
$c = New-ExcelChart -Title Stats ` $c = New-ExcelChartDefinition -Title "ProcessStats" `
-ChartType LineMarkersStacked ` -ChartType LineMarkersStacked `
-Header "Stuff" ` -XRange "Processes[Name]" `
-XRange "Processes[Company]" ` -YRange "Processes[PM]","Processes[VirtualMemorySize]" `
-YRange "Processes[PM]","Processes[VirtualMemorySize]" -SeriesHeader "PM","VM"
$data | $data |
Export-Excel temp.xlsx -AutoSize -TableName Processes -Show -ExcelChartDefinition $c Export-Excel -Path temp.xlsx -AutoSize -TableName Processes -ExcelChartDefinition $c -Show

View File

@@ -6,13 +6,14 @@ $data = @"
A,B,C,Date A,B,C,Date
2,1,1,2016-03-29 2,1,1,2016-03-29
5,10,1,2016-03-29 5,10,1,2016-03-29
"@ | ConvertFrom-Csv "@
$c = New-ExcelChart -Title Impressions ` $c = New-ExcelChartDefinition -Title Impressions `
-ChartType Line -Header "Something" ` -ChartType Line `
-XRange "Impressions[Date]" ` -XRange "Impressions[Date]" `
-YRange @("Impressions[B]","Impressions[A]") ` -YRange "Impressions[B]" # @("Impressions[B]","Impressions[A]") `
-SeriesHeader 'B data','A data' -SeriesHeader 'B data','A data' `
-Row 0 -Column 0
$data | $data | ConvertFrom-Csv | Export-Excel -path temp.xlsx -AutoSize -TableName Impressions
Export-Excel temp.xlsx -AutoSize -TableName Impressions -Show -ExcelChartDefinition $c Export-Excel -path temp.xlsx -worksheetName chartPage -ExcelChartDefinition $c -show

View File

@@ -1,6 +1,6 @@
try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {}
Remove-Item *.xlsx Remove-Item -Path Tools.xlsx
$data = @" $data = @"
ID,Product,Quantity,Price,Total ID,Product,Quantity,Price,Total
@@ -9,13 +9,11 @@ ID,Product,Quantity,Price,Total
12003,Saw,12,15.37,184.44 12003,Saw,12,15.37,184.44
12010,Drill,20,8,160 12010,Drill,20,8,160
12011,Crowbar,7,23.48,164.36 12011,Crowbar,7,23.48,164.36
"@ | ConvertFrom-Csv "@
$xRange = "Product" $c1 = New-ExcelChartDefinition -YRange "Price" -XRange "Product" -Title "Item price" -NoLegend -Height 225
$c2 = New-ExcelChartDefinition -YRange "Total "-XRange "Product" -Title "Total sales" -NoLegend -Height 225 -Row 9 -Column 15
$c3 = New-ExcelChartDefinition -YRange "Quantity"-XRange "Product" -Title "Sales volume" -NoLegend -Height 225 -Row 15
$yRange="Price"; $c1 = New-ExcelChart -YRange $yRange -XRange $xRange -Title $yRange -Height 225 $data | ConvertFrom-Csv |
$yRange="Total"; $c2 = New-ExcelChart -YRange $yRange -XRange $xRange -Title $yRange -Row 9 -Column 15 -Height 225 Export-Excel -Path "Tools.xlsx" -AutoFilter -AutoNameRange -AutoSize -ExcelChartDefinition $c1,$c2,$c3 -Show
$yRange="Quantity"; $c3 = New-ExcelChart -YRange $yRange -XRange $xRange -Title $yRange -Row 15 -Height 225
$data |
Export-Excel -ExcelChartDefinition $c1,$c2,$c3 Tools.xlsx -Show -AutoFilter -AutoNameRange -AutoSize

View File

@@ -869,14 +869,16 @@
yrange = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R[$FirstDataRow]C[$ycol]:R[$($lastrow)]C[$ycol]",0,0) ; yrange = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R[$FirstDataRow]C[$ycol]:R[$($lastrow)]C[$ycol]",0,0) ;
title = ""; title = "";
Column = ($lastCol +1) ; Column = ($lastCol +1) ;
Width = 1200 Width = 800
} }
if ($NoHeader) {$params["NoHeader"] = $true} if ($ShowPercent) {$params["ShowPercent"] = $true}
else {$Params["SeriesHeader"] = $ws.Cells[$startRow, $YCol].Value} if ($ShowCategory) {$params["ShowCategory"] = $true}
if ($NoLegend) {$params["NoLegend"] = $true}
if (-not $NoHeader) {$params["SeriesHeader"] = $ws.Cells[$startRow, $YCol].Value}
if ($ColumnChart) {$Params["chartType"] = "ColumnStacked" } if ($ColumnChart) {$Params["chartType"] = "ColumnStacked" }
elseif ($Barchart) {$Params["chartType"] = "BarStacked" } elseif ($Barchart) {$Params["chartType"] = "BarStacked" }
elseif ($PieChart) {$Params["chartType"] = "PieExploded3D" } elseif ($PieChart) {$Params["chartType"] = "PieExploded3D" }
elseif ($LineChart) {$Params["chartType"] = "Line" } elseif ($LineChart) {$Params["chartType"] = "Line" }
Add-ExcelChart -Worksheet $ws @params Add-ExcelChart -Worksheet $ws @params
} }
@@ -1309,8 +1311,8 @@ 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.XAxis.AxisPosition = $XAxisPosition} if ($XAxisPosition) {$chart.ChartXml.chartSpace.chart.plotArea.catAx.axPos.val = $XAxisPosition.ToString().substring(0,1)}
if ($XMajorUnit) {$chart.XAxis.MajorUnit = $XMajorUnit} if ($XMajorUnit) {$chart.XAxis.MajorUnit = $XMajorUnit}
if ($XMinorUnit) {$chart.XAxis.MinorUnit = $XMinorUnit} if ($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}
@@ -1321,7 +1323,7 @@ function Add-ExcelChart {
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.YAxis.AxisPosition = $YAxisPosition} if ($YAxisPosition) {$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}

View File

@@ -44,6 +44,15 @@ To install to your personal modules folder (e.g. ~\Documents\WindowsPowerShell\M
iex (new-object System.Net.WebClient).DownloadString('https://raw.github.com/dfinke/ImportExcel/master/Install.ps1') iex (new-object System.Net.WebClient).DownloadString('https://raw.github.com/dfinke/ImportExcel/master/Install.ps1')
``` ```
# New to 25th July
- Added parameter completer to Add-ConditionalFormatting/PatternColor New-ConditionalText PatternColor&BackgroundColor
- Changed charting.ps1 and examples\charts\*.ps1 to use New-ExcelChartDefinition instead of New-ExcelChart
- Quick charts in Export-excel were too wide (now 800 pixels instead of 1200), and now support show percent, ShowCategory and NoLegend Parameters
- Fixed bug in Add-ExcelChart where XAxisPosition and YAxisPostion would not be set correctly
- Fixed bug in Set-Format where enums with a value of zero, or zero numbers would not be set; added functionality to set-format to support -bold:$false -italic:$false etc. (see #400)
- Added tests for better coverage, and tweaked some tests to use few rows and/or columns for speed
# What's new to 18th July 18 # What's new to 18th July 18
- Moved chart creation into its own function (Add-Excel chart) within Export-Excel.ps1. Renamed New-Excelchart to New-ExcelChartDefinition to make it clearer that it is not making anything in the workbook (but for compatibility put an alias of New-ExcelChart in so existing code does not break). Found that -Header does nothing, so it isn't Add-Excel chart and there is a message that does nothing in New-ExcelChartDefinition . - 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.

View File

@@ -102,7 +102,7 @@
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 ($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
@@ -113,29 +113,16 @@
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.
}} }}
#region Apply formatting #region Apply formatting
if ($Underline) { $params = @{}
$Worksheet.Column( $Column).Style.Font.UnderLine = $true foreach ($p in @('Underline','Bold','Italic','StrikeThru','FontSize','FontShift','NumberFormat','TextRotation',
$Worksheet.Column( $Column).Style.Font.UnderLineType = $UnderLineType 'WrapText', 'HorizontalAlignment','VerticalAlignment', 'Autosize', 'Width', 'FontColor'
'BorderAround', 'BackgroundColor', 'BackgroundPattern', 'PatternColor')) {
if ($PSBoundParameters.ContainsKey($p)) {$params[$p] = $PSBoundParameters[$p]}
} }
if ($Bold) { $Worksheet.Column( $Column).Style.Font.Bold = $true } if ($params.Count) {
if ($Italic) { $Worksheet.Column( $Column).Style.Font.Italic = $true } Set-Format -WorkSheet $Worksheet -Range "$ColumnName$startRow`:$ColumnName$endRow" @params
if ($StrikeThru) { $Worksheet.Column( $Column).Style.Font.Strike = $true } }
if ($FontShift) { $Worksheet.Column( $Column).Style.Font.VerticalAlign = $FontShift } #endregion
if ($NumberFormat) { $Worksheet.Column( $Column).Style.Numberformat.Format = $NumberFormat }
if ($TextRotation) { $Worksheet.Column( $Column).Style.TextRotation = $TextRotation }
if ($WrapText) { $Worksheet.Column( $Column).Style.WrapText = $true }
if ($HorizontalAlignment) { $Worksheet.Column( $Column).Style.HorizontalAlignment = $HorizontalAlignment}
if ($VerticalAlignment) { $Worksheet.Column( $Column).Style.VerticalAlignment = $VerticalAlignment }
if ($FontColor) { $Worksheet.Column( $Column).Style.Font.Color.SetColor( $FontColor ) }
if ($BorderAround) { $Worksheet.Column( $Column).Style.Border.BorderAround( $BorderAround ) }
if ($BackgroundColor) {
$Worksheet.Column( $Column).Style.Fill.PatternType = $BackgroundPattern
$Worksheet.Column( $Column).Style.Fill.BackgroundColor.SetColor($BackgroundColor )
if ($PatternColor) { $Worksheet.Column( $Column).Style.Fill.PatternColor.SetColor( $PatternColor ) }
}
if ($Autosize) { $Worksheet.Column( $Column).AutoFit() }
elseif ($Width) { $Worksheet.Column( $Column).Width = $Width }
#endregion
#return the new data if -passthru was specified. #return the new data if -passthru was specified.
if ($passThru) { $Worksheet.Column( $Column)} if ($passThru) { $Worksheet.Column( $Column)}
} }

View File

@@ -100,7 +100,7 @@
$StartColumn ++ $StartColumn ++
} }
#Fill in the data #Fill in the data
if ($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] ) {
@@ -110,30 +110,19 @@
} }
else{$cellData = $Value} else{$cellData = $Value}
if ($cellData -match "^=") { $Worksheet.Cells[$Row, $column].Formula = $cellData } if ($cellData -match "^=") { $Worksheet.Cells[$Row, $column].Formula = $cellData }
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.
}} }}
#region Apply formatting #region Apply formatting
if ($Underline) { $params = @{}
$worksheet.row( $Row ).Style.Font.UnderLine = $true foreach ($p in @('Underline','Bold','Italic','StrikeThru','FontSize', 'FontShift','NumberFormat','TextRotation',
$worksheet.row( $Row ).Style.Font.UnderLineType = $UnderLineType 'WrapText', 'HorizontalAlignment','VerticalAlignment', 'Height', 'FontColor'
'BorderAround', 'BackgroundColor', 'BackgroundPattern', 'PatternColor')) {
if ($PSBoundParameters.ContainsKey($p)) {$params[$p] = $PSBoundParameters[$p]}
} }
if ($Bold) { $worksheet.row( $Row ).Style.Font.Bold = $true } if ($params.Count) {
if ($Italic) { $worksheet.row( $Row ).Style.Font.Italic = $true } $theRange = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R[$Row]C[$StartColumn]:R[$Row]C[$EndColumn]",0,0)
if ($StrikeThru) { $worksheet.row( $Row ).Style.Font.Strike = $true } Set-Format -WorkSheet $Worksheet -Range $theRange @params
if ($FontShift) { $worksheet.row( $Row ).Style.Font.VerticalAlign = $FontShift }
if ($NumberFormat) { $worksheet.row( $Row ).Style.Numberformat.Format = $NumberFormat }
if ($TextRotation) { $worksheet.row( $Row ).Style.TextRotation = $TextRotation }
if ($WrapText) { $worksheet.row( $Row ).Style.WrapText = $true }
if ($HorizontalAlignment) { $worksheet.row( $Row ).Style.HorizontalAlignment = $HorizontalAlignment}
if ($VerticalAlignment) { $worksheet.row( $Row ).Style.VerticalAlignment = $VerticalAlignment }
if ($Height) { $worksheet.row( $Row ).Height = $Height }
if ($FontColor) { $worksheet.row( $Row ).Style.Font.Color.SetColor( $FontColor ) }
if ($BorderAround) { $worksheet.row( $Row ).Style.Border.BorderAround( $BorderAround ) }
if ($BackgroundColor) {
$worksheet.row( $Row ).Style.Fill.PatternType = $BackgroundPattern
$worksheet.row( $Row ).Style.Fill.BackgroundColor.SetColor($BackgroundColor )
if ($PatternColor) { $worksheet.row( $Row ).Style.Fill.PatternColor.SetColor( $PatternColor ) }
} }
#endregion #endregion
#return the new data if -passthru was specified. #return the new data if -passthru was specified.

View File

@@ -92,59 +92,82 @@
} }
else { else {
if ($ResetFont) { if ($ResetFont) {
$Address.Style.Font.Color.SetColor("Black") $Address.Style.Font.Color.SetColor("Black")
$Address.Style.Font.Bold = $false $Address.Style.Font.Bold = $false
$Address.Style.Font.Italic = $false $Address.Style.Font.Italic = $false
$Address.Style.Font.UnderLine = $false $Address.Style.Font.UnderLine = $false
$Address.Style.Font.Strike = $false $Address.Style.Font.Strike = $false
} }
if ($Underline) { if ($PSBoundParameters.ContainsKey('Underline')) {
$Address.Style.Font.UnderLine = $true $Address.Style.Font.UnderLine = [boolean]$Underline
$Address.Style.Font.UnderLineType = $UnderLineType $Address.Style.Font.UnderLineType = $UnderLineType
} }
if ($Bold) {$Address.Style.Font.Bold = $true } if ($PSBoundParameters.ContainsKey('Bold')) {
if ($Italic) {$Address.Style.Font.Italic = $true } $Address.Style.Font.Bold = [boolean]$bold
if ($StrikeThru) {$Address.Style.Font.Strike = $true } }
if ($FontShift) {$Address.Style.Font.VerticalAlign = $FontShift } if ($PSBoundParameters.ContainsKey('Italic')) {
if ($FontColor) {$Address.Style.Font.Color.SetColor( $FontColor ) } $Address.Style.Font.Italic = [boolean]$italic
if ($NumberFormat) {$Address.Style.Numberformat.Format = $NumberFormat } }
if ($TextRotation) {$Address.Style.TextRotation = $TextRotation } if ($PSBoundParameters.ContainsKey('StrikeThru')) {
if ($WrapText) {$Address.Style.WrapText = $true } $Address.Style.Font.Strike = [boolean]$StrikeThru
if ($HorizontalAlignment) {$Address.Style.HorizontalAlignment = $HorizontalAlignment } }
if ($VerticalAlignment) {$Address.Style.VerticalAlignment = $VerticalAlignment } if ($PSBoundParameters.ContainsKey('FontSize')){
if ($Value) {$Address.Value = $Value } $Address.Style.Font.Size = $FontSize
if ($Formula) {$Address.Formula = $Formula } }
if ($BorderAround) {$Address.Style.Border.BorderAround($BorderAround, $BorderColor)} if ($PSBoundParameters.ContainsKey('FontShift')){
$Address.Style.Font.VerticalAlign = $FontShift
if ($BorderBottom) { }
if ($PSBoundParameters.ContainsKey('FontColor')){
$Address.Style.Font.Color.SetColor( $FontColor)
}
if ($PSBoundParameters.ContainsKey('NumberFormat')) {
$Address.Style.Numberformat.Format = $NumberFormat
}
if ($PSBoundParameters.ContainsKey('TextRotation')) {
$Address.Style.TextRotation = $TextRotation
}
if ($PSBoundParameters.ContainsKey('WrapText')) {
$Address.Style.WrapText = [boolean]$WrapText
}
if ($PSBoundParameters.ContainsKey('HorizontalAlignment')) {
$Address.Style.HorizontalAlignment = $HorizontalAlignment
}
if ($PSBoundParameters.ContainsKey('VerticalAlignment')) {
$Address.Style.VerticalAlignment = $VerticalAlignment
}
if ($PSBoundParameters.ContainsKey('Value')) {
$Address.Value = $Value
}
if ($PSBoundParameters.ContainsKey('Formula')) {
$Address.Formula = $Formula
}
if ($PSBoundParameters.ContainsKey('BorderAround')) {
$Address.Style.Border.BorderAround($BorderAround, $BorderColor)
}
if ($PSBoundParameters.ContainsKey('BorderBottom')) {
$Address.Style.Border.Bottom.Style=$BorderBottom $Address.Style.Border.Bottom.Style=$BorderBottom
$Address.Style.Border.Bottom.Color.SetColor($BorderColor) $Address.Style.Border.Bottom.Color.SetColor($BorderColor)
} }
if ($PSBoundParameters.ContainsKey('BorderTop')) {
if ($BorderTop) {
$Address.Style.Border.Top.Style=$BorderTop $Address.Style.Border.Top.Style=$BorderTop
$Address.Style.Border.Top.Color.SetColor($BorderColor) $Address.Style.Border.Top.Color.SetColor($BorderColor)
} }
if ($PSBoundParameters.ContainsKey('BorderLeft')) {
if ($BorderLeft) {
$Address.Style.Border.Left.Style=$BorderLeft $Address.Style.Border.Left.Style=$BorderLeft
$Address.Style.Border.Left.Color.SetColor($BorderColor) $Address.Style.Border.Left.Color.SetColor($BorderColor)
} }
if ($PSBoundParameters.ContainsKey('BorderRight')) {
if ($BorderRight) {
$Address.Style.Border.Right.Style=$BorderRight $Address.Style.Border.Right.Style=$BorderRight
$Address.Style.Border.Right.Color.SetColor($BorderColor) $Address.Style.Border.Right.Color.SetColor($BorderColor)
} }
if ($PSBoundParameters.ContainsKey('BackgroundColor')) {
if ($BackgroundColor) {
$Address.Style.Fill.PatternType = $BackgroundPattern $Address.Style.Fill.PatternType = $BackgroundPattern
$Address.Style.Fill.BackgroundColor.SetColor($BackgroundColor) $Address.Style.Fill.BackgroundColor.SetColor($BackgroundColor)
if ($PatternColor) { if ($PatternColor) {
$Address.Style.Fill.PatternColor.SetColor( $PatternColor) $Address.Style.Fill.PatternColor.SetColor( $PatternColor)
} }
} }
if ($PSBoundParameters.ContainsKey('Height')) {
if ($Height) {
if ($Address -is [OfficeOpenXml.ExcelRow] ) {$Address.Height = $Height } if ($Address -is [OfficeOpenXml.ExcelRow] ) {$Address.Height = $Height }
elseif ($Address -is [OfficeOpenXml.ExcelRange] ) { elseif ($Address -is [OfficeOpenXml.ExcelRange] ) {
($Address.Start.Row)..($Address.Start.Row + $Address.Rows) | ($Address.Start.Row)..($Address.Start.Row + $Address.Rows) |
@@ -160,7 +183,7 @@
else {Write-Warning -Message ("Can autofit a column or a range but not a {0} object" -f ($Address.GetType().name)) } else {Write-Warning -Message ("Can autofit a column or a range but not a {0} object" -f ($Address.GetType().name)) }
} }
elseif ($Width) { elseif ($PSBoundParameters.ContainsKey('Width')) {
if ($Address -is [OfficeOpenXml.ExcelColumn]) {$Address.Width = $Width} if ($Address -is [OfficeOpenXml.ExcelColumn]) {$Address.Width = $Width}
elseif ($Address -is [OfficeOpenXml.ExcelRange] ) { elseif ($Address -is [OfficeOpenXml.ExcelRange] ) {
($Address.Start.Column)..($Address.Start.Column + $Address.Columns - 1) | ($Address.Start.Column)..($Address.Start.Column + $Address.Columns - 1) |
@@ -171,9 +194,9 @@
} }
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 ($Hidden) { if ($PSBoundParameters.ContainsKey('$Hidden')) {
if ($Address -is [OfficeOpenXml.ExcelRow] -or if ($Address -is [OfficeOpenXml.ExcelRow] -or
$Address -is [OfficeOpenXml.ExcelColumn] ) {$Address.Hidden = $True} $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)) }
} }

12
ToDo.md
View File

@@ -2,10 +2,8 @@
- [ ] 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
- [ ] Add checks for valid worksheet names (also check pivot names, range names and table names are valid) - [ ] 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 - [ ] Investigate regional support for number conversion & possible date conversion
- [ ] Add help in ConvertToExcelXLSx.ps1, Copy-ExcelWorkSheet.ps1 (probably re-write copy) - [ ] 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 (continued) in Get-HTMLTable.ps1, GetRange.PS1, GetExcelTable.Ps1, Import-HTML.PS1, New-ConditionalFormattingIconSet.Ps1, NewConditionalText.PS1, New-Psitem.PS1, Remove-Worksheet.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).
[ ] Copy parameter help from function Add-ExcelChart into New-ExcelChart.ps1 - [ ] Refactor Set-Row and Set-Column to use set-format and add conditional format and return range support.
- [ ] Examples and tests for new "Quick charts" in Export Excel - [ ] Examples and tests for set-Row and Set-column
- [ ] Charting.ps1,GetXYRange.ps1, InferData.PS1 move to deprecated. (replace examples) - [ ] Add PivotTable can't select sheet by position.
- [ ] Refactor Set-Row and Set-Column to use set-format and add conditional format support.
- [ ] Examples and tests for set-Row and Set-column; review test coverage and examples for Set-Format and Add-Conditional formatting

View File

@@ -5,7 +5,7 @@ Describe "Compare Worksheet" {
Context "Simple comparison output" { Context "Simple comparison output" {
BeforeAll { BeforeAll {
Remove-Item -Path "$env:temp\server*.xlsx" Remove-Item -Path "$env:temp\server*.xlsx"
[System.Collections.ArrayList]$s = get-service | Select-Object -Property * [System.Collections.ArrayList]$s = get-service | Select-Object -first 25 -Property *
$s | Export-Excel -Path $env:temp\server1.xlsx $s | Export-Excel -Path $env:temp\server1.xlsx
#$s is a zero based array, excel rows are 1 based and excel has a header row so Excel rows will be 2 + index in $s #$s is a zero based array, excel rows are 1 based and excel has a header row so Excel rows will be 2 + index in $s
$row4Displayname = $s[2].DisplayName $row4Displayname = $s[2].DisplayName
@@ -47,9 +47,10 @@ Describe "Compare Worksheet" {
} }
} }
Context "Setting the background to highlight different rows" { Context "Setting the background to highlight different rows, use of grid view." {
BeforeAll { BeforeAll {
$null = compare-WorkSheet "$env:temp\Server1.xlsx" "$env:temp\Server2.xlsx" -BackgroundColor LightGreen Compare-WorkSheet "$env:temp\Server1.xlsx" "$env:temp\Server2.xlsx" -BackgroundColor LightGreen -GridView
Start-Sleep -sec 5; [System.Windows.Forms.SendKeys]::Sendwait("%{F4}")
$xl1 = Open-ExcelPackage -Path "$env:temp\Server1.xlsx" $xl1 = Open-ExcelPackage -Path "$env:temp\Server1.xlsx"
$xl2 = Open-ExcelPackage -Path "$env:temp\Server2.xlsx" $xl2 = Open-ExcelPackage -Path "$env:temp\Server2.xlsx"
$s1Sheet = $xl1.Workbook.Worksheets[1] $s1Sheet = $xl1.Workbook.Worksheets[1]
@@ -104,7 +105,7 @@ Describe "Compare Worksheet" {
Context "More complex comparison: output check and different worksheet names " { Context "More complex comparison: output check and different worksheet names " {
BeforeAll { BeforeAll {
[System.Collections.ArrayList]$s = get-service | Select-Object -Property * -ExcludeProperty Name [System.Collections.ArrayList]$s = get-service | Select-Object -first 25 -Property * -ExcludeProperty Name
$s | Export-Excel -Path $env:temp\server1.xlsx -WorkSheetname Server1 $s | Export-Excel -Path $env:temp\server1.xlsx -WorkSheetname Server1
#$s is a zero based array, excel rows are 1 based and excel has a header row so Excel rows will be 2 + index in $s #$s is a zero based array, excel rows are 1 based and excel has a header row so Excel rows will be 2 + index in $s
$row4Displayname = $s[2].DisplayName $row4Displayname = $s[2].DisplayName
@@ -177,7 +178,7 @@ Describe "Merge Worksheet" {
Context "Merge with 3 properties" { Context "Merge with 3 properties" {
BeforeAll { BeforeAll {
Remove-Item -Path "$env:temp\server*.xlsx" , "$env:temp\Combined*.xlsx" -ErrorAction SilentlyContinue Remove-Item -Path "$env:temp\server*.xlsx" , "$env:temp\Combined*.xlsx" -ErrorAction SilentlyContinue
[System.Collections.ArrayList]$s = get-service | Select-Object -Property * [System.Collections.ArrayList]$s = get-service | Select-Object -first 25 -Property *
$s | Export-Excel -Path $env:temp\server1.xlsx $s | Export-Excel -Path $env:temp\server1.xlsx
@@ -243,7 +244,7 @@ Describe "Merge Multiple sheets" {
Context "Merge 3 sheets with 3 properties" { Context "Merge 3 sheets with 3 properties" {
BeforeAll { BeforeAll {
Remove-Item -Path "$env:temp\server*.xlsx" , "$env:temp\Combined*.xlsx" -ErrorAction SilentlyContinue Remove-Item -Path "$env:temp\server*.xlsx" , "$env:temp\Combined*.xlsx" -ErrorAction SilentlyContinue
[System.Collections.ArrayList]$s = get-service | Select-Object -Property Name,DisplayName,StartType [System.Collections.ArrayList]$s = get-service | Select-Object -first 25 -Property Name,DisplayName,StartType
$s | Export-Excel -Path $env:temp\server1.xlsx $s | Export-Excel -Path $env:temp\server1.xlsx
#$s is a zero based array, excel rows are 1 based and excel has a header row so Excel rows will be 2 + index in $s #$s is a zero based array, excel rows are 1 based and excel has a header row so Excel rows will be 2 + index in $s

View File

@@ -1,6 +1,6 @@
$path1 = "$env:TEMP\Test1.xlsx" $path1 = "$env:TEMP\Test1.xlsx"
$path2 = "$env:TEMP\Test2.xlsx" $path2 = "$env:TEMP\Test2.xlsx"
Remove-item -Path $path1, $path2 # -ErrorAction SilentlyContinue 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

View File

@@ -22,8 +22,7 @@ Describe ExportExcel {
# it "Started Excel to display the file " { # it "Started Excel to display the file " {
# Get-process -Name Excel, xlim -ErrorAction SilentlyContinue | Should not benullorempty # Get-process -Name Excel, xlim -ErrorAction SilentlyContinue | Should not benullorempty
# } # }
#Start-Sleep -Seconds 5 ;
Start-Sleep -Seconds 5 ;
#Open-ExcelPackage with -Create is tested in Export-Excel #Open-ExcelPackage with -Create is tested in Export-Excel
#This is a test of using it with -KillExcel #This is a test of using it with -KillExcel
@@ -116,10 +115,10 @@ 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
$returnedRange = Write-Output -1 668 34 777 860 -0.5 119 -0.1 234 788 | 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
$returnedRange | Should be "A1:A10" $returnedRange | Should be "A1:A11"
} }
$Excel = Open-ExcelPackage -Path $path $Excel = Open-ExcelPackage -Path $path
@@ -131,7 +130,7 @@ Describe ExportExcel {
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 1 $ws.Dimension.Columns | Should be 1
$ws.Dimension.Rows | Should be 10 $ws.Dimension.Rows | Should be 11
} }
it "Set the default style for the sheet as expected " { it "Set the default style for the sheet as expected " {
@@ -368,7 +367,7 @@ Describe ExportExcel {
Close-ExcelPackage -ExcelPackage $Excel Close-ExcelPackage -ExcelPackage $Excel
} }
context "#Example 7 # Update-FirstObjectProperties works " { Context "#Example 7 # Update-FirstObjectProperties works " {
$Array = @() $Array = @()
$Obj1 = [PSCustomObject]@{ $Obj1 = [PSCustomObject]@{
@@ -408,7 +407,7 @@ Describe ExportExcel {
#This time we are not deleting the XLSX file so this Should create a new, named, sheet. #This time we are not deleting the XLSX file so this Should create a new, named, sheet.
$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 50 -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 -passthru and adding the Pivot as a second step. Want to save and re-open it ...
Export-Excel -ExcelPackage $Excel -WorkSheetname Processes -IncludePivotTable -PivotRows Company -PivotData PM Export-Excel -ExcelPackage $Excel -WorkSheetname Processes -IncludePivotTable -PivotRows Company -PivotData PM -NoTotalsInPivot
$Excel = Open-ExcelPackage $path $Excel = Open-ExcelPackage $path
$PTws = $Excel.Workbook.Worksheets["ProcessesPivotTable"] $PTws = $Excel.Workbook.Worksheets["ProcessesPivotTable"]
@@ -431,7 +430,7 @@ Describe ExportExcel {
} }
#using the already open sheet add the pivot chart #using the already open sheet add the pivot chart
$warnvar = $null $warnvar = $null
Export-Excel -ExcelPackage $Excel -WorkSheetname Processes -IncludePivotTable -PivotRows Company -PivotData PM -IncludePivotChart -ChartType PieExploded3D -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
it "Added a chart to the pivot table without rebuilding " { it "Added a chart to the pivot table without rebuilding " {
$ws = $Excel.Workbook.Worksheets["ProcessesPivotTable"] $ws = $Excel.Workbook.Worksheets["ProcessesPivotTable"]
@@ -490,21 +489,21 @@ 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"
#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 a command line parameter
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 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 -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 -AutoFilter -AutoNameRange -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]
it "Created and appended to a sheet offset from the top left corner " { it "Created and appended to a sheet offset from the top left corner " {
$dataWs.Cells[1, 1].Value | Should beNullOrEmpty $dataWs.Cells[1, 1].Value | Should beNullOrEmpty
$dataWs.Cells[2, 2].Value | Should beNullOrEmpty $dataWs.Cells[2, 2].Value | Should beNullOrEmpty
$dataWs.Cells[3, 3].Value | Should not beNullOrEmpty $dataWs.Cells[3, 3].Value | Should not beNullOrEmpty
$dataWs.Cells[3, 3].Style.Font.Bold | Should be $true $dataWs.Cells[3, 3].Style.Font.Bold | Should be $true
$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'
@@ -605,7 +604,7 @@ Describe ExportExcel {
Set-Format -Address $sheet.Column(4) -HorizontalAlignment Right -NFormat "#,##0.0" -Bold Set-Format -Address $sheet.Column(4) -HorizontalAlignment Right -NFormat "#,##0.0" -Bold
Set-Format -Address $sheet.Row(1) -Bold -HorizontalAlignment Center Set-Format -Address $sheet.Row(1) -Bold -HorizontalAlignment Center
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 -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 "Processes" -PivotRows Company -PivotData @{'Name' = 'Count'} -IncludePivotChart -ChartType ColumnClustered -NoLegend
Close-ExcelPackage $excel Close-ExcelPackage $excel
@@ -698,10 +697,12 @@ 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"
$excel = 0..360 | ForEach-Object {[pscustomobject][ordered]@{x = $_; Sinx = "=Sin(Radians(x)) "}} | Export-Excel -AutoNameRange -Path $path -WorkSheetname SinX -ClearSheet -PassThru $excel = 0..360 | ForEach-Object {[pscustomobject][ordered]@{x = $_; Sinx = "=Sin(Radians(x)) "}} | Export-Excel -AutoNameRange -Path $path -WorkSheetname SinX -ClearSheet -FreezeFirstColumn -PassThru
Add-ExcelChart -Worksheet $excel.Workbook.Worksheets["Sinx"] -XRange "X" -YRange "Sinx" -Title "Graph of Sine X" -ChartType line -SeriesHeader "Sin(x)" -Column 2 -ColumnOffSetPixels 35 -TitleBold -TitleSize 14 -XAxisTitleText "Degrees" -XAxisTitleBold -XAxisTitleSize 12 -XMajorUnit 30 -XMinorUnit 10 -XMinValue 0 -XMaxValue 361 -Width 800 -YMinValue -1.25 -YMaxValue 1.25 -YMajorUnit 0.25 -YAxisNumberformat "0.00" -LegendPostion Bottom -LegendSize 8 -legendBold 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 `
-YMinValue -1.25 -YMaxValue 1.25 -YMajorUnit 0.25 -YAxisNumberformat "0.00" -YAxisTitleText "Sine" -YAxisTitleBold -YAxisTitleSize 12 -YAxisPosition Left -LegendPostion Bottom -LegendSize 8 -legendBold
$d = $excel.Workbook.Worksheets["Sinx"].Drawings[0] $d = $excel.Workbook.Worksheets["Sinx"].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
$d.XAxis.MinorUnit | Should be 10 $d.XAxis.MinorUnit | Should be 10
@@ -728,6 +729,44 @@ Describe ExportExcel {
Close-ExcelPackage -ExcelPackage $excel -nosave Close-ExcelPackage -ExcelPackage $excel -nosave
} }
Context " # Quick Pie chart and three icon conditional formating" {
$path = "$Env:TEMP\Pie.xlsx"
Remove-Item -Path $path -ErrorAction SilentlyContinue
$range = Get-Process| Group-Object -Property company | Where-Object -Property name |
Select-Object -Property Name, @{n="TotalPm";e={($_.group | Measure-Object -sum -Property pm).sum }} |
Export-Excel -NoHeader -AutoNameRange -path $path -ReturnRange -PieChart -ShowPercent
$Cf = New-ConditionalFormattingIconSet -Range ($range -replace "^.*:","B2:") -ConditionalFormat ThreeIconSet -Reverse -IconType Flags
$ct = New-ConditionalText -Text "Microsoft" -ConditionalTextColor red -BackgroundColor AliceBlue -ConditionalType ContainsText
it "Created the Conditional formatting rules " {
$cf.Formatter | should be "ThreeIconSet"
$cf.IconType | should be "Flags"
$cf.Range | Should be ($range -replace "^.*:","B2:")
$cf.Reverse | Should be $true
$ct.BackgroundColor.Name | Should be "AliceBlue"
$ct.ConditionalTextColor.Name | Should be "Red"
$ct.ConditionalType | Should be "ContainsText"
$ct.Text | Should be "Microsoft"
}
Export-Excel -Path $path -ConditionalFormat $cf -ConditionalText $ct
$excel = Open-ExcelPackage -Path $path
$rows = $range -replace "^.*?(\d+)$", '$1'
$chart = $excel.Workbook.Worksheets["sheet1"].Drawings[0]
$cFmt = $excel.Workbook.Worksheets["sheet1"].ConditionalFormatting
it "Created the chart with the right series " {
$chart.ChartType | should be "PieExploded3D"
$chart.series.series | should be "'Sheet1'!B1:B$rows" #would be B2 and A2 if we had a header.
$chart.series.Xseries | should be "'Sheet1'!A1:A$rows"
$chart.DataLabel.ShowPercent | should be $true
}
it "Created two Conditional formatting rules " {
$cFmt.Count | should be $true
$cFmt.Where({$_.type -eq "ContainsText"}) | Should not beNullOrEmpty
$cFmt.Where({$_.type -eq "ThreeIconSet"}) | Should not beNullOrEmpty
}
}
Context " # Awkward multiple tables" { Context " # Awkward multiple tables" {
$path = "$Env:TEMP\test.xlsx" $path = "$Env:TEMP\test.xlsx"
remove-item -Path $path -ErrorAction SilentlyContinue remove-item -Path $path -ErrorAction SilentlyContinue
@@ -738,7 +777,7 @@ Describe ExportExcel {
Export-Excel -Path $path -TableName FileSize -StartRow 2 -StartColumn 7 -TableStyle Medium2 Export-Excel -Path $path -TableName FileSize -StartRow 2 -StartColumn 7 -TableStyle Medium2
$r.extension | Group-Object | Sort-Object -Property count -Descending | Select-Object -First 12 Name, Count | $r.extension | Group-Object | Sort-Object -Property count -Descending | Select-Object -First 12 Name, Count |
Export-Excel -Path $path -TableName ExtSize -Title "Frequent Extensions" -TitleSize 11 Export-Excel -Path $path -TableName ExtSize -Title "Frequent Extensions" -TitleSize 11 -BoldTopRow
$r | Group-Object -Property extension | Select-Object Name, @{n="Size"; e={($_.group | Measure-Object -property length -sum).sum}} | $r | Group-Object -Property extension | Select-Object Name, @{n="Size"; e={($_.group | Measure-Object -property length -sum).sum}} |
Sort-Object -Property size -Descending | Select-Object -First 10 | Sort-Object -Property size -Descending | Select-Object -First 10 |
@@ -761,11 +800,4 @@ Describe ExportExcel {
} }
} }
## To do
## More Charts , pivot options & other FreezePanes settings ?
## Style script block
## Rezip ?
} }

View File

@@ -0,0 +1,84 @@
$path = "$Env:TEMP\test.xlsx"
Remove-Item -Path $path -ErrorAction SilentlyContinue
$data = ConvertFrom-Csv -InputObject @"
ID,Product,Quantity,Price
12001,Nails,37,3.99
12002,Hammer,5,12.10
12003,Saw,12,15.37
12010,Drill,20,8
12011,Crowbar,7,23.48
"@
Describe "Set-Column, Set-Row and Set Format" {
BeforeAll {
$excel = $data| Export-Excel -Path $path -AutoNameRange -PassThru
$ws = $excel.Workbook.Worksheets["Sheet1"]
Set-Column -Worksheet $ws -Heading "Total" -Value "=Quantity*Price" -NumberFormat "£#,###.00" -FontColor Blue -Bold -HorizontalAlignment Right -VerticalAlignment Top
Set-Row -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 -WorkSheet $ws -Range "E3" -Bold:$false -FontShift Superscript -HorizontalAlignment Left
Set-Format -WorkSheet $ws -Range "E1" -ResetFont -HorizontalAlignment General
Set-Format -Address $ws.cells["E7"] -ResetFont -WrapText -BackgroundColor AliceBlue -BackgroundPattern DarkTrellis -PatternColor Red -NumberFormat "£#,###.00"
Set-Format -Address $ws.Column(1) -Width 0
Set-Format -Address $ws.row(5) -Height 0
Close-ExcelPackage $excel
$excel = Open-ExcelPackage $path
$ws = $excel.Workbook.Worksheets["Sheet1"]
}
Context "Rows and Columns" {
it "Set a row and a column to have zero width/height " {
$ws.Column(1).width | should be 0
$ws.Row(5).height | should be 0
}
it "Set a column formula, with numberformat, color, bold face and alignment" {
$ws.cells["e2"].Formula | Should be "=Quantity*Price"
$ws.cells["e2"].Style.Font.Color.rgb | Should be "FF0000FF"
$ws.cells["e2"].Style.Font.Bold | Should be $true
$ws.cells["e2"].Style.Font.VerticalAlign | Should be "None"
$ws.cells["e2"].Style.Numberformat.format | Should be "£#,###.00"
$ws.cells["e2"].Style.HorizontalAlignment | Should be "Right"
}
}
Context "Other formatting" {
it "Set a row formula with border font size and underline " {
$ws.cells["b7"].style.Border.Top.Style | Should be "None"
$ws.cells["F7"].style.Border.Top.Style | Should be "None"
$ws.cells["C7"].style.Border.Top.Style | Should be "Thin"
$ws.cells["C7"].style.Border.Bottom.Style | Should be "Thin"
$ws.cells["C7"].style.Border.Right.Style | Should be "None"
$ws.cells["C7"].style.Border.Left.Style | Should be "Thin"
$ws.cells["E7"].style.Border.Left.Style | Should be "None"
$ws.cells["E7"].style.Border.Right.Style | Should be "Thin"
$ws.cells["C7"].style.Font.size | Should be 14
$ws.cells["C7"].Formula | Should be "=sum(C2:C6)"
$ws.cells["C7"].style.Font.UnderLine | Should be $true
$ws.cells["C6"].style.Font.UnderLine | Should be $false
}
it "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"
}
}
}