From 890906ff102be5f7a757dc00d97cd76a595481e8 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Tue, 24 Oct 2017 09:02:14 +0100 Subject: [PATCH] Fixes to formatting , new Export charts tool (requires Excel.exe) help updates and Export excel support for "No data" use Export-Excel.ps1 1. No code seems to act on the "NoClobber" parameter, I had previously added a "ClearSheet" parameter which removes the worksheet and any past data (before if there were fewer rows or columns in the new data, the old would not be over-written) 2. I have made the whole of the process{} block in export-Excel subject to IF ($target data) .... this way things which are processed in the end{} block can be done in a seperate call to Export-Excel without the need to load data. Because of this there should be no need for the Open and Close -ExcelPackage functions going forward, but I've left them in place for now 3. Fixed a bug when setting the target range it was previously setting the end of the range to be the number of columns which failed if the data was inserted at a column other than one. 4. I've moved the top left corner of a pivot chart so it sits closer to the data. 5. I've change the check for inserting a pivot table so if -InsertPivotChart is specified it implies -insertPivotTable. Formatting. 6. The previous check in was not up-to date and contained some issues with conditional formatting which I had fixed in the past. 7. Fixed a peformance bug in set-format where a foreach intended to allow the same format to be applied to multiple ranges would format a large blocks of cells one-by-one if it was the only range passed. . 8. Improved online help for the formatting commands. Export charts 9. My current project is importing a lot of data into Excel and needs to take Excel charts out as JPG files. I've thrown in the Export-Charts script as "something for the pot", even though the connection with the rest of work is loose, --- Export-Excel.ps1 | 165 ++++++++++++++++++++++++++++++++++++++++------ Export-charts.ps1 | 51 ++++++++++++++ ImportExcel.psm1 | 3 +- formatting.ps1 | 106 ++++++++++++++++++----------- 4 files changed, 267 insertions(+), 58 deletions(-) create mode 100644 Export-charts.ps1 diff --git a/Export-Excel.ps1 b/Export-Excel.ps1 index 59532b0..e131309 100644 --- a/Export-Excel.ps1 +++ b/Export-Excel.ps1 @@ -5,13 +5,83 @@ .DESCRIPTION Export data to an Excel file and where possible try to convert numbers so Excel recognizes them as numbers instead of text. After all. Excel is a spreadsheet program used for number manipulation and calculations. In case the number conversion is not desired, use the parameter '-NoNumberConversion *'. - + .PARAMETER Path + Path to a new or existing .XLSX file + .PARAMETER ExcelPackage + An object representing an Excel Package - usually this is returned by specifying -Passthru alllowing multiple commands to work on the same Workbook without saving and reloading each time. + .PARAMETER WorkSheetName + The name of a sheet within the workbook - "Sheet1" by default + .PARAMETER ClearSheet + If specified Export-Excel will remove any existing worksheet with the selected name. The Default behaviour is to overwrite cells in this sheet as needed (but leaving non-overwritten ones in place) + .PARAMETER Append + If specified data will be added to the end of an existing sheet, using the same column headings. + .PARAMETER TargetData + Data to insert onto the worksheet - this is often provided from the pipeline. + .PARAMETER ExcludeProperty + Speficies properties which may exist in the target data but should not be placed on the worksheet + .PARAMETER Title + Text of a title to be placed in Cell A1 + .PARAMETER TitleBold + Sets the title in boldface type + .PARAMETER TitleSize + Sets the point size for the title + .PARAMETER TitleBackgroundColor + Sets the cell background to solid and the chose colour for the title cell + .PARAMETER Password + Sets password protection on the workbook + .PARAMETER IncludePivotTable + Adds a Pivot table using the data in the worksheet + .PARAMETER PivotRows + Name(s) columns from the spreadhseet which will prvoide the row name(s) in the pivot table + .PARAMETER PivotColumns + Name(s) columns from the spreadhseet which will prvoide the Column name(s) in the pivot table + .PARAMETER PivotData + Hash table in the form ColumnName = Average|Count|CountNums|Max|Min|Product|None|StdDev|StdDevP|Sum|Var|VarP to provide the data in the Pivot table + .PARAMETER PivotTableDefinition, + HashTable(s) with Sheet PivotTows, PivotColumns, PivotData, IncludePivotChart and ChartType values to make it easier to specify a definition or multiple Pivots. + .PARAMETER IncludePivotChart, + Include a chart with the Pivot table - implies Include Pivot Table. + .PARAMETER NoLegend + Exclude the legend from the pivot chart + .PARAMETER ShowCategory + Add category labels to the pivot chart + .PARAMETER ShowPercent + Add Percentage labels to the pivot chart .PARAMETER ConditionalText Applies a 'Conditional formatting rule' in Excel on all the cells. When specific conditions are met a rule is triggered. - .PARAMETER NoNumberConversion By default we convert all values to numbers if possible, but this isn't always desirable. NoNumberConversion allows you to add exceptions for the conversion. Wildcards (like '*') are allowed. - + .PARAMETER BoldTopRow + Makes the top Row boldface. + .PARAMETER NoHeader + Does not put field names at the top of columns + .PARAMETER RangeName + Makes the data in the worksheet a named range + .PARAMETER TableName + Makes the data in the worksheet a table with a name applies a style to it. Name must not contain spaces + .PARAMETER TableStyle + Selects the style for the named table - defaults to 'Medium6' + .PARAMETER ExcelChartDefinition + A hash table containing ChartType, Title, NoLegend, ShowCategory, ShowPecent, Yrange, Xrange and SeriesHeader for one or more [non-pivot] charts + .PARAMETER HideSheet + Name(s) of Sheet(s) to hide in the workbook + .PARAMETER KillExcel + Closes Excel - prevents errors writing to the file because Excel has it open + .PARAMETER AutoNameRange + Makes each column a named range + .PARAMETER StartRow + Row to start adding data. 1 by default. Row 1 will contain the title if any. Then headers will appear (Unless -No header is specified) then the data appears + .PARAMETER StartColumn + Column to start adding data - 1 by default + + .PARAMETER FreezeTopRow + Freezes headers etc. in the top row + .PARAMETER FreezeFirstColumn + Freezes titles etc. in the left column + .PARAMETER FreezeTopRowFirstColumn + Freezes top row and left column (equivalent to Freeze pane 2,2 ) + .PARAMETER FreezePane + Freezes panes at specified coordinates (in the form RowNumber , ColumnNumber) .PARAMETER AutoFilter Enables the 'Filter' in Excel on the complete header row. So users can easily sort, filter and/or search the data in the select column from within Excel. @@ -51,7 +121,9 @@ .PARAMETER Show Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first. - + .PARAMETER PassThru + If specified, Export-Excel returns an object representing the Excel package without saving the package first. To save it you need to call the save or Saveas method or send it back to Export-Excel + .EXAMPLE Get-Process | Export-Excel .\Test.xlsx -show Export all the processes to the Excel file 'Test.xlsx' and open the file immediately. @@ -189,7 +261,60 @@ .EXAMPLE Get-Service | Export-Excel 'c:\temp\test.xlsx' -Show -IncludePivotTable -PivotRows status -PivotData @{status='count'} + + .EXAMPLE + $pt = [ordered]@{} + $pt.pt1=@{ SourceWorkSheet = 'Sheet1'; + PivotRows = 'Status' + PivotData = @{'Status'='count'} + IncludePivotChart = $true + ChartType = 'BarClustered3D' + } + $pt.pt2=@{ SourceWorkSheet = 'Sheet2'; + PivotRows = 'Company' + PivotData = @{'Company'='count'} + IncludePivotChart = $true + ChartType = 'PieExploded3D' + } + Remove-Item -Path .\test.xlsx + Get-Service | Select-Object -Property Status,Name,DisplayName,StartType | Export-Excel -Path .\test.xlsx -AutoSize + Get-Process | Select-Object -Property Name,Company,Handles,CPU,VM | Export-Excel -Path .\test.xlsx -AutoSize -WorkSheetname 'sheet2' + Export-Excel -Path .\test.xlsx -PivotTableDefinition $pt -Show + This example defines two pivot tables. Then it puts Service data on Sheet1 with one call to Export-Excel and Process Data on sheet2 with a second call to Export-Excel + The thrid and final call adds the two pivot tables and opens the spreadsheet in Excel + + + .EXAMPLE + Remove-Item -Path .\test.xlsx + $excel = Get-Service | Select-Object -Property Status,Name,DisplayName,StartType | Export-Excel -Path .\test.xlsx -PassThru + $excel.Workbook.Worksheets["Sheet1"].Row(1).style.font.bold = $true + $excel.Workbook.Worksheets["Sheet1"].Column(3 ).width = 29 + $excel.Workbook.Worksheets["Sheet1"].Column(3 ).Style.wraptext = $true + $excel.Save() + $excel.Dispose() + Start-Process .\test.xlsx + + This example uses -passthrough - put service information into sheet1 of the work book and saves the excelPackageObject in $Excel + It then uses the package object to apply formatting, and then saves the workbook and disposes of the object before loading the document in Excel. + + .EXAMPLE + $excel = Get-Process | Select-Object -Property Name,Company,Handles,CPU,PM,NPM,WS | Export-Excel -Path .\test.xlsx -ClearSheet -WorkSheetname "Processes" -PassThru + $sheet = $excel.Workbook.Worksheets["Processes"] + $sheet.Column(1) | Set-Format -Bold -AutoFit + $sheet.Column(2) | Set-Format -Width 29 -WrapText + $sheet.Column(3) | Set-Format -HorizontalAlignment Right -NFormat "#,###" + Set-Format -Address $sheet.Cells["E1:H1048576"] -HorizontalAlignment Right -NFormat "#,###" + 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 + foreach ($c in 5..9) {Set-Format $sheet.Column($c) -AutoFit } + Export-Excel -ExcelPackage $excel -WorkSheetname "Processes" -IncludePivotChart -ChartType ColumnClustered -NoLegend -PivotRows company -PivotData @{'Name'='Count'} -Show + + This a more sophisticated version of the previous example showing different ways of using Set-Format, and also adding conditional formatting. + In the final command a Pivot chart is added and the workbook is opened in Excel. + .LINK https://github.com/dfinke/ImportExcel #> @@ -204,21 +329,23 @@ [OfficeOpenXml.ExcelPackage]$ExcelPackage, [Parameter(ValueFromPipeline=$true)] $TargetData, + [String]$Password, [String]$WorkSheetname = 'Sheet1', + [switch]$ClearSheet, + [switch]$Append, [String]$Title, [OfficeOpenXml.Style.ExcelFillStyle]$TitleFillPattern = 'None', [Switch]$TitleBold, [Int]$TitleSize = 22, [System.Drawing.Color]$TitleBackgroundColor, + [Switch]$IncludePivotTable, [String[]]$PivotRows, [String[]]$PivotColumns, $PivotData, - [Switch]$PivotDataToColumn, - [String]$Password, - [OfficeOpenXml.Drawing.Chart.eChartType]$ChartType = 'Pie', + [Switch]$PivotDataToColumn, [Hashtable]$PivotTableDefinition, - [Switch]$IncludePivotTable, [Switch]$IncludePivotChart, + [OfficeOpenXml.Drawing.Chart.eChartType]$ChartType = 'Pie', [Switch]$NoLegend, [Switch]$ShowCategory, [Switch]$ShowPercent, @@ -249,8 +376,8 @@ $true } })] - [Parameter(ParameterSetName = 'Table')] - [Parameter(ParameterSetName = 'PackageTable')] + [Parameter(ParameterSetName = 'Table' ,Mandatory = $true)] + [Parameter(ParameterSetName = 'PackageTable' ,Mandatory = $true)] [String]$TableName, [Parameter(ParameterSetName = 'Table')] [Parameter(ParameterSetName = 'PackageTable')] @@ -268,8 +395,7 @@ [Object[]]$ConditionalFormat, [Object[]]$ConditionalText, [ScriptBlock]$CellStyleSB, - [Switch]$Now, - [switch]$Append + [Switch]$Now ) Begin { @@ -427,8 +553,7 @@ $pkg = New-Object OfficeOpenXml.ExcelPackage $Path } - [OfficeOpenXml.ExcelWorksheet]$ws = $pkg | Add-WorkSheet -WorkSheetname $WorkSheetname -NoClobber:$NoClobber - + [OfficeOpenXml.ExcelWorksheet]$ws = $pkg | Add-WorkSheet -WorkSheetname $WorkSheetname -NoClobber:$NoClobber -ClearSheet:$ClearSheet #Add worksheet doesn't take any action for -noClobber foreach ($format in $ConditionalFormat ) { $target = "Add$($format.Formatter)" $rule = ($ws.ConditionalFormatting).PSObject.Methods[$target].Invoke($format.Range, $format.IconType) @@ -468,6 +593,7 @@ } Process { + if ($TargetData) { Try { if ($firstTimeThru) { $firstTimeThru = $false @@ -487,7 +613,7 @@ #region Add headers if (-not $script:Header) { $ColumnIndex = $StartColumn - $script:Header = $TargetData.PSObject.Properties.Name | Where-Object {$_ -notin $ExcludeProperty} + $script:Header = $TargetData.PSObject.Properties.Name | Where-Object {$_ -notin $ExcludeProperty} if ($NoHeader) { # Don't push the headers to the spread sheet @@ -518,6 +644,7 @@ Catch { throw "Failed exporting worksheet '$WorkSheetname' to '$Path': $_" } + } } End { @@ -561,7 +688,7 @@ } $csc = $StartColumn $cer = $ws.Dimension.End.Row - $cec = $script:Header.Count + $cec = $ws.Dimension.End.Column # was $script:Header.Count $targetRange = $ws.Cells[$csr, $csc, $cer, $cec] #if we're appending data the table may already exist: but excel doesn't like the result if I put @@ -633,14 +760,14 @@ } $chart = $wsPivot.Drawings.AddChart('PivotChart', $ChartType, $pivotTable) - $chart.SetPosition(1, 0, 3, 0) + $chart.SetPosition(0, 0, 2, 0) #Changed position to top row, next to a chart which doesn't pivot on columns $chart.SetSize(600, 400) } } } } - if ($IncludePivotTable) { + if ($IncludePivotTable -or $IncludePivotChart) { #changed so -includePivotChart Implies -includePivotTable. $pivotTableName = $WorkSheetname + 'PivotTable' #Make sure the Pivot table sheet doesn't already exist try { $pkg.Workbook.Worksheets.Delete( $pivotTableName) } catch {} @@ -686,7 +813,7 @@ $chart = $wsPivot.Drawings.AddChart('PivotChart', $ChartType, $pivotTable) $chart.DataLabel.ShowCategory = $ShowCategory $chart.DataLabel.ShowPercent = $ShowPercent - + $chart.SetPosition(0,0,2,0) # if Pivot table is rows+data only it will be 2 columns wide if has pivot columns we don't know how wide it will be if ($NoLegend) { $chart.Legend.Remove() } diff --git a/Export-charts.ps1 b/Export-charts.ps1 new file mode 100644 index 0000000..196d8e5 --- /dev/null +++ b/Export-charts.ps1 @@ -0,0 +1,51 @@ +<# + .Synopsis + Exports the charts in an Excel spreadSheet + .Example + Export-Charts .\test,xlsx + Exports the charts in test.xlsx to JPEG files in the current directory. + + .Example + Export-Charts -path .\test,xlsx -destination [System.Environment+SpecialFolder]::MyDocuments -outputType PNG -passthrough + Exports the charts to PNG files in MyDocuments , and returns file objects representing the newly created files + +#> +Param ( + #Path to the Excel file whose chars we will export. + $Path = "C:\Users\public\Documents\stats.xlsx", + #If specified, output file objects representing the image files. + [switch]$passthru, + #Format to write - JPG by default + [ValidateSet("JPG","PNG","GIF")] + $OutputType = "JPG", + #Folder to write image files to (defaults to same one as the Excel file is in) + $Destination +) + +#if no output folder was specified, set destination to the folder where the Excel file came from +if (-not $Destination) {$Destination = Split-Path -Path $path -Parent } + +#Call up Excel and tell it to open the file. +try { $excelApp = New-Object -ComObject "Excel.Application" } +catch { Write-Warning "Could not start Excel application - which usually means it is not installed." ; return } + +try { $excelWorkBook = $excelApp.Workbooks.Open($path) } +catch { Write-Warning "Could not start Excel application - which usually means it is not installed." ; return } + + +#For each worksheet, for each chart, jump to the chart, create a filename of "WorksheetName_ChartTitle.jpg", and export the file. +foreach ($excelWorkSheet in $excelWorkBook.Worksheets) { + #note somewhat unusual way of telling excel we want all the charts. + foreach ($excelchart in $excelWorkSheet.ChartObjects([System.Type]::Missing)) { + #if you don't go to the chart the image will be zero size ! + $excelApp.Goto($excelchart.TopLeftCell,$true) + $imagePath = Join-Path -Path $Destination -ChildPath ($excelWorkSheet.Name + "_" + ($excelchart.Chart.ChartTitle.Text -split "\s\d\d:\d\d,")[0] + ".$OutputType") + if ( $excelchart.Chart.Export($imagePath, $OutputType, $false) ) { # Export returs true/false for success/failure + if ($passThru) {Get-Item -Path $imagePath } # when succesful return a file object (-passthru) or print a verbose message, write warning for any failures + else {Write-Verbose -Message "Exported $imagePath"} + } + else {Write-Warning -Message "Failure exporting $imagePath" } + } +} + +$excelApp.Quit() \ No newline at end of file diff --git a/ImportExcel.psm1 b/ImportExcel.psm1 index 14e47e7..8ab5ed2 100644 --- a/ImportExcel.psm1 +++ b/ImportExcel.psm1 @@ -437,11 +437,12 @@ function Add-WorkSheet { [OfficeOpenXml.ExcelPackage] $ExcelPackage, [Parameter(Mandatory=$true)] [string] $WorkSheetname, + [switch] $ClearSheet, [Switch] $NoClobber ) $ws = $ExcelPackage.Workbook.Worksheets[$WorkSheetname] - + if($ClearSheet -and $ws) {$ExcelPackage.Workbook.Worksheets.Delete($WorkSheetname) ; $ws = $null } if(!$ws) { Write-Verbose "Add worksheet '$WorkSheetname'" $ws=$ExcelPackage.Workbook.Worksheets.Add($WorkSheetname) diff --git a/formatting.ps1 b/formatting.ps1 index ed3bde7..2ec8b58 100644 --- a/formatting.ps1 +++ b/formatting.ps1 @@ -1,79 +1,109 @@ Function Add-ConditionalFormatting { <# -.Synopsis Adds contitional formatting to worksheet +.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 + $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() + 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. + 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, - $ConditionValue, - $ConditionValue2, + #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, - [OfficeOpenXml.Style.ExcelFillStyle]$BackgroundPattern, + #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 ($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} - $rule.Style.Font.Bold = $Bold - $rule.Style.Font.Italic = $Italic - $rule.Style.Font.Underline = $Underline - $rule.Style.Font.Strike = $StrikeThru - - if ($ForeGroundColor) {$rule.Style.Font.Color = $ForeGroundColor} - if ($BackgroundColor) {$rule.Style.Fill.BackgroundColor = $BackgroundColor } - if ($BackgroundPattern) {$rule.Style.Fill.PatternType = $BackgroundPattern } - if ($PatternColor) {$rule.Style.Fill.PatternColor = $PatternColor} - if ($NumberFormat) {$rule.Style.NumberFormat.Format = $NumberFormat} + 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 ( - #A row, Column or block of cells to format + #One or more row(s), Column(s) and/or block(s) of cells to format [Parameter(ValueFromPipeline=$true)] - $Address , + [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,