mirror of
https://github.com/dfinke/ImportExcel.git
synced 2025-12-10 21:33:16 +00:00
Merge pull request #405 from jhoneill/master
Internal hyperlinks, reworked format parameters, unhide in export Excel
This commit is contained in:
@@ -15,7 +15,14 @@
|
||||
The desired worksheet is selected and the then columns B and i are conditially formatted (excluding the top row) to show red text if
|
||||
the columns contain "2003" or "Disabled respectively. A fixed date formats are then applied to columns D..G, and the top row is formatted.
|
||||
Finally the workbook is saved and the Excel object closed.
|
||||
.Example
|
||||
C:\> $r = Add-ConditionalFormatting -WorkSheet $excel.Workbook.Worksheets[1] -Range "B1:B100" -ThreeIconsSet Flags -Passthru
|
||||
C:\> $r.Reverse = $true ; $r.Icon1.Type = "Num"; $r.Icon2.Type = "Num" ; $r.Icon2.value = 100 ; $r.Icon3.type = "Num" ;$r.Icon3.value = 1000
|
||||
|
||||
Again Export excel has been called with -passthru leaving a package object in $Excel
|
||||
This time B1:B100 has been conditionally formatted with 3 icons, using the flags icon set.
|
||||
Add-ConditionalFormatting does not provide access to every option in the formatting rule, so passthru has been used and the
|
||||
rule is to apply the flags in reverse order, and boundaries for the number which will set the split are set to 100 and 1000
|
||||
#>
|
||||
Param (
|
||||
#The worksheet where the format is to be applied
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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,8 +23,11 @@ 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 BorderColor -ScriptBlock $Function:ColorCompletion
|
||||
Register-ArgumentCompleter -CommandName Set-Format -ParameterName PatternColor -ScriptBlock $Function:ColorCompletion
|
||||
Register-ArgumentCompleter -CommandName Set-Column -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion
|
||||
Register-ArgumentCompleter -CommandName Set-Column -ParameterName FontColor -ScriptBlock $Function:ColorCompletion
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -88,7 +88,9 @@
|
||||
.PARAMETER ExcelChartDefinition
|
||||
A hash table containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-pivot] charts.
|
||||
.PARAMETER HideSheet
|
||||
Name(s) of Sheet(s) to hide in the workbook.
|
||||
Name(s) of Sheet(s) to hide in the workbook, supports wildcards. If all sheets would be hidden, the sheet being worked on will be revealed .
|
||||
.PARAMETER UnHideSheet
|
||||
Name(s) of Sheet(s) to Reveal in the workbook, supports wildcards.
|
||||
.PARAMETER MoveToStart
|
||||
If specified, the worksheet will be moved to the start of the workbook.
|
||||
MoveToStart takes precedence over MoveToEnd, Movebefore and MoveAfter if more than one is specified.
|
||||
@@ -425,6 +427,7 @@
|
||||
[Switch]$ColumnChart ,
|
||||
[Object[]]$ExcelChartDefinition,
|
||||
[String[]]$HideSheet,
|
||||
[String[]]$UnHideSheet,
|
||||
[Switch]$MoveToStart,
|
||||
[Switch]$MoveToEnd,
|
||||
$MoveBefore ,
|
||||
@@ -493,9 +496,14 @@
|
||||
break
|
||||
}
|
||||
{ [System.Uri]::IsWellFormedUriString($_ , [System.UriKind]::Absolute) } {
|
||||
# Save a hyperlink
|
||||
$TargetCell.Value = $_.AbsoluteUri
|
||||
$TargetCell.HyperLink = $_
|
||||
# Save a hyperlink : internal links can be in the form xl://sheet!E419 (use A1 as goto sheet), or xl://RangeName
|
||||
if ($_ -match "^xl://internal/") {
|
||||
$referenceAddress = $_ -replace "^xl://internal/" , ""
|
||||
$display = $referenceAddress -replace "!A1$" , ""
|
||||
$h = New-Object -TypeName OfficeOpenXml.ExcelHyperLink -ArgumentList $referenceAddress , $display
|
||||
$TargetCell.HyperLink = $h
|
||||
}
|
||||
else {$TargetCell.HyperLink = $_ } #$TargetCell.Value = $_.AbsoluteUri
|
||||
$TargetCell.Style.Font.Color.SetColor([System.Drawing.Color]::Blue)
|
||||
$TargetCell.Style.Font.UnderLine = $true
|
||||
#Write-Verbose "Cell '$Row`:$ColumnIndex' header '$Name' add value '$($_.AbsoluteUri)' as Hyperlink"
|
||||
@@ -841,11 +849,26 @@
|
||||
|
||||
foreach ($Sheet in $HideSheet) {
|
||||
try {
|
||||
$pkg.Workbook.WorkSheets[$Sheet].Hidden = 'Hidden'
|
||||
Write-verbose -Message "Sheet '$sheet' Hidden."
|
||||
$pkg.Workbook.WorkSheets.Where({$_.Name -like $sheet}) | ForEach-Object {
|
||||
$_.Hidden = 'Hidden'
|
||||
Write-verbose -Message "Sheet '$($_.Name)' Hidden."
|
||||
}
|
||||
}
|
||||
catch {Write-Warning -Message "Failed hiding worksheet '$sheet': $_"}
|
||||
}
|
||||
foreach ($Sheet in $UnHideSheet) {
|
||||
try {
|
||||
$pkg.Workbook.WorkSheets.Where({$_.Name -like $sheet}) | ForEach-Object {
|
||||
$_.Hidden = 'Visible'
|
||||
Write-verbose -Message "Sheet '$($_.Name)' shown"
|
||||
}
|
||||
}
|
||||
catch {Write-Warning -Message "Failed showing worksheet '$sheet': $_"}
|
||||
}
|
||||
if (-not $pkg.Workbook.Worksheets.Where({$_.Hidden -eq 'visible'})) {
|
||||
Write-Verbose -Message "No Sheets were left visible, making $WorkSheetname visible"
|
||||
$ws.Hidden = 'Visible'
|
||||
}
|
||||
|
||||
foreach ($chartDef in $ExcelChartDefinition) {
|
||||
$params = @{}
|
||||
@@ -864,10 +887,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" }
|
||||
@@ -1171,6 +1196,9 @@ function Add-PivotTable {
|
||||
if ($SourceWorkSheet -is [string]) {
|
||||
$SourceWorkSheet = $ExcelPackage.Workbook.Worksheets.where( {$_.name -match $SourceWorkSheet})[0]
|
||||
}
|
||||
elseif ($SourceWorkSheet -is [int]) {
|
||||
$SourceWorkSheet = $ExcelPackage.Workbook.Worksheets[$SourceWorkSheet]
|
||||
}
|
||||
if (-not ($SourceWorkSheet -is [OfficeOpenXml.ExcelWorksheet])) {Write-Warning -Message "Could not find source Worksheet for pivot-table '$pivotTableName'." }
|
||||
else {
|
||||
if ($PivotFilter) {$PivotTableStartCell = "A3"} else { $PivotTableStartCell = "A1"}
|
||||
@@ -1304,7 +1332,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}
|
||||
@@ -1316,7 +1344,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}
|
||||
|
||||
@@ -40,17 +40,17 @@
|
||||
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderAround,
|
||||
#Colour for the text - if none specified it will be left as it it is
|
||||
[System.Drawing.Color]$FontColor,
|
||||
#Make text bold
|
||||
#Make text bold; use -Bold:$false to remove bold
|
||||
[switch]$Bold,
|
||||
#Make text italic
|
||||
#Make text italic; use -Italic:$false to remove italic
|
||||
[switch]$Italic,
|
||||
#Underline the text using the underline style in -underline type
|
||||
#Underline the text using the underline style in -underline type; use -Underline:$false to remove underlining
|
||||
[switch]$Underline,
|
||||
#Should Underline use single or double, normal or accounting mode : default is single normal
|
||||
[OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single,
|
||||
#StrikeThrough text
|
||||
#Strike through text; use -Strikethru:$false to remove Strike through
|
||||
[switch]$StrikeThru,
|
||||
#Subscript or superscript
|
||||
#Subscript or superscript (or none)
|
||||
[OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift,
|
||||
#Font to use - Excel defaults to Calibri
|
||||
[String]$FontName,
|
||||
@@ -63,9 +63,9 @@
|
||||
#Secondary colour for background pattern
|
||||
[Alias("PatternColour")]
|
||||
[System.Drawing.Color]$PatternColor,
|
||||
#Turn on text wrapping
|
||||
#Turn on text wrapping; use -WrapText:$false to turn off word wrapping
|
||||
[switch]$WrapText,
|
||||
#Position cell contents to left, right or centre ...
|
||||
#Position cell contents to left, right, center etc. default is 'General'
|
||||
[OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment,
|
||||
#Position cell contents to top bottom or centre
|
||||
[OfficeOpenXml.Style.ExcelVerticalAlignment]$VerticalAlignment,
|
||||
@@ -79,6 +79,8 @@
|
||||
[float]$Width,
|
||||
#Set the inserted data to be a named range (ignored if header is not specified)
|
||||
[Switch]$AutoNameRange,
|
||||
#If Sepecified returns the range of cells which affected
|
||||
[switch]$ReturnRange,
|
||||
#If Specified, return an ExcelPackage object to allow further work to be done on the file.
|
||||
[switch]$PassThru
|
||||
)
|
||||
@@ -102,7 +104,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,29 +115,18 @@
|
||||
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 ) }
|
||||
$theRange = "$ColumnName$startRow`:$ColumnName$endRow"
|
||||
if ($params.Count) {
|
||||
Set-Format -WorkSheet $Worksheet -Range $theRange @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)}
|
||||
elseif ($ReturnRange) { $theRange}
|
||||
}
|
||||
58
Set-Row.ps1
58
Set-Row.ps1
@@ -1,7 +1,7 @@
|
||||
Function Set-Row {
|
||||
<#
|
||||
.Synopsis
|
||||
Fills values into a row in a Excel spreadsheet
|
||||
Fills values into a [new] row in an Excel spreadsheet. To format a row without setting values, use Set-Format.
|
||||
.Description
|
||||
Set-Row accepts either a Worksheet object or an Excel package object returned by Export-Excel and the name of a sheet,
|
||||
and inserts the chosen contents into a row of the sheet.
|
||||
@@ -37,26 +37,25 @@
|
||||
$Value,
|
||||
#Optional Row heading
|
||||
$Heading ,
|
||||
#Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc
|
||||
#Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc
|
||||
[Alias("NFormat")]
|
||||
$NumberFormat,
|
||||
#Style of border to draw around the row
|
||||
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderAround,
|
||||
#Colour for the text - if none specified it will be left as it it is
|
||||
[System.Drawing.Color]$FontColor,
|
||||
#Make text bold
|
||||
#Make text bold; use -Bold:$false to remove bold
|
||||
[switch]$Bold,
|
||||
#Make text italic
|
||||
#Make text italic; use -Italic:$false to remove italic
|
||||
[switch]$Italic,
|
||||
#Underline the text using the underline style in -underline type
|
||||
#Underline the text using the underline style in -underline type; use -Underline:$false to remove underlining
|
||||
[switch]$Underline,
|
||||
#Should Underline use single or double, normal or accounting mode : default is single normal
|
||||
[OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single,
|
||||
#StrikeThrough text
|
||||
#Strike through text; use -Strikethru:$false to remove Strike through
|
||||
[switch]$StrikeThru,
|
||||
#Subscript or superscript
|
||||
#Subscript or superscript (or none)
|
||||
[OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift,
|
||||
#Font to use - Excel defaults to Calibri
|
||||
[String]$FontName,
|
||||
#Point size for the text
|
||||
[float]$FontSize,
|
||||
@@ -67,9 +66,9 @@
|
||||
#Secondary colour for background pattern
|
||||
[Alias("PatternColour")]
|
||||
[System.Drawing.Color]$PatternColor,
|
||||
#Turn on text wrapping
|
||||
#Turn on text wrapping; use -WrapText:$false to turn off word wrapping
|
||||
[switch]$WrapText,
|
||||
#Position cell contents to left, right or centre ...
|
||||
#Position cell contents to left, right, center etc. default is 'General'
|
||||
[OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment,
|
||||
#Position cell contents to top bottom or centre
|
||||
[OfficeOpenXml.Style.ExcelVerticalAlignment]$VerticalAlignment,
|
||||
@@ -78,7 +77,9 @@
|
||||
[int]$TextRotation ,
|
||||
#Set cells to a fixed hieght
|
||||
[float]$Height,
|
||||
#If Specified, return an ExcelPackage object to allow further work to be done on the file
|
||||
#If Sepecified returns the range of cells which affected
|
||||
[switch]$ReturnRange,
|
||||
#If Specified, return a row object to allow further work to be done
|
||||
[switch]$PassThru
|
||||
)
|
||||
|
||||
@@ -92,7 +93,6 @@
|
||||
$endColumn = $Worksheet.Dimension.End.Column
|
||||
$endRow = $Worksheet.Dimension.End.Row
|
||||
if ($Row -lt 2 ) {$Row = $endRow + 1 }
|
||||
|
||||
Write-Verbose -Message "Updating Row $Row"
|
||||
#Add a row label
|
||||
if ($Heading) {
|
||||
@@ -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,32 +110,22 @@
|
||||
}
|
||||
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 ) }
|
||||
$theRange = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R[$Row]C[$StartColumn]:R[$Row]C[$EndColumn]",0,0)
|
||||
if ($params.Count) {
|
||||
Set-Format -WorkSheet $Worksheet -Range $theRange @params
|
||||
}
|
||||
#endregion
|
||||
#return the new data if -passthru was specified.
|
||||
if ($passThru) {$Worksheet.Row($Row)}
|
||||
elseif ($ReturnRange) {$theRange}
|
||||
}
|
||||
101
SetFormat.ps1
101
SetFormat.ps1
@@ -38,17 +38,17 @@
|
||||
$Formula,
|
||||
#Clear Bold, Italic, StrikeThrough and Underline and set colour to black
|
||||
[switch]$ResetFont,
|
||||
#Make text bold
|
||||
#Make text bold; use -Bold:$false to remove bold
|
||||
[switch]$Bold,
|
||||
#Make text italic
|
||||
#Make text italic; use -Italic:$false to remove italic
|
||||
[switch]$Italic,
|
||||
#Underline the text using the underline style in -underline type
|
||||
#Underline the text using the underline style in -underline type; use -Underline:$false to remove underlining
|
||||
[switch]$Underline,
|
||||
#Should Underline use single or double, normal or accounting mode : default is single normal
|
||||
[OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single,
|
||||
#StrikeThrough text
|
||||
#Strike through text; use -Strikethru:$false to remove Strike through
|
||||
[switch]$StrikeThru,
|
||||
#Subscript or superscript
|
||||
#Subscript or superscript (or none)
|
||||
[OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift,
|
||||
#Font to use - Excel defaults to Calibri
|
||||
[String]$FontName,
|
||||
@@ -61,11 +61,11 @@
|
||||
#Secondary colour for background pattern
|
||||
[Alias("PatternColour")]
|
||||
[System.Drawing.Color]$PatternColor,
|
||||
#Turn on text wrapping
|
||||
#Turn on text wrapping; use -WrapText:$false to turn off word wrapping
|
||||
[switch]$WrapText,
|
||||
#Position cell contents to left, right or centre ...
|
||||
#Position cell contents to left, right, center etc. default is 'General'
|
||||
[OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment,
|
||||
#Position cell contents to top bottom or centre
|
||||
#Position cell contents to top bottom or center
|
||||
[OfficeOpenXml.Style.ExcelVerticalAlignment]$VerticalAlignment,
|
||||
#Degrees to rotate text. Up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise.
|
||||
[ValidateRange(-90, 90)]
|
||||
@@ -77,7 +77,7 @@
|
||||
[float]$Width,
|
||||
#Set cells to a fixed hieght (rows or ranges only)
|
||||
[float]$Height,
|
||||
#Hide a row or column (not a range)
|
||||
#Hide a row or column (not a range); use -Hidden:$false to unhide
|
||||
[switch]$Hidden
|
||||
)
|
||||
begin {
|
||||
@@ -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)) }
|
||||
}
|
||||
|
||||
|
||||
16
ToDo.md
16
ToDo.md
@@ -1,11 +1,11 @@
|
||||
- [ ] Create an autocomplete for WorkSheetName param on ImportExcel
|
||||
- [ ] Create an autocomplete for WorkSheetName param on ImportExcel and for number format ; where number format exists Translate "Date", "DateTime", "Currency"
|
||||
|
||||
- [ ] 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, 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).
|
||||
- [ ] Test Add PivotTable selecting source sheet by position , UnhideSheet, and Wildcard support for hideSheet
|
||||
- [ ] Test return range support to Set-Row and Set-Column and add examples to examples for set-Row and Set-column set-format, add-Conditional format (e.g. from tests)
|
||||
- [ ] Increase code covereage for import-excel and Set-Format
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -223,7 +224,7 @@ Describe "Merge Worksheet" {
|
||||
$ws.cells[5,1].Style.font.color.rgb | Should be "FF8b0000"
|
||||
$ws.cells[7,1].Style.font.color.rgb | Should be "FF8b0000"
|
||||
}
|
||||
it "Set the background for the added / deleted /changed rows " {
|
||||
it "Set the background for the added / deleted / changed rows " {
|
||||
$ws.cells["A3:E3"].style.Fill.BackgroundColor.Rgb | Should beNullOrEmpty
|
||||
$ws.cells["A4:E4"].style.Fill.BackgroundColor.Rgb | Should be "FFFFA500"
|
||||
$ws.cells["A5" ].style.Fill.BackgroundColor.Rgb | Should be "FF98FB98"
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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 " {
|
||||
@@ -171,8 +170,10 @@ Describe ExportExcel {
|
||||
StrAltPhone2 = '+3244444444'
|
||||
StrLeadSpace = ' 123'
|
||||
StrTrailSpace = '123 '
|
||||
Link1 = [uri]"https://github.com/dfinke/ImportExcel" #2,15
|
||||
Link2 = "https://github.com/dfinke/ImportExcel" #2, 16
|
||||
Link1 = [uri]"https://github.com/dfinke/ImportExcel"
|
||||
Link2 = "https://github.com/dfinke/ImportExcel"
|
||||
Link3 = "xl://internal/sheet1!A1"
|
||||
Link4 = "xl://internal/sheet1!C5"
|
||||
} | Export-Excel -NoNumberConversion IPAddress, StrLeadZero, StrAltPhone2 -Path $path
|
||||
it "Created a new file " {
|
||||
Test-Path -Path $path -ErrorAction SilentlyContinue | Should be $true
|
||||
@@ -184,7 +185,7 @@ Describe ExportExcel {
|
||||
$ws = $Excel.Workbook.Worksheets[1]
|
||||
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 22
|
||||
$ws.Dimension.Columns | Should be 24
|
||||
$ws.Dimension.Rows | Should be 2
|
||||
}
|
||||
it "Set a date in Cell A2 " {
|
||||
@@ -206,10 +207,18 @@ Describe ExportExcel {
|
||||
$ws.Cells[2, 12].Value | Should beLessThan 0
|
||||
$ws.Cells[2, 13].Value | Should beLessThan 0
|
||||
}
|
||||
it "Set hyperlinks in Cells U2 and V2 " {
|
||||
it "Set external hyperlinks in Cells U2 and V2 " {
|
||||
$ws.Cells[2, 21].Hyperlink | Should be "https://github.com/dfinke/ImportExcel"
|
||||
$ws.Cells[2, 22].Hyperlink | Should be "https://github.com/dfinke/ImportExcel"
|
||||
}
|
||||
it "Set internal hyperlinks in Cells W2 and X2 " {
|
||||
$ws.Cells[2, 23].Hyperlink.Scheme | Should be "xl"
|
||||
$ws.Cells[2, 23].Hyperlink.ReferenceAddress | Should be "sheet1!A1"
|
||||
$ws.Cells[2, 23].Hyperlink.Display | Should be "sheet1"
|
||||
$ws.Cells[2, 24].Hyperlink.Scheme | Should be "xl"
|
||||
$ws.Cells[2, 24].Hyperlink.ReferenceAddress | Should be "sheet1!c5"
|
||||
$ws.Cells[2, 24].Hyperlink.Display | Should be "sheet1!c5"
|
||||
}
|
||||
it "Processed thousands according to local settings (Cells H2 and I2) " {
|
||||
if ((Get-Culture).NumberFormat.NumberGroupSeparator -EQ ",") {
|
||||
($ws.Cells[2, 8].Value -is [valuetype] ) | Should be $true
|
||||
@@ -293,8 +302,6 @@ Describe ExportExcel {
|
||||
}
|
||||
|
||||
Context "#Example 5 # Adding a single conditional format " {
|
||||
### TODO New-ConditionalText doesn't a lot of options in Add-ConditionalFormat.
|
||||
# It would be good to pull the logic out of Export-Excel and have EE call Add-ConditionalFormat.
|
||||
$ct = New-ConditionalText -ConditionalType GreaterThan 525 -ConditionalTextColor DarkRed -BackgroundColor LightPink
|
||||
it "Created a Conditional format description " {
|
||||
$ct.BackgroundColor -is [System.Drawing.Color] | Should be $true
|
||||
@@ -358,7 +365,7 @@ Describe ExportExcel {
|
||||
Close-ExcelPackage -ExcelPackage $Excel
|
||||
}
|
||||
|
||||
context "#Example 7 # Update-FirstObjectProperties works " {
|
||||
Context "#Example 7 # Update-FirstObjectProperties works " {
|
||||
$Array = @()
|
||||
|
||||
$Obj1 = [PSCustomObject]@{
|
||||
@@ -398,7 +405,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"]
|
||||
@@ -421,7 +428,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"]
|
||||
@@ -480,13 +487,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]
|
||||
@@ -595,14 +602,19 @@ 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
|
||||
$rule = Add-ConditionalFormatting -passthru -Address $sheet.cells["C:C"] -RuleType TopPercent -ConditionValue 20 -Bold -StrikeThru
|
||||
Add-ConditionalFormatting -WorkSheet $sheet -Range "G2:G1048576" -RuleType GreaterThan -ConditionValue "104857600" -ForeGroundColor Red -Bold -Italic -Underline -BackgroundColor Beige -BackgroundPattern LightUp -PatternColor Gray
|
||||
foreach ($c in 5..9) {Set-Format $sheet.Column($c) -AutoFit }
|
||||
Add-PivotTable -PivotTableName "PT_Procs" -ExcelPackage $excel -SourceWorkSheet "Processes" -PivotRows Company -PivotData @{'Name' = 'Count'} -IncludePivotChart -ChartType ColumnClustered -NoLegend
|
||||
Close-ExcelPackage $excel
|
||||
|
||||
$excel = Open-ExcelPackage $path
|
||||
$sheet = $excel.Workbook.Worksheets["Processes"]
|
||||
|
||||
it "Returned the rule when calling Add-ConditionalFormatting -passthru " {
|
||||
$rule | should not beNullOrEmpty
|
||||
$rule.getType().fullname | should be "OfficeOpenXml.ConditionalFormatting.ExcelConditionalFormattingTopPercent"
|
||||
$rule.Style.Font.Strike | should be true
|
||||
}
|
||||
it "Applied the formating " {
|
||||
$sheet | Should not beNullOrEmpty
|
||||
$sheet.Column(1).wdith | Should not be $sheet.DefaultColWidth
|
||||
@@ -619,13 +631,15 @@ Describe ExportExcel {
|
||||
$sheet.Cells['E2'].style.numberformat.format | Should be '#,###'
|
||||
$sheet.Column(3).style.numberformat.format | Should be '#,###'
|
||||
$sheet.Column(4).style.numberformat.format | Should be '#,##0.0'
|
||||
$sheet.ConditionalFormatting.Count | Should be 2
|
||||
$sheet.ConditionalFormatting.Count | Should be 3
|
||||
$sheet.ConditionalFormatting[0].type | Should be 'Databar'
|
||||
$sheet.ConditionalFormatting[0].Color.name | Should be 'ffff0000'
|
||||
$sheet.ConditionalFormatting[0].Address.Address | Should be 'D2:D1048576'
|
||||
$sheet.ConditionalFormatting[1].type | Should be 'GreaterThan'
|
||||
$sheet.ConditionalFormatting[1].Formula | Should be '104857600'
|
||||
$sheet.ConditionalFormatting[1].Style.Font.Color.Color.Name | Should be 'ffff0000'
|
||||
$sheet.ConditionalFormatting[1].Style.Font.Strike | Should be $true
|
||||
$sheet.ConditionalFormatting[1].type | Should be "TopPercent"
|
||||
$sheet.ConditionalFormatting[2].type | Should be 'GreaterThan'
|
||||
$sheet.ConditionalFormatting[2].Formula | Should be '104857600'
|
||||
$sheet.ConditionalFormatting[2].Style.Font.Color.Color.Name | Should be 'ffff0000'
|
||||
}
|
||||
it "Froze the panes " {
|
||||
$sheet.view.Panes.Count | Should be 3
|
||||
@@ -688,10 +702,12 @@ 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" {
|
||||
It "Controled the axes and title and legend of the chart " {
|
||||
$d.XAxis.MaxValue | Should be 361
|
||||
$d.XAxis.MajorUnit | Should be 30
|
||||
$d.XAxis.MinorUnit | Should be 10
|
||||
@@ -718,6 +734,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
|
||||
@@ -728,7 +782,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 |
|
||||
@@ -751,11 +805,4 @@ Describe ExportExcel {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
## To do
|
||||
## More Charts , pivot options & other FreezePanes settings ?
|
||||
## Style script block
|
||||
## Rezip ?
|
||||
|
||||
}
|
||||
|
||||
89
__tests__/Set-Row_Set-Column-SetFormat.tests.ps1
Normal file
89
__tests__/Set-Row_Set-Column-SetFormat.tests.ps1
Normal file
@@ -0,0 +1,89 @@
|
||||
|
||||
$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"]
|
||||
|
||||
$c = Set-Column -PassThru -Worksheet $ws -Heading "Total" -Value "=Quantity*Price" -NumberFormat "£#,###.00" -FontColor Blue -Bold -HorizontalAlignment Right -VerticalAlignment Top
|
||||
$r = Set-Row -PassThru -Worksheet $ws -StartColumn 3 -BorderAround Thin -Italic -Underline -FontSize 14 -Value {"=sum($columnName`2:$columnName$endrow)" } -VerticalAlignment Bottom
|
||||
Set-Format -Address $excel.Workbook.Worksheets["Sheet1"].cells["b3"] -HorizontalAlignment Right -VerticalAlignment Center -BorderAround Thick -BorderColor Red -StrikeThru
|
||||
Set-Format -Address $excel.Workbook.Worksheets["Sheet1"].cells["c3"] -BorderColor Red -BorderTop DashDot -BorderLeft DashDotDot -BorderBottom Dashed -BorderRight Dotted
|
||||
Set-Format -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.Column(2) -AutoFit
|
||||
Set-Format -Address $ws.Cells["E:E"] -AutoFit
|
||||
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 " {
|
||||
$r | should not beNullorEmpty
|
||||
# $c | should not beNullorEmpty ## can't see why but this test breaks in appveyor
|
||||
$ws.Column(1).width | should be 0
|
||||
$ws.Row(5).height | should be 0
|
||||
}
|
||||
it "Set a column formula, with numberformat, color, bold face and alignment" {
|
||||
$ws.cells["e2"].Formula | Should be "=Quantity*Price"
|
||||
$ws.cells["e2"].Style.Font.Color.rgb | Should be "FF0000FF"
|
||||
$ws.cells["e2"].Style.Font.Bold | Should be $true
|
||||
$ws.cells["e2"].Style.Font.VerticalAlign | Should be "None"
|
||||
$ws.cells["e2"].Style.Numberformat.format | Should be "£#,###.00"
|
||||
$ws.cells["e2"].Style.HorizontalAlignment | Should be "Right"
|
||||
}
|
||||
}
|
||||
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"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
227
formatting.ps1
227
formatting.ps1
@@ -1,227 +0,0 @@
|
||||
Function Add-ConditionalFormatting {
|
||||
<#
|
||||
.Synopsis
|
||||
Adds contitional formatting to worksheet
|
||||
.Example
|
||||
$excel = $avdata | Export-Excel -Path (Join-path $FilePath "\Machines.XLSX" ) -WorksheetName "Server Anti-Virus" -AutoSize -FreezeTopRow -AutoFilter -PassThru
|
||||
|
||||
Add-ConditionalFormatting -WorkSheet $excel.Workbook.Worksheets[1] -Address "b":b1048576" -ForeGroundColor "RED" -RuleType ContainsText -ConditionValue "2003"
|
||||
Add-ConditionalFormatting -WorkSheet $excel.Workbook.Worksheets[1] -Address "i2:i1048576" -ForeGroundColor "RED" -RuleType ContainsText -ConditionValue "Disabled"
|
||||
$excel.Workbook.Worksheets[1].Cells["D1:G1048576"].Style.Numberformat.Format = [cultureinfo]::CurrentCulture.DateTimeFormat.ShortDatePattern
|
||||
$excel.Workbook.Worksheets[1].Row(1).style.font.bold = $true
|
||||
$excel.Save() ; $excel.Dispose()
|
||||
|
||||
Here Export-Excel is called with the -passThru parameter so the Excel Package object is stored in $Excel
|
||||
The desired worksheet is selected and the then columns B and i are conditially formatted (excluding the top row) to show
|
||||
Fixed formats are then applied to dates in columns D..G and the top row is formatted
|
||||
Finally the workbook is saved and the Excel closed.
|
||||
|
||||
#>
|
||||
Param (
|
||||
#The worksheet where the format is to be applied
|
||||
[OfficeOpenXml.ExcelWorksheet]$WorkSheet ,
|
||||
#The area of the worksheet where the format is to be applied
|
||||
[OfficeOpenXml.ExcelAddress]$Range ,
|
||||
#One of the standard named rules - Top / Bottom / Less than / Greater than / Contains etc
|
||||
[Parameter(Mandatory=$true,ParameterSetName="NamedRule",Position=3)]
|
||||
[OfficeOpenXml.ConditionalFormatting.eExcelConditionalFormattingRuleType]$RuleType ,
|
||||
#Text colour for matching objects
|
||||
[Alias("ForeGroundColour")]
|
||||
[System.Drawing.Color]$ForeGroundColor,
|
||||
#colour for databar type charts
|
||||
[Parameter(Mandatory=$true,ParameterSetName="DataBar")]
|
||||
[Alias("DataBarColour")]
|
||||
[System.Drawing.Color]$DataBarColor,
|
||||
#One of the three-icon set types (e.g. Traffic Lights)
|
||||
[Parameter(Mandatory=$true,ParameterSetName="ThreeIconSet")]
|
||||
[OfficeOpenXml.ConditionalFormatting.eExcelconditionalFormatting3IconsSetType]$ThreeIconsSet,
|
||||
#A four-icon set name
|
||||
[Parameter(Mandatory=$true,ParameterSetName="FourIconSet")]
|
||||
[OfficeOpenXml.ConditionalFormatting.eExcelconditionalFormatting4IconsSetType]$FourIconsSet,
|
||||
#A five-icon set name
|
||||
[Parameter(Mandatory=$true,ParameterSetName="FiveIconSet")]
|
||||
[OfficeOpenXml.ConditionalFormatting.eExcelconditionalFormatting5IconsSetType]$FiveIconsSet,
|
||||
#A value for the condition (e.g. "2000" if the test is 'lessthan 2000')
|
||||
[string]$ConditionValue,
|
||||
#A second value for the conditions like between x and Y
|
||||
[string]$ConditionValue2,
|
||||
#Background colour for matching items
|
||||
[System.Drawing.Color]$BackgroundColor,
|
||||
#Background pattern for matching items
|
||||
[OfficeOpenXml.Style.ExcelFillStyle]$BackgroundPattern = [OfficeOpenXml.Style.ExcelFillStyle]::Solid,
|
||||
#Secondary colour when a background pattern requires it
|
||||
[System.Drawing.Color]$PatternColor,
|
||||
#Sets the numeric format for matching items
|
||||
$NumberFormat,
|
||||
#Put matching items in bold face
|
||||
[switch]$Bold,
|
||||
#Put matching items in italic
|
||||
[switch]$Italic,
|
||||
#Underline matching items
|
||||
[switch]$Underline,
|
||||
#Strikethrough text of matching items
|
||||
[switch]$StrikeThru
|
||||
)
|
||||
|
||||
If ($ThreeIconsSet) {$rule = $WorkSheet.ConditionalFormatting.AddThreeIconSet($Range , $ThreeIconsSet)}
|
||||
elseif ($FourIconsSet) {$rule = $WorkSheet.ConditionalFormatting.AddFourIconSet( $Range , $FourIconsSet) }
|
||||
elseif ($FiveIconsSet) {$rule = $WorkSheet.ConditionalFormatting.AddFiveIconSet( $Range , $IconType) }
|
||||
elseif ($DataBarColor) {$rule = $WorkSheet.ConditionalFormatting.AddDatabar( $Range , $DataBarColor) }
|
||||
else { $rule = ($WorkSheet.ConditionalFormatting)."Add$RuleType"($Range)}
|
||||
|
||||
if ($ConditionValue -and $RuleType -match "Top|Botom") {$rule.Rank = $ConditionValue }
|
||||
if ($ConditionValue -and $RuleType -match "StdDev") {$rule.StdDev = $ConditionValue }
|
||||
if ($ConditionValue -and $RuleType -match "Than|Equal|Expression") {$rule.Formula = $ConditionValue }
|
||||
if ($ConditionValue -and $RuleType -match "Text|With") {$rule.Text = $ConditionValue }
|
||||
if ($ConditionValue -and
|
||||
$ConditionValue2 -and $RuleType -match "Between") {$rule.Formula = $ConditionValue
|
||||
$rule.Formula2 = $ConditionValue2}
|
||||
|
||||
if ($NumberFormat) {$rule.Style.NumberFormat.Format = $NumberFormat }
|
||||
if ($Underline) {$rule.Style.Font.Underline = [OfficeOpenXml.Style.ExcelUnderLineType]::Single }
|
||||
if ($Bold) {$rule.Style.Font.Bold = $true}
|
||||
if ($Italic) {$rule.Style.Font.Italic = $true}
|
||||
if ($StrikeThru) {$rule.Style.Font.Strike = $true}
|
||||
if ($ForeGroundColor) {$rule.Style.Font.Color.color = $ForeGroundColor }
|
||||
if ($BackgroundColor) {$rule.Style.Fill.BackgroundColor.color = $BackgroundColor }
|
||||
if ($BackgroundPattern) {$rule.Style.Fill.PatternType = $BackgroundPattern }
|
||||
if ($PatternColor) {$rule.Style.Fill.PatternColor.color = $PatternColor }
|
||||
}
|
||||
|
||||
Function Set-Format {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Applies Number, font, alignment and colour formatting to a range of Excel Cells
|
||||
.EXAMPLE
|
||||
$sheet.Column(3) | Set-Format -HorizontalAlignment Right -NumberFormat "#,###"
|
||||
Selects column 3 from a sheet object (within a workbook object, which is a child of the ExcelPackage object) and passes it to Set-Format which formats as an integer with comma seperated groups
|
||||
.EXAMPLE
|
||||
Set-Format -Address $sheet.Cells["E1:H1048576"] -HorizontalAlignment Right -NumberFormat "#,###"
|
||||
Instead of piping the address in this version specifies a block of cells and applies similar formatting
|
||||
|
||||
#>
|
||||
Param (
|
||||
#One or more row(s), Column(s) and/or block(s) of cells to format
|
||||
[Parameter(ValueFromPipeline=$true)]
|
||||
[object[]]$Address ,
|
||||
#Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc
|
||||
[Alias("NFormat")]
|
||||
$NumberFormat,
|
||||
#Style of border to draw around the range
|
||||
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderAround,
|
||||
#Colour for the text - if none specified it will be left as it it is
|
||||
[System.Drawing.Color]$FontColor,
|
||||
#Clear Bold, Italic, StrikeThrough and Underline and set colour to black
|
||||
[switch]$ResetFont,
|
||||
#Make text bold
|
||||
[switch]$Bold,
|
||||
#Make text italic
|
||||
[switch]$Italic,
|
||||
#Underline the text using the underline style in -underline type
|
||||
[switch]$Underline,
|
||||
#Should Underline use single or double, normal or accounting mode : default is single normal
|
||||
[OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single,
|
||||
#StrikeThrough text
|
||||
[switch]$StrikeThru,
|
||||
#Subscript or superscript
|
||||
[OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift,
|
||||
#Font to use - Excel defaults to Calibri
|
||||
[String]$FontName,
|
||||
#Point size for the text
|
||||
[float]$FontSize,
|
||||
#Change background colour
|
||||
[System.Drawing.Color]$BackgroundColor,
|
||||
#Background pattern - solid by default
|
||||
[OfficeOpenXml.Style.ExcelFillStyle]$BackgroundPattern =[OfficeOpenXml.Style.ExcelFillStyle]::Solid ,
|
||||
#Secondary colour for background pattern
|
||||
[Alias("PatternColour")]
|
||||
[System.Drawing.Color]$PatternColor,
|
||||
#Turn on text wrapping
|
||||
[switch]$WrapText,
|
||||
#Position cell contents to left, right or centre ...
|
||||
[OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment,
|
||||
#Position cell contents to top bottom or centre
|
||||
[OfficeOpenXml.Style.ExcelVerticalAlignment]$VerticalAlignment,
|
||||
#Degrees to rotate text. Up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise.
|
||||
[ValidateRange(-90,90)]
|
||||
[int]$TextRotation ,
|
||||
#Autofit cells to width (columns or ranges only)
|
||||
[switch]$AutoFit,
|
||||
#Set cells to a fixed width (columns or ranges only), ignored if Autofit is specified
|
||||
[float]$Width,
|
||||
#Set cells to a fixed hieght (rows or ranges only)
|
||||
[float]$Height,
|
||||
#Hide a row or column (not a range)
|
||||
[switch]$Hidden
|
||||
)
|
||||
process {
|
||||
Foreach ($range in $Address) {
|
||||
if ($ResetFont) {$Range.Style.Font.Color.SetColor("Black")
|
||||
$Range.Style.Font.Bold = $false
|
||||
$Range.Style.Font.Italic = $false
|
||||
$Range.Style.Font.UnderLine = $false
|
||||
$Range.Style.Font.Strike = $false
|
||||
}
|
||||
if ($Underline) {$Range.Style.Font.UnderLine = $true
|
||||
$Range.Style.Font.UnderLineType =$UnderLineType
|
||||
}
|
||||
if ($Bold) {$Range.Style.Font.Bold = $true }
|
||||
if ($Italic) {$Range.Style.Font.Italic = $true }
|
||||
if ($StrikeThru) {$Range.Style.Font.Strike = $true }
|
||||
if ($FontShift) {$Range.Style.Font.VerticalAlign = $FontShift }
|
||||
if ($FontColor) {$Range.Style.Font.Color.SetColor( $FontColor ) }
|
||||
if ($BorderAround) {$Range.Style.Border.BorderAround( $BorderAround ) }
|
||||
if ($NumberFormat) {$Range.Style.Numberformat.Format= $NumberFormat }
|
||||
if ($TextRotation) {$Range.Style.TextRotation = $TextRotation }
|
||||
if ($WrapText) {$Range.Style.WrapText = $true }
|
||||
if ($HorizontalAlignment) {$Range.Style.HorizontalAlignment= $HorizontalAlignment }
|
||||
if ($VerticalAlignment) {$Range.Style.VerticalAlignment = $VerticalAlignment }
|
||||
|
||||
if ($BackgroundColor) {
|
||||
$Range.Style.Fill.PatternType = $BackgroundPattern
|
||||
$Range.Style.Fill.BackgroundColor.SetColor($BackgroundColor)
|
||||
if ($PatternColor) {
|
||||
$range.Style.Fill.PatternColor.SetColor( $PatternColor)
|
||||
}
|
||||
}
|
||||
|
||||
if ($Height) {
|
||||
if ($Range -is [OfficeOpenXml.ExcelRow] ) {$Range.Height = $Height }
|
||||
elseif ($Range -is [OfficeOpenXml.ExcelRange] ) {
|
||||
($range.Start.Row)..($range.Start.Row + $range.Rows) |
|
||||
ForEach-Object {$ws.Row($_).Height = $Height }
|
||||
}
|
||||
else {Write-Warning -Message ("Can set the height of a row or a range but not a {0} object" -f ($Range.GetType().name)) }
|
||||
}
|
||||
if ($AutoFit) {
|
||||
if ($Range -is [OfficeOpenXml.ExcelColumn]) {$Range.AutoFit() }
|
||||
elseif ($Range -is [OfficeOpenXml.ExcelRange] ) {$Range.AutoFitColumns() }
|
||||
else {Write-Warning -Message ("Can autofit a column or a range but not a {0} object" -f ($Range.GetType().name)) }
|
||||
|
||||
}
|
||||
elseif ($Width) {
|
||||
if ($Range -is [OfficeOpenXml.ExcelColumn]) {$Range.Width = $Width}
|
||||
elseif ($Range -is [OfficeOpenXml.ExcelRange] ) {
|
||||
($range.Start.Column)..($range.Start.Column+ $range.Columns) |
|
||||
ForEach-Object {$ws.Column($_).Width = $Width}
|
||||
}
|
||||
else {Write-Warning -Message ("Can set the width of a column or a range but not a {0} object" -f ($Range.GetType().name)) }
|
||||
}
|
||||
if ($Hidden) {
|
||||
if ($Range -is [OfficeOpenXml.ExcelRow] -or
|
||||
$Range -is [OfficeOpenXml.ExcelColumn] ) {$Range.Hidden = $True}
|
||||
else {Write-Warning -Message ("Can hide a row or a column but not a {0} object" -f ($Range.GetType().name)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#Argument completer for colours. If we have PS 5 or Tab expansion++ then we'll register it. Otherwise it does nothing.
|
||||
Function ColorCompletion{
|
||||
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
|
||||
[System.Drawing.KnownColor].GetFields() | Where-Object {$_.IsStatic -and $_.name -like "$wordToComplete*" } |
|
||||
Sort-Object name | ForEach-Object {New-CompletionResult $_.name $_.name
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user