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]) {
$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 {
$xyRange = Get-XYRange $targetData
@@ -19,7 +19,7 @@ function DoChart {
$Y = $xyRange.YRange.ExcelColumn
$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
}

View File

@@ -10,6 +10,7 @@ if (Get-Command -Name register-argumentCompleter -ErrorAction SilentlyContinue)
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 ForeGroundColor -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 FontColor -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 DeleteBackgroundColor -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 FontColor -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
$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 `
-Header "Stuff" `
-XRange "Processes[Company]" `
-YRange "Processes[PM]","Processes[VirtualMemorySize]"
-XRange "Processes[Name]" `
-YRange "Processes[PM]","Processes[VirtualMemorySize]" `
-SeriesHeader "PM","VM"
$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
2,1,1,2016-03-29
5,10,1,2016-03-29
"@ | ConvertFrom-Csv
"@
$c = New-ExcelChart -Title Impressions `
-ChartType Line -Header "Something" `
$c = New-ExcelChartDefinition -Title Impressions `
-ChartType Line `
-XRange "Impressions[Date]" `
-YRange @("Impressions[B]","Impressions[A]") `
-SeriesHeader 'B data','A data'
-YRange "Impressions[B]" # @("Impressions[B]","Impressions[A]") `
-SeriesHeader 'B data','A data' `
-Row 0 -Column 0
$data |
Export-Excel temp.xlsx -AutoSize -TableName Impressions -Show -ExcelChartDefinition $c
$data | ConvertFrom-Csv | Export-Excel -path temp.xlsx -AutoSize -TableName Impressions
Export-Excel -path temp.xlsx -worksheetName chartPage -ExcelChartDefinition $c -show

View File

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

View File

@@ -869,10 +869,12 @@
yrange = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R[$FirstDataRow]C[$ycol]:R[$($lastrow)]C[$ycol]",0,0) ;
title = "";
Column = ($lastCol +1) ;
Width = 1200
Width = 800
}
if ($NoHeader) {$params["NoHeader"] = $true}
else {$Params["SeriesHeader"] = $ws.Cells[$startRow, $YCol].Value}
if ($ShowPercent) {$params["ShowPercent"] = $true}
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" }
elseif ($Barchart) {$Params["chartType"] = "BarStacked" }
elseif ($PieChart) {$Params["chartType"] = "PieExploded3D" }
@@ -1309,7 +1311,7 @@ function Add-ExcelChart {
if ($XAxisTitleBold) {$chart.XAxis.Title.Font.Bold = $true}
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 ($XMinorUnit) {$chart.XAxis.MinorUnit = $XMinorUnit}
if ($null -ne $XMinValue) {$chart.XAxis.MinValue = $XMinValue}
@@ -1321,7 +1323,7 @@ function Add-ExcelChart {
if ($YAxisTitleBold) {$chart.YAxis.Title.Font.Bold = $true}
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 ($YMinorUnit) {$chart.YAxis.MinorUnit = $YMinorUnit}
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')
```
# 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
- 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.

View File

@@ -102,7 +102,7 @@
if ($AutoNameRange) { $Worksheet.Names.Add( $heading, ($Worksheet.Cells[$startrow, $Column, $endRow, $Column]) ) | Out-Null }
}
#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.
$cellData = & ([scriptblock]::create( $Value ))
Write-Verbose -Message $cellData
@@ -113,28 +113,15 @@
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
if ($Underline) {
$Worksheet.Column( $Column).Style.Font.UnderLine = $true
$Worksheet.Column( $Column).Style.Font.UnderLineType = $UnderLineType
$params = @{}
foreach ($p in @('Underline','Bold','Italic','StrikeThru','FontSize','FontShift','NumberFormat','TextRotation',
'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 ($Italic) { $Worksheet.Column( $Column).Style.Font.Italic = $true }
if ($StrikeThru) { $Worksheet.Column( $Column).Style.Font.Strike = $true }
if ($FontShift) { $Worksheet.Column( $Column).Style.Font.VerticalAlign = $FontShift }
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 ($params.Count) {
Set-Format -WorkSheet $Worksheet -Range "$ColumnName$startRow`:$ColumnName$endRow" @params
}
if ($Autosize) { $Worksheet.Column( $Column).AutoFit() }
elseif ($Width) { $Worksheet.Column( $Column).Width = $Width }
#endregion
#return the new data if -passthru was specified.
if ($passThru) { $Worksheet.Column( $Column)}

View File

@@ -100,7 +100,7 @@
$StartColumn ++
}
#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
$ColumnName = [OfficeOpenXml.ExcelCellAddress]::new(1,$column).Address -replace "1",""
if ($Value -is [scriptblock] ) {
@@ -110,30 +110,19 @@
}
else{$cellData = $Value}
if ($cellData -match "^=") { $Worksheet.Cells[$Row, $column].Formula = $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.
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.
}}
#region Apply formatting
if ($Underline) {
$worksheet.row( $Row ).Style.Font.UnderLine = $true
$worksheet.row( $Row ).Style.Font.UnderLineType = $UnderLineType
$params = @{}
foreach ($p in @('Underline','Bold','Italic','StrikeThru','FontSize', 'FontShift','NumberFormat','TextRotation',
'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 ($Italic) { $worksheet.row( $Row ).Style.Font.Italic = $true }
if ($StrikeThru) { $worksheet.row( $Row ).Style.Font.Strike = $true }
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 ) }
if ($params.Count) {
$theRange = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R[$Row]C[$StartColumn]:R[$Row]C[$EndColumn]",0,0)
Set-Format -WorkSheet $Worksheet -Range $theRange @params
}
#endregion
#return the new data if -passthru was specified.

View File

@@ -98,53 +98,76 @@
$Address.Style.Font.UnderLine = $false
$Address.Style.Font.Strike = $false
}
if ($Underline) {
$Address.Style.Font.UnderLine = $true
if ($PSBoundParameters.ContainsKey('Underline')) {
$Address.Style.Font.UnderLine = [boolean]$Underline
$Address.Style.Font.UnderLineType = $UnderLineType
}
if ($Bold) {$Address.Style.Font.Bold = $true }
if ($Italic) {$Address.Style.Font.Italic = $true }
if ($StrikeThru) {$Address.Style.Font.Strike = $true }
if ($FontShift) {$Address.Style.Font.VerticalAlign = $FontShift }
if ($FontColor) {$Address.Style.Font.Color.SetColor( $FontColor ) }
if ($NumberFormat) {$Address.Style.Numberformat.Format = $NumberFormat }
if ($TextRotation) {$Address.Style.TextRotation = $TextRotation }
if ($WrapText) {$Address.Style.WrapText = $true }
if ($HorizontalAlignment) {$Address.Style.HorizontalAlignment = $HorizontalAlignment }
if ($VerticalAlignment) {$Address.Style.VerticalAlignment = $VerticalAlignment }
if ($Value) {$Address.Value = $Value }
if ($Formula) {$Address.Formula = $Formula }
if ($BorderAround) {$Address.Style.Border.BorderAround($BorderAround, $BorderColor)}
if ($BorderBottom) {
if ($PSBoundParameters.ContainsKey('Bold')) {
$Address.Style.Font.Bold = [boolean]$bold
}
if ($PSBoundParameters.ContainsKey('Italic')) {
$Address.Style.Font.Italic = [boolean]$italic
}
if ($PSBoundParameters.ContainsKey('StrikeThru')) {
$Address.Style.Font.Strike = [boolean]$StrikeThru
}
if ($PSBoundParameters.ContainsKey('FontSize')){
$Address.Style.Font.Size = $FontSize
}
if ($PSBoundParameters.ContainsKey('FontShift')){
$Address.Style.Font.VerticalAlign = $FontShift
}
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.Color.SetColor($BorderColor)
}
if ($BorderTop) {
if ($PSBoundParameters.ContainsKey('BorderTop')) {
$Address.Style.Border.Top.Style=$BorderTop
$Address.Style.Border.Top.Color.SetColor($BorderColor)
}
if ($BorderLeft) {
if ($PSBoundParameters.ContainsKey('BorderLeft')) {
$Address.Style.Border.Left.Style=$BorderLeft
$Address.Style.Border.Left.Color.SetColor($BorderColor)
}
if ($BorderRight) {
if ($PSBoundParameters.ContainsKey('BorderRight')) {
$Address.Style.Border.Right.Style=$BorderRight
$Address.Style.Border.Right.Color.SetColor($BorderColor)
}
if ($BackgroundColor) {
if ($PSBoundParameters.ContainsKey('BackgroundColor')) {
$Address.Style.Fill.PatternType = $BackgroundPattern
$Address.Style.Fill.BackgroundColor.SetColor($BackgroundColor)
if ($PatternColor) {
$Address.Style.Fill.PatternColor.SetColor( $PatternColor)
}
}
if ($Height) {
if ($PSBoundParameters.ContainsKey('Height')) {
if ($Address -is [OfficeOpenXml.ExcelRow] ) {$Address.Height = $Height }
elseif ($Address -is [OfficeOpenXml.ExcelRange] ) {
($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)) }
}
elseif ($Width) {
elseif ($PSBoundParameters.ContainsKey('Width')) {
if ($Address -is [OfficeOpenXml.ExcelColumn]) {$Address.Width = $Width}
elseif ($Address -is [OfficeOpenXml.ExcelRange] ) {
($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)) }
}
if ($Hidden) {
if ($PSBoundParameters.ContainsKey('$Hidden')) {
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)) }
}

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 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, Copy-ExcelWorkSheet.ps1 (probably re-write copy)
- [ ] 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
[ ] Copy parameter help from function Add-ExcelChart into New-ExcelChart.ps1
- [ ] Examples and tests for new "Quick charts" in Export Excel
- [ ] Charting.ps1,GetXYRange.ps1, InferData.PS1 move to deprecated. (replace examples)
- [ ] 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
- [ ] 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).
- [ ] Refactor Set-Row and Set-Column to use set-format and add conditional format and return range support.
- [ ] Examples and tests for set-Row and Set-column
- [ ] Add PivotTable can't select sheet by position.

View File

@@ -5,7 +5,7 @@ Describe "Compare Worksheet" {
Context "Simple comparison output" {
BeforeAll {
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 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
@@ -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 {
$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"
$xl2 = Open-ExcelPackage -Path "$env:temp\Server2.xlsx"
$s1Sheet = $xl1.Workbook.Worksheets[1]
@@ -104,7 +105,7 @@ Describe "Compare Worksheet" {
Context "More complex comparison: output check and different worksheet names " {
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 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
@@ -177,7 +178,7 @@ Describe "Merge Worksheet" {
Context "Merge with 3 properties" {
BeforeAll {
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
@@ -243,7 +244,7 @@ Describe "Merge Multiple sheets" {
Context "Merge 3 sheets with 3 properties" {
BeforeAll {
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 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"
$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

View File

@@ -22,8 +22,7 @@ Describe ExportExcel {
# it "Started Excel to display the file " {
# 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
#This is a test of using it with -KillExcel
@@ -116,10 +115,10 @@ Describe ExportExcel {
$path = "$env:TEMP\Test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue
#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 " {
Test-Path -Path $path -ErrorAction SilentlyContinue | Should be $true
$returnedRange | Should be "A1:A10"
$returnedRange | Should be "A1:A11"
}
$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 " {
$ws.Name | Should be "sheet1"
$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 " {
@@ -368,7 +367,7 @@ Describe ExportExcel {
Close-ExcelPackage -ExcelPackage $Excel
}
context "#Example 7 # Update-FirstObjectProperties works " {
Context "#Example 7 # Update-FirstObjectProperties works " {
$Array = @()
$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.
$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 ...
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
$PTws = $Excel.Workbook.Worksheets["ProcessesPivotTable"]
@@ -431,7 +430,7 @@ Describe ExportExcel {
}
#using the already open sheet add the pivot chart
$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
it "Added a chart to the pivot table without rebuilding " {
$ws = $Excel.Workbook.Worksheets["ProcessesPivotTable"]
@@ -490,13 +489,13 @@ 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"
#Catch warning
$warnVar = $null
#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 -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 -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
$Excel = Open-ExcelPackage $path
$dataWs = $Excel.Workbook.Worksheets["withOffset"]
$pt = $Excel.Workbook.Worksheets["PTOffset"].PivotTables[0]
@@ -605,7 +604,7 @@ Describe ExportExcel {
Set-Format -Address $sheet.Column(4) -HorizontalAlignment Right -NFormat "#,##0.0" -Bold
Set-Format -Address $sheet.Row(1) -Bold -HorizontalAlignment Center
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 }
Add-PivotTable -PivotTableName "PT_Procs" -ExcelPackage $excel -SourceWorkSheet "Processes" -PivotRows Company -PivotData @{'Name' = 'Count'} -IncludePivotChart -ChartType ColumnClustered -NoLegend
Close-ExcelPackage $excel
@@ -698,8 +697,10 @@ Describe ExportExcel {
Context " # variation of plot.ps1 from Examples Directory using Add chart outside ExportExcel" {
$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
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
$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"] -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]
It "Controled the axes and title and legend of the chart " {
$d.XAxis.MaxValue | Should be 361
@@ -728,6 +729,44 @@ Describe ExportExcel {
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" {
$path = "$Env:TEMP\test.xlsx"
remove-item -Path $path -ErrorAction SilentlyContinue
@@ -738,7 +777,7 @@ Describe ExportExcel {
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 |
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}} |
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"
}
}
}