Merge pull request #475 from jhoneill/master

Colors for PS core and proof reading
This commit is contained in:
Doug Finke
2018-10-24 21:26:35 +00:00
committed by GitHub
22 changed files with 611 additions and 405 deletions

4
.gitignore vendored
View File

@@ -2,6 +2,8 @@
Thumbs.db
ehthumbs.db
*.gitignore
# Folder config file
Desktop.ini
@@ -14,6 +16,8 @@ $RECYCLE.BIN/
*.msm
*.msp
*.dll
# Windows shortcuts
*.lnk

View File

@@ -1,46 +1,97 @@
Function Add-ConditionalFormatting {
<#
.Synopsis
Adds conditional formatting to worksheet.
Adds conditional formatting to all or part of a worksheet.
.Description
Conditional formatting allows excel to
* Mark cells with Icons depending on their value
* Show a databar whose length indicates the value or a 2 or 3 color scale where the color indicate the relative value
Conditional formatting allows Excel to:
* Mark cells with icons depending on their value
* Show a databar whose length indicates the value or a two or three color scale where the color indicates the relative value
* Change the color, font, or number format of cells which meet given criteria
Add-ConditionalFormatting allows these to be set; for fine tuning of the rules you can use the -PassThru switch,
which will return the rule so that you can modify things which are specific to that type of rule,
for example the values which correspond to each icon in an Icon set.
Add-ConditionalFormatting allows these parameters to be set; for fine tuning of
the rules, the -PassThru switch will return the rule so that you can modify
things which are specific to that type of rule, example, the values which
correspond to each icon in an Icon-Set.
.Example
>
PS> $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 "b2: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 conditionally formatted (excluding the top row) to show red text if
the columns contain "2003" or "Disabled respectively. A fixed date format is then applied to columns D..G, and the top row is formatted.
Finally the workbook is saved and the Excel object closed.
Here Export-Excel is called with the -PassThru parameter so the ExcelPackage object
representing Machines.XLSX is stored in $Excel.The desired worksheet is selected
and then columns" B" and "I" are conditionally formatted (excluding the top row)
to show red text if they contain "2003" or "Disabled" respectively.
A fixed date format is then applied to columns D to G, and the top row is formatted.
Finally the workbook is saved and the Excel package object is closed.
.Example
>
>PS $r = Add-ConditionalFormatting -WorkSheet $excel.Workbook.Worksheets[1] -Range "B1:B100" -ThreeIconsSet Flags -Passthru
$r = Add-ConditionalFormatting -WorkSheet $excel.Workbook.Worksheets[1] -Range "B1:B100" -ThreeIconsSet Flags -Passthru
$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 modified to apply the flags in reverse order, and boundaries for the number which will set the split are set to 100 and 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 modified to apply the flags in reverse order, and transitions
between flags are set to 100 and 1000.
.Example
Add-ConditionalFormatting -WorkSheet $sheet -Range "D2:D1048576" -DataBarColor Red
This time $sheet holds an ExcelWorkseet object and databars are add to all of column D except for the tip row.
This time $sheet holds an ExcelWorkshseet object and databars are added to
column D, excluding the top row.
.Example
Add-ConditionalFormatting -Address $worksheet.cells["FinishPosition"] -RuleType Equal -ConditionValue 1 -ForeGroundColor Purple -Bold -Priority 1 -StopIfTrue
In this example a named range is used to select the cells where the formula should apply. If a cell in the "FinishPosition" range is 1, then the text is turned to Bold & Purple.
This rule is moved to first in the priority list, and where cells have a value of 1, no other rules will be processed.
In this example a named range is used to select the cells where the condition
should apply, and instead of specifying a sheet and range within the sheet as
separate parameters, the cells where the format should apply are specified
directly. If a cell in the "FinishPosition" range is 1, then the text is
turned to Bold & Purple. This rule is moved to first in the priority list,
and where cells have a value of 1, no other rules will be processed.
.Example
>
$excel = Get-ChildItem | Select-Object -Property Name,Length,LastWriteTime,CreationTime | Export-Excel "$env:temp\test43.xlsx" -PassThru -AutoSize
$ws = $excel.Workbook.Worksheets["Sheet1"]
$ws.Cells["E1"].Value = "SavedAt"
$ws.Cells["F1"].Value = [datetime]::Now
$ws.Cells["F1"].Style.Numberformat.Format = (Expand-NumberFormat -NumberFormat 'Date-Time')
$lastRow = $ws.Dimension.End.Row
Add-ConditionalFormatting -WorkSheet $ws -address "A2:A$Lastrow" -RuleType LessThan -ConditionValue "A" -ForeGroundColor Gray
Add-ConditionalFormatting -WorkSheet $ws -address "B2:B$Lastrow" -RuleType GreaterThan -ConditionValue 1000000 -NumberFormat '#,###,,.00"M"'
Add-ConditionalFormatting -WorkSheet $ws -address "C2:C$Lastrow" -RuleType GreaterThan -ConditionValue "=INT($F$1-7)" -ForeGroundColor Green -StopIfTrue
Add-ConditionalFormatting -WorkSheet $ws -address "D2:D$Lastrow" -RuleType Equal -ConditionValue "=C2" -ForeGroundColor Blue -StopIfTrue
Close-ExcelPackage -Show $excel
The first few lines of code export a list of file and directory names, sizes
and dates to a spreadsheet. It puts the date of the export in cell F1.
The first Conditional format changes the color of files and folders that begin
with a ".", "_" or anything else which sorts before "A".
The second Conditional format changes the Number format of numbers bigger than
1 million, for example 1,234,567,890 will dispay as "1,234.57M"
The third highlights datestamps of files less than a week old when the export
was run; the = is necessary in the condition value otherwise the rule will
look for the the text INT($F$1-7), and the cell address for the date is fixed
using the standard Excel $ notation.
The final Conditional format looks for files which have not changed since they
were created. Here the condition value is "=C2". The = sign means C2 is treated
as a formula, not literal text. Unlike the file age, we want the cell used to
change for each cell where the conditional format applies. The first cell in
the conditional format range is D2, which is compared against C2, then D3 is
compared against C3 and so on. A common mistake is to include the title row in
the range and accidentally apply conditional formatting to it, or to begin the
range at row 2 but use row 1 as the starting point for comparisons.
.Example
Add-ConditionalFormatting $ws.Cells["B:B"] GreaterThan 10000000 -Fore Red -Stop -Pri 1
This version shows the shortest syntax - the Address, Ruletype, and
Conditionvalue can be identified from their position, and ForegroundColor,
StopIfTrue and Priority can all be shortend.
#>
Param (
#A block of cells to format - you can use a named range with -Address $ws.names[1] or $ws.cells["RangeName"]
@@ -52,14 +103,14 @@
#A standard named-rule - Top / Bottom / Less than / Greater than / Contains etc.
[Parameter(Mandatory = $true, ParameterSetName = "NamedRule", Position = 1)]
[OfficeOpenXml.ConditionalFormatting.eExcelConditionalFormattingRuleType]$RuleType ,
#Text colour for matching objects
#Text color for matching objects
[Parameter(ParameterSetName = "NamedRule")]
[Alias("ForeGroundColour")]
[System.Drawing.Color]$ForeGroundColor,
#Colour for databar type charts
[Alias("ForegroundColour")]
$ForegroundColor,
#Color for databar type charts
[Parameter(Mandatory = $true, ParameterSetName = "DataBar")]
[Alias("DataBarColour")]
[System.Drawing.Color]$DataBarColor,
$DataBarColor,
#One of the three-icon set types (e.g. Traffic Lights)
[Parameter(Mandatory = $true, ParameterSetName = "ThreeIconSet")]
[OfficeOpenXml.ConditionalFormatting.eExcelconditionalFormatting3IconsSetType]$ThreeIconsSet,
@@ -69,27 +120,27 @@
#A five-icon set name
[Parameter(Mandatory = $true, ParameterSetName = "FiveIconSet")]
[OfficeOpenXml.ConditionalFormatting.eExcelconditionalFormatting5IconsSetType]$FiveIconsSet,
#Use the icon set in reverse order, or reverse the orders of Two- & Three-Color Scales
#Use the Icon-Set in reverse order, or reverse the orders of Two- & Three-Color Scales
[Parameter(ParameterSetName = "NamedRule")]
[Parameter(ParameterSetName = "ThreeIconSet")]
[Parameter(ParameterSetName = "FourIconSet")]
[Parameter(ParameterSetName = "FiveIconSet")]
[switch]$Reverse,
#A value for the condition (for example 2000 if the test is 'lessthan 2000'; Formulas should begin with "=" )
[Parameter(ParameterSetName = "NamedRule")]
[Parameter(ParameterSetName = "NamedRule",Position = 2)]
$ConditionValue,
#A second value for the conditions like "between x and Y"
[Parameter(ParameterSetName = "NamedRule")]
#A second value for the conditions like "Between X and Y"
[Parameter(ParameterSetName = "NamedRule",Position = 3)]
$ConditionValue2,
#Background colour for matching items
#Background color for matching items
[Parameter(ParameterSetName = "NamedRule")]
[System.Drawing.Color]$BackgroundColor,
$BackgroundColor,
#Background pattern for matching items
[Parameter(ParameterSetName = "NamedRule")]
[OfficeOpenXml.Style.ExcelFillStyle]$BackgroundPattern = [OfficeOpenXml.Style.ExcelFillStyle]::None ,
#Secondary colour when a background pattern requires it
#Secondary color when a background pattern requires it
[Parameter(ParameterSetName = "NamedRule")]
[System.Drawing.Color]$PatternColor,
$PatternColor,
#Sets the numeric format for matching items
[Parameter(ParameterSetName = "NamedRule")]
$NumberFormat,
@@ -111,7 +162,7 @@
#Set the sequence for rule processing
[int]$Priority,
#If specified pass the rule back to the caller to allow additional customization.
[switch]$Passthru
[switch]$PassThru
)
#Allow conditional formatting to work like Set-ExcelRange (with single ADDRESS parameter), split it to get worksheet and range of cells.
@@ -141,11 +192,13 @@
#By this point we should have a worksheet object whose ConditionalFormatting collection we will add to. If not, bail.
if (-not $worksheet -or $WorkSheet -isnot [OfficeOpenXml.ExcelWorksheet]) {write-warning "You need to provide a worksheet object." ; return}
#region create a rule of the right type
if ($RuleType -match 'IconSet$') {Write-warning -Message "You cannot configure a IconSet rule in this way; please use -$RuleType <SetName>." ; return}
if ($PSBoundParameters.ContainsKey("ThreeIconsSet" ) ) {$rule = $WorkSheet.ConditionalFormatting.AddThreeIconSet($Address , $ThreeIconsSet)}
if ($RuleType -match 'IconSet$') {Write-warning -Message "You cannot configure a Icon-Set rule in this way; please use -$RuleType <SetName>." ; return}
if ($PSBoundParameters.ContainsKey("DataBarColor" ) ) {if ($DataBarColor -is [string]) {$DataBarColor = [System.Drawing.Color]::$DataBarColor }
$rule = $WorkSheet.ConditionalFormatting.AddDatabar( $Address , $DataBarColor )
}
elseif ($PSBoundParameters.ContainsKey("ThreeIconsSet" ) ) {$rule = $WorkSheet.ConditionalFormatting.AddThreeIconSet($Address , $ThreeIconsSet)}
elseif ($PSBoundParameters.ContainsKey("FourIconsSet" ) ) {$rule = $WorkSheet.ConditionalFormatting.AddFourIconSet( $Address , $FourIconsSet )}
elseif ($PSBoundParameters.ContainsKey("FiveIconsSet" ) ) {$rule = $WorkSheet.ConditionalFormatting.AddFiveIconSet( $Address , $FiveIconsSet )}
elseif ($PSBoundParameters.ContainsKey("DataBarColor" ) ) {$rule = $WorkSheet.ConditionalFormatting.AddDatabar( $Address , $DataBarColor )}
else {$rule = ($WorkSheet.ConditionalFormatting)."Add$RuleType"($Address ) }
if ($Reverse) {
if ($rule.type -match 'IconSet$' ) {$rule.reverse = $true}
@@ -204,10 +257,13 @@
if ($PSBoundParameters.ContainsKey("Bold" ) ) {$rule.Style.Font.Bold = [boolean]$Bold }
if ($PSBoundParameters.ContainsKey("Italic" ) ) {$rule.Style.Font.Italic = [boolean]$Italic }
if ($PSBoundParameters.ContainsKey("StrikeThru" ) ) {$rule.Style.Font.Strike = [boolean]$StrikeThru }
if ($PSBoundParameters.ContainsKey("ForeGroundColor" ) ) {$rule.Style.Font.Color.color = $ForeGroundColor }
if ($PSBoundParameters.ContainsKey("BackgroundColor" ) ) {$rule.Style.Fill.BackgroundColor.color = $BackgroundColor }
if ($PSBoundParameters.ContainsKey("ForeGroundColor" ) ) {if ($ForeGroundColor -is [string]) {$ForeGroundColor = [System.Drawing.Color]::$ForeGroundColor }
$rule.Style.Font.Color.color = $ForeGroundColor }
if ($PSBoundParameters.ContainsKey("BackgroundColor" ) ) {if ($BackgroundColor -is [string]) {$BackgroundColor = [System.Drawing.Color]::$BackgroundColor }
$rule.Style.Fill.BackgroundColor.color = $BackgroundColor }
if ($PSBoundParameters.ContainsKey("BackgroundPattern") ) {$rule.Style.Fill.PatternType = $BackgroundPattern }
if ($PSBoundParameters.ContainsKey("PatternColor" ) ) {$rule.Style.Fill.PatternColor.color = $PatternColor }
if ($PSBoundParameters.ContainsKey("PatternColor" ) ) {if ($PatternColor -is [string]) {$PatternColor = [System.Drawing.Color]::$PatternColor }
$rule.Style.Fill.PatternColor.color = $PatternColor }
#endregion
#Allow further tweaking by returning the rule, if passthru specified
if ($Passthru) {$rule}

View File

@@ -1,21 +1,25 @@
function Export-Excel {
<#
.SYNOPSIS
Export data to an Excel worksheet.
Exports data to an Excel worksheet.
.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 *'.
Exports data to an Excel file and where possible tries to convert numbers
in text fields so Excel recognizes them as numbers instead of text.
After all: Excel is a spreadsheet program used for number manipulation
and calculations. If 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 allowing multiple commands to work on the same Workbook without saving and reloading each time.
An object representing an Excel Package - usually this is returned by specifying -PassThru allowing multiple commands to work on the same workbook without saving and reloading each time.
.PARAMETER WorksheetName
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.
If specified dat,a 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.
Data to insert onto the worksheet - this is usually provided from the pipeline.
.PARAMETER DisplayPropertySet
Many (but not all) objects have a hidden property named psStandardmembers with a child property DefaultDisplayPropertySet ; this parameter reduces the properties exported to those in this set.
.PARAMETER NoAliasOrScriptPropeties
@@ -37,36 +41,36 @@
.PARAMETER Password
Sets password protection on the workbook.
.PARAMETER IncludePivotTable
Adds a Pivot table using the data in the worksheet.
Adds a PivotTable using the data in the worksheet.
.PARAMETER PivotTableName
If a Pivot table is created from command line parameters, specifies the name of the new sheet holding the pivot. Defaults to "WorksheetName-PivotTable"
If a PivotTable is created from command line parameters, specifies the name of the new sheet holding the pivot. Defaults to "WorksheetName-PivotTable".
.PARAMETER PivotRows
Name(s) columns from the spreadsheet which will provide the Row name(s) in a pivot table created from command line parameters.
Name(s) of column(s) from the spreadsheet which will provide the Row name(s) in a PivotTable created from command line parameters.
.PARAMETER PivotColumns
Name(s) columns from the spreadsheet which will provide the Column name(s) in a pivot table created from command line parameters.
Name(s) of columns from the spreadsheet which will provide the Column name(s) in a PivotTable created from command line parameters.
.PARAMETER PivotFilter
Name(s) columns from the spreadsheet which will provide the Filter name(s) in a pivot table created from command line parameters.
Name(s) columns from the spreadsheet which will provide the Filter name(s) in a PivotTable created from command line parameters.
.PARAMETER PivotData
In a pivot table created from command line parameters, the fields to use in the table body are given as a Hash table in the form ColumnName = Average|Count|CountNums|Max|Min|Product|None|StdDev|StdDevP|Sum|Var|VarP.
In a PivotTable created from command line parameters, the fields to use in the table body are given as a Hash table in the form ColumnName = Average|Count|CountNums|Max|Min|Product|None|StdDev|StdDevP|Sum|Var|VarP.
.PARAMETER PivotDataToColumn
If there are multiple datasets in a PivotTable, by default they are shown as separate rows under the given row heading; this switch makes them separate columns.
.PARAMETER NoTotalsInPivot
In a pivot table created from command line parameters, prevents the addition of totals to rows and columns.
In a PivotTable created from command line parameters, prevents the addition of totals to rows and columns.
.PARAMETER PivotTotals
By default, Pivot tables have totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected.
By default, PivotTables have totals for each row (on the right) and for each column at the bottom. This allows just one or neither to be selected.
.PARAMETER PivotTableDefinition
Instead of describing a single pivot table with multiple commandline parameters; you can use a hashTable in the form PivotTableName = Definition;
Definition is itself a hashtable with Sheet, PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values.
Instead of describing a single PivotTable with multiple command-line parameters; you can use a HashTable in the form PivotTableName = Definition;
Definition is itself a Hashtable with Sheet, PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values.
.PARAMETER IncludePivotChart
Include a chart with the Pivot table - implies -IncludePivotTable.
Include a chart with the PivotTable - implies -IncludePivotTable.
.PARAMETER ChartType
The type for Pivot chart (one of Excel's defined chart types)
The type for PivotChart (one of Excel's defined chart types).
.PARAMETER NoLegend
Exclude the legend from the pivot chart.
Exclude the legend from the PivotChart.
.PARAMETER ShowCategory
Add category labels to the pivot chart.
Add category labels to the PivotChart.
.PARAMETER ShowPercent
Add Percentage labels to the pivot chart.
Add percentage labels to the PivotChart.
.PARAMETER ConditionalFormat
One or more conditional formatting rules defined with New-ConditionalFormattingIconSet.
.PARAMETER ConditionalText
@@ -74,13 +78,13 @@
.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.
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.
Makes the data in the worksheet a table with a name, and applies a style to it. Name must not contain spaces.
.PARAMETER TableStyle
Selects the style for the named table - defaults to 'Medium6'.
.PARAMETER BarChart
@@ -92,11 +96,11 @@
.PARAMETER PieChart
Creates a "quick" pie chart using the first text column as labels and the first numeric column as values
.PARAMETER ExcelChartDefinition
A hash table containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-pivot] charts.
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, supports wildcards. If all sheets would be hidden, the sheet being worked on will be revealed.
Name(s) of Sheet(s) to hide in the workbook, supports wildcards. If the selection would cause all sheets to be hidden, the sheet being worked on will be revealed.
.PARAMETER UnHideSheet
Name(s) of Sheet(s) to Reveal in the workbook, supports wildcards.
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.
@@ -126,13 +130,13 @@
.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 selected column from within Excel.
Enables the Excel filter on the complete header row, so users can easily sort, filter and/or search the data in the selected column.
.PARAMETER AutoSize
Sizes the width of the Excel column to the maximum width needed to display all the containing data in that cell.
.PARAMETER Activate
If there is already content in the workbook, a new sheet will not be active UNLESS Activate is specified; if a Pivot table is included it will be the active sheet
If there is already content in the workbook, a new sheet will not be active UNLESS Activate is specified; if a PivotTable is included it will be the active sheet
.PARAMETER Now
The 'Now' switch is a shortcut that creates automatically a temporary file, enables 'AutoSize', 'AutoFiler' and 'Show', and opens the file immediately.
The -Now switch is a shortcut that automatically creates a temporary file, enables "AutoSize", "AutoFiler" and "Show", and opens the file immediately.
.PARAMETER NumberFormat
Formats all values that can be converted to a number to the format specified.
@@ -162,7 +166,7 @@
'[Blue]$#,##0.00;[Red]-$#,##0.00'
.PARAMETER ReZip
If specified, Export-Excel will expand the contents of the .XLSX file (which is multiple files in a zip archive) and rebuilt it.
If specified, Export-Excel will expand the contents of the .XLSX file (which is multiple files in a zip archive) and rebuild it.
.PARAMETER NoClobber
Not used. Left in to avoid problems with older scripts, it may be removed in future versions.
.PARAMETER CellStyleSB
@@ -171,7 +175,7 @@
.PARAMETER Show
Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first.
.PARAMETER ReturnRange
If specified, Export-Excel returns the range of added cells in the format "A1:Z100"
If specified, Export-Excel returns the range of added cells in the format "A1:Z100".
.PARAMETER PassThru
If specified, Export-Excel returns an object representing the Excel package without saving the package first.
To save, you need to call Close-ExcelPackage or send the object back to Export-Excel, or use its .Save() or SaveAs() method.
@@ -190,7 +194,9 @@
Write-Output -1 668 34 777 860 -0.5 119 -0.1 234 788 |
Export-Excel @ExcelParams -NumberFormat '[Blue]$#,##0.00;[Red]-$#,##0.00'
Exports all data to the Excel file 'Excel.xslx' and colors the negative values in 'Red' and the positive values in 'Blue'. It will also add a dollar sign '$' in front of the rounded numbers to two decimal characters behind the comma.
Exports all data to the Excel file 'Excel.xslx' and colors the negative values
in Red and the positive values in Blue. It will also add a dollar sign in front
of the numbers which use a thousand seperator and display to two decimal places.
.EXAMPLE
>
@@ -216,7 +222,9 @@
PhoneNr3 = '+3244444444'
} | Export-Excel @ExcelParams -NoNumberConversion IPAddress, Number1
Exports all data to the Excel file 'Excel.xslx' and tries to convert all values to numbers where possible except for 'IPAddress' and 'Number1'. These are stored in the sheet 'as is', without being converted to a number.
Exports all data to the Excel file "Excel.xlsx" and tries to convert all values
to numbers where possible except for "IPAddress" and "Number1", which are
stored in the sheet 'as is', without being converted to a number.
.EXAMPLE
>
@@ -242,7 +250,9 @@
PhoneNr3 = '+3244444444'
} | Export-Excel @ExcelParams -NoNumberConversion *
Exports all data to the Excel file 'Excel.xslx' as is, no number conversion will take place. This means that Excel will show the exact same data that you handed over to the 'Export-Excel' function.
Exports all data to the Excel file 'Excel.xslx' as is, no number conversion
will take place. This means that Excel will show the exact same data that
you handed over to the 'Export-Excel' function.
.EXAMPLE
>
@@ -257,9 +267,11 @@
New-ConditionalText -ConditionalType GreaterThan 525 -ConditionalTextColor DarkRed -BackgroundColor LightPink
)
Exports data that will have a 'Conditional formatting rule' in Excel on these cells that will show the background fill color in
'LightPink' and the text color in 'DarkRed' when the value is greater than '525'. In case this condition is not met the color will
be the default, black text on a white background.
Exports data that will have a Conditional Formatting rule in Excel
that will show cells with a value is greater than 525, whith a
background fill color of "LightPink" and the text in "DarkRed".
Where condition is not met the color willbe the default, black
text on a white background.
.EXAMPLE
>
@@ -275,7 +287,12 @@
New-ConditionalText Running Blue Cyan
)
Export all services to an Excel sheet where all cells have a 'Conditional formatting rule' in Excel that will show the background fill color in 'LightPink' and the text color in 'DarkRed' when the value contains the word 'Stop'. If the value contains the word 'Running' it will have a background fill color in 'Cyan' and a text color 'Blue'. In case none of these conditions are met the color will be the default, black text on a white background.
Exports all services to an Excel sheet, setting a Conditional formatting rule
that will set the background fill color to "LightPink" and the text color
to "DarkRed" when the value contains the word "Stop".
If the value contains the word "Running" it will have a background fill
color of "Cyan" and text colored 'Blue'. If neither condition is met, the
color will be the default, black text on a white background.
.EXAMPLE
>
@@ -310,7 +327,8 @@
$Array | Out-GridView -Title 'Not showing Member3 and Member4'
$Array | Update-FirstObjectProperties | Export-Excel @ExcelParams -WorksheetName Numbers
Updates the first object of the array by adding property 'Member3' and 'Member4'. Afterwards. all objects are exported to an Excel file and all column headers are visible.
Updates the first object of the array by adding property 'Member3' and 'Member4'.
Afterwards. all objects are exported to an Excel file and all column headers are visible.
.EXAMPLE
Get-Process | Export-Excel .\test.xlsx -WorksheetName Processes -IncludePivotTable -Show -PivotRows Company -PivotData PM
@@ -341,10 +359,10 @@
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 third and final call adds the two pivot tables and opens the spreadsheet in Excel.
This example defines two PivotTables. 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 third and final call adds the two PivotTables
and opens the spreadsheet in Excel.
.EXAMPLE
>
PS> Remove-Item -Path .\test.xlsx
@@ -356,8 +374,11 @@
$excel.Dispose()
Start-Process .\test.xlsx
This example uses -passthrough. It puts service information into sheet1 of the workbook 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.
This example uses -PassThru. It puts service information into sheet1 of the
workbook and saves the ExcelPackage object 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. Other commands in the module remove the need
to work directly with the package object in this way.
.EXAMPLE
>
@@ -375,8 +396,9 @@
foreach ($c in 5..9) {Set-ExcelRange -Address $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-ExcelRange, and also adding conditional formatting.
In the final command a Pivot chart is added and the workbook is opened in Excel.
This a more sophisticated version of the previous example showing different
ways of using Set-ExcelRange, and also adding conditional formatting.
In the final command a PivotChart is added and the workbook is opened in Excel.
.EXAMPLE
0..360 | ForEach-Object {[pscustomobject][ordered]@{X=$_; Sinx="=Sin(Radians(x)) "} } | Export-Excel -now -LineChart -AutoNameRange
@@ -416,7 +438,7 @@
[OfficeOpenXml.Style.ExcelFillStyle]$TitleFillPattern = 'Solid',
[Switch]$TitleBold,
[Int]$TitleSize = 22,
[System.Drawing.Color]$TitleBackgroundColor,
$TitleBackgroundColor,
[Switch]$IncludePivotTable,
[String]$PivotTableName,
[String[]]$PivotRows,
@@ -482,12 +504,12 @@
[Object[]]$ConditionalFormat,
[Object[]]$ConditionalText,
[ScriptBlock]$CellStyleSB,
#If there is already content in the workbook the sheet with the Pivot table will not be active UNLESS Activate is specified
#If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified
[switch]$Activate,
[Parameter(ParameterSetName = 'Now')]
[Switch]$Now,
[Switch]$ReturnRange,
#By default Pivot tables have Totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected.
#By default PivotTables have Totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected.
[ValidateSet("Both","Columns","Rows","None")]
[String]$PivotTotals = "Both",
#Included for compatibility - equivalent to -PivotTotals "None"
@@ -665,6 +687,7 @@
$ws.Cells[$Row, $StartColumn].Style.Font.Bold = $True
}
if ($TitleBackgroundColor ) {
if ($TitleBackgroundColor -is [string]) {$TitleBackgroundColor = [System.Drawing.Color]::$TitleBackgroundColor }
$ws.Cells[$Row, $StartColumn].Style.Fill.PatternType = $TitleFillPattern
$ws.Cells[$Row, $StartColumn].Style.Fill.BackgroundColor.SetColor($TitleBackgroundColor)
}
@@ -739,7 +762,7 @@
foreach ($Name in $script:Header) {
try {Add-CellValue -TargetCell $ws.Cells[$Row, $ColumnIndex] -CellValue $TargetData.$Name}
catch {Write-Warning -Message "Could not insert the $Name property at Row $Row, Column $Column"}
catch {Write-Warning -Message "Could not insert the '$Name' property at Row $Row, Column $ColumnIndex"}
$ColumnIndex += 1
}
$ColumnIndex -= 1 # column index will be the last column whether isDataTypeValueType was true or false
@@ -833,7 +856,7 @@
'SourceRange' = $dataRange
}
if ($PivotTableName -and ($pkg.workbook.worksheets.tables.name -contains $PivotTableName)) {
Write-Warning -Message "The selected Pivot table name '$PivotTableName' is already used as a table name. Adding a suffix of 'Pivot'."
Write-Warning -Message "The selected PivotTable name '$PivotTableName' is already used as a table name. Adding a suffix of 'Pivot'."
$PivotTableName += 'Pivot'
}
@@ -1001,7 +1024,7 @@
Write-Verbose -Message "Added conditional formatting to range $($c.range)"
}
elseif ($c -is [hashtable] -or $c -is[System.Collections.Specialized.OrderedDictionary]) {
if (-not $c.Range) {$c.Range = $ws.Dimension.Address }
if (-not $c.Range -or $c.Address) {$c.Address = $ws.Dimension.Address }
Add-ConditionalFormatting -WorkSheet $ws @c
}
}
@@ -1183,7 +1206,7 @@ function Select-Worksheet {
Sets the selected tab in an Excel workbook to be the chosen sheet and unselects all the others.
.DESCRIPTION
Sometimes when a sheet is added we want it to be the active sheet, sometimes we want the active sheet to be left as it was.
Select-Worksheet exists to change the which sheet is the selected tab when Excel opens the file.
Select-Worksheet exists to change which sheet is the selected tab when Excel opens the file.
.EXAMPLE
Select-Worksheet -ExcelWorkbook $ExcelWorkbook -WorksheetName "NewSheet"
$ExcelWorkbook holds a workbook object containing a sheet named "NewSheet";
@@ -1194,10 +1217,11 @@ function Select-Worksheet {
This sheet will become the [only] active sheet in the workbook.
.EXAMPLE
Select-Worksheet -ExcelWorksheet $ws
$ws holds an Excel worksheet which will become the [only] active sheet in the workbook.
$ws holds an Excel worksheet which will become the [only] active sheet
in its workbook.
#>
param (
#An object representing an Excel Package.
#An object representing an ExcelPackage.
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Package', Position = 0)]
[OfficeOpenXml.ExcelPackage]$ExcelPackage,
#An Excel workbook to which the Worksheet will be added - a package contains one Workbook so you can use workbook or package as it suits.
@@ -1205,7 +1229,7 @@ function Select-Worksheet {
[OfficeOpenXml.ExcelWorkbook]$ExcelWorkbook,
[Parameter(ParameterSetName='Package')]
[Parameter(ParameterSetName='Workbook')]
#The name of the worksheet 'Sheet1' by default.
#The name of the worksheet "Sheet1" by default.
[string]$WorksheetName,
#An object representing an Excel worksheet.
[Parameter(ParameterSetName='Sheet',Mandatory=$true)]

View File

@@ -3,10 +3,13 @@
.SYNOPSIS
Combines data on all the sheets in an Excel worksheet onto a single sheet.
.DESCRIPTION
Join worksheet can work in two main ways:
Either Combining data which has the same layout from many pages into one, or combining pages which have nothing in common.
In the former case the header row is copied from the first sheet and, by default, each row of data is labelled with the name of the sheet it came from.
In the latter case -NoHeader is specified, and each copied block can have the sheet it came from placed above it as a title.
Join-Worksheet can work in two main ways, either
Combining data which has the same layout from many pages into one, or
combining pages which have nothing in common.
In the former case the header row is copied from the first sheet and,
by default, each row of data is labelled with the name of the sheet it came from.
In the latter case -NoHeader is specified, and each copied block can have the
sheet it came from placed above it as a title.
.EXAMPLE
>
PS> foreach ($computerName in @('Server1', 'Server2', 'Server3', 'Server4')) {
@@ -16,11 +19,15 @@
PS> $ptDef =New-PivotTableDefinition -PivotTableName "Pivot1" -SourceWorkSheet "Combined" -PivotRows "Status" -PivotFilter "MachineName" -PivotData @{Status='Count'} -IncludePivotChart -ChartType BarClustered3D
PS> Join-Worksheet -Path .\test.xlsx -WorkSheetName combined -FromLabel "MachineName" -HideSource -AutoSize -FreezeTopRow -BoldTopRow -PivotTableDefinition $pt -Show
The foreach command gets the services running on four servers and exports each to its own page in Test.xlsx.
$PtDef= creates a defintion for a PivotTable.
The Join-Worksheet command uses the same file and merges the results onto a sheet named "Combined". It sets a column header of "Machinename",
this column will contain the name of the sheet the data was copied from; after copying the data to the sheet "combined", the other sheets will be hidden.
Join-Worksheet finishes by calling Export-Excel to AutoSize cells, freeze the top row and make it bold and add the Pivot table.
The foreach command gets the services running on four servers and exports each
to its own page in Test.xlsx.
$PtDef= creates a definition for a PivotTable.
The Join-Worksheet command uses the same file and merges the results into a sheet
named "Combined". It sets a column header of "Machinename", this column will
contain the name of the sheet the data was copied from; after copying the data
to the sheet "Combined", the other sheets will be hidden.
Join-Worksheet finishes by calling Export-Excel to AutoSize cells, freeze the
top row and make it bold and add thePivotTable.
.EXAMPLE
>
@@ -30,10 +37,14 @@
Export-Excel -Path "$env:COMPUTERNAME.xlsx" -WorkSheetname NetAdapter
PS> Join-Worksheet -Path "$env:COMPUTERNAME.xlsx" -WorkSheetName Summary -Title "Summary" -TitleBold -TitleSize 22 -NoHeader -LabelBlocks -AutoSize -HideSource -show
The first two commands get logical disk and network card information; each type is exported to its own sheet in a workbook.
The Join-Worksheet command copies both onto a page named "Summary". Because the data is disimilar -NoHeader is specified, ensuring the whole of each page is copied.
Specifying -LabelBlocks causes each sheet's name to become a title on the summary page above the copied data.
The source data is hidden, a title is added in 22 point boldface and the columns are sized to fit the data.
The first two commands get logical-disk and network-card information; each type
is exported to its own sheet in a workbook.
The Join-Worksheet command copies both onto a page named "Summary". Because
the data is dissimilar, -NoHeader is specified, ensuring the whole of each
page is copied. Specifying -LabelBlocks causes each sheet's name to become
a title on the summary page above the copied data. The source data is
hidden, a title is added in 22 point boldface and the columns are sized
to fit the data.
#>
[CmdletBinding(DefaultParameterSetName = 'Default')]
param (
@@ -41,21 +52,21 @@
[Parameter(ParameterSetName = "Default", Position = 0)]
[Parameter(ParameterSetName = "Table" , Position = 0)]
[String]$Path ,
# An object representing an Excel Package - usually this is returned by specifying -Passthru allowing multiple commands to work on the same Workbook without saving and reloading each time.
# An object representing an Excel Package - either from Open-Excel Package or specifying -PassThru to Export-Excel.
[Parameter(Mandatory = $true, ParameterSetName = "PackageDefault")]
[Parameter(Mandatory = $true, ParameterSetName = "PackageTable")]
[OfficeOpenXml.ExcelPackage]$ExcelPackage,
# The name of a sheet within the workbook where the other sheets will be joined together - "Combined" by default.
$WorkSheetName = 'Combined',
# If specified any pre-existing target for the joined data will be deleted and re-created; otherwise data will be appended on this sheet.
# If specified ,any pre-existing target for the joined data will be deleted and re-created; otherwise data will be appended on this sheet.
[switch]$Clearsheet,
#Join-Worksheet assumes each sheet has identical headers and the headers should be copied to the target sheet, unless -NoHeader is specified.
[switch]$NoHeader,
#If -NoHeader is NOT specified, then rows of data will be labeled with the name of the sheet they came, FromLabel is the header for this column. If it is null or empty, the labels will be omitted.
#If -NoHeader is NOT specified, then rows of data will be labeled with the name of the sheet they came from. FromLabel is the header for this column. If it is null or empty, the labels will be omitted.
$FromLabel = "From" ,
#If specified, the copied blocks of data will have the name of the sheet they were copied from inserted above them as a title.
[switch]$LabelBlocks,
#Sizes the width of the Excel column to the maximum width needed to display all the containing data in that cell.
#Sets the width of the Excel columns to display all the data in their cells.
[Switch]$AutoSize,
#Freezes headers etc. in the top row.
[Switch]$FreezeTopRow,
@@ -65,25 +76,25 @@
[Switch]$FreezeTopRowFirstColumn,
# Freezes panes at specified coordinates (in the form RowNumber , ColumnNumber).
[Int[]]$FreezePane,
#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.
#Enables the Excel filter on the headers of the combined sheet.
[Parameter(ParameterSetName = 'Default')]
[Parameter(ParameterSetName = 'PackageDefault')]
[Switch]$AutoFilter,
#Makes the top Row boldface.
#Makes the top row boldface.
[Switch]$BoldTopRow,
#If Specified hides the sheets that the data is copied from.
#If specified, hides the sheets that the data is copied from.
[switch]$HideSource,
#Text of a title to be placed in Cell A1.
[String]$Title,
#Sets the fill pattern for the title cell.
[OfficeOpenXml.Style.ExcelFillStyle]$TitleFillPattern = 'Solid',
#Sets the cell background color for the title cell.
[System.Drawing.Color]$TitleBackgroundColor,
$TitleBackgroundColor,
#Sets the title in boldface type.
[Switch]$TitleBold,
#Sets the point size for the title.
[Int]$TitleSize = 22,
#Hashtable(s) with Sheet PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values to specify a definition for one or more pivot table(s).
#Hashtable(s) with Sheet PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values to specify a definition for one or morePivotTable(s).
[Hashtable]$PivotTableDefinition,
#A hashtable containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-pivot] charts.
[Object[]]$ExcelChartDefinition,
@@ -107,13 +118,13 @@
})]
[Parameter(ParameterSetName = 'Table' , Mandatory = $true)]
[Parameter(ParameterSetName = 'PackageTable' , Mandatory = $true)]
# Makes the data in the worksheet a table with a name applies a style to it. Name must not contain spaces.
# Makes the data in the worksheet a table with a name and applies a style to it. Name must not contain spaces.
[String]$TableName,
[Parameter(ParameterSetName = 'Table')]
[Parameter(ParameterSetName = 'PackageTable')]
#Selects the style for the named table - defaults to 'Medium6'.
#Selects the style for the named table - defaults to "Medium6".
[OfficeOpenXml.Table.TableStyles]$TableStyle = 'Medium6',
#Selects the style for the named table - defaults to 'Medium6'.
#If specified, returns the range of cells in the combined sheet, in the format "A1:Z100".
[switch]$ReturnRange,
#Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first.
[switch]$Show,
@@ -138,6 +149,7 @@
if ($TitleBold) {$destinationSheet.Cells[1, 1].Style.Font.Bold = $True }
#Can only set TitleBackgroundColor if TitleFillPattern is something other than None.
if ($TitleBackgroundColor -AND ($TitleFillPattern -ne 'None')) {
if ($TitleBackgroundColor -is [string]) {$TitleBackgroundColor = [System.Drawing.Color]::$TitleBackgroundColor }
$destinationSheet.Cells[1, 1].Style.Fill.PatternType = $TitleFillPattern
$destinationSheet.Cells[1, 1].Style.Fill.BackgroundColor.SetColor($TitleBackgroundColor)
}

View File

@@ -4,29 +4,36 @@
Merges two Worksheets (or other objects) into a single Worksheet with differences marked up.
.Description
The Compare-Worksheet command takes two Worksheets and marks differences in the source document, and optionally outputs a grid showing the changes.
By contrast the Merge-Worksheet command takes the Worksheets and combines them into a single sheet showing the old and new data side by side .
Although it is designed to work with Excel data it can work with arrays of any kind of object; so it can be a merge *of* Worksheets, or a merge *to* Worksheet.
By contrast the Merge-Worksheet command takes the Worksheets and combines them into a single sheet showing the old and new data side by side.
Although it is designed to work with Excel data it can work with arrays of any kind of object; so it can be a merge *of* Worksheets, or a merge *to* a Worksheet.
.Example
merge-Worksheet "Server54.xlsx" "Server55.xlsx" -WorksheetName services -OutputFile Services.xlsx -OutputSheetName 54-55 -show
The workbooks contain audit information for two servers, one page contains a list of services. This command creates a Worksheet named 54-55
in a workbook named services which shows all the services and their differences, and opens it in Excel.
Merge-Worksheet "Server54.xlsx" "Server55.xlsx" -WorksheetName services -OutputFile Services.xlsx -OutputSheetName 54-55 -show
The workbooks contain audit information for two servers, one sheet contains
a list of services. This command creates a worksheet named "54-55" in a
workbook named "services.xlsx" which shows all the services and their
differences, and opens the new workbook in Excel.
.Example
merge-Worksheet "Server54.xlsx" "Server55.xlsx" -WorksheetName services -OutputFile Services.xlsx -OutputSheetName 54-55 -HideEqual -AddBackgroundColor LightBlue -show
This modifies the previous command to hide the equal rows in the output sheet and changes the color used to mark rows added to the second file.
Merge-Worksheet "Server54.xlsx" "Server55.xlsx" -WorksheetName services -OutputFile Services.xlsx -OutputSheetName 54-55 -HideEqual -AddBackgroundColor LightBlue -show
This modifies the previous command to hide the equal rows in the output
sheet and changes the color used to mark rows added to the second file.
.Example
merge-Worksheet -OutputFile .\j1.xlsx -OutputSheetName test11 -ReferenceObject (dir .\ImportExcel\4.0.7) -DifferenceObject (dir .\ImportExcel\4.0.8) -Property Length -Show
Merge-Worksheet -OutputFile .\j1.xlsx -OutputSheetName test11 -ReferenceObject (dir .\ImportExcel\4.0.7) -DifferenceObject (dir .\ImportExcel\4.0.8) -Property Length -Show
This version compares two directories, and marks what has changed.
Because no "Key" property is given, "Name" is assumed to be the key and the only other property examined is length.
Files which are added or deleted or have changed size will be highlighed in the output sheet. Changes to dates or other attributes will be ignored.
Because no "Key" property is given, "Name" is assumed to be the key
and the only other property examined is length. Files which are added
or deleted or have changed size will be highlighed in the output sheet.
Changes to dates or other attributes will be ignored.
.Example
merge-Worksheet -RefO (dir .\ImportExcel\4.0.7) -DiffO (dir .\ImportExcel\4.0.8) -Pr Length | Out-GridView
This time no file is written and the results -which include all properties, not just length, are output and sent to Out-Gridview.
This version uses aliases to shorten the parameters,
(OutputFileName can be "outFile" and the sheet "OutSheet" : DifferenceObject & ReferenceObject can be DiffObject & RefObject).
Merge-Worksheet -RefO (dir .\ImportExcel\4.0.7) -DiffO (dir .\ImportExcel\4.0.8) -Pr Length | Out-GridView
This time no file is written and the results - which include all properties,
not just length, are output and sent to Out-Gridview. This version uses
aliases to shorten the parameters, (OutputFileName can be "outFile" and
the Sheet can be"OutSheet"; DifferenceObject & ReferenceObject can be
DiffObject & RefObject respectively).
#>
[cmdletbinding(SupportsShouldProcess=$true)]
Param(
#First Excel file to compare. You can compare two Excel files or two other objects but not one of each.
#First Excel file to compare. You can compare two Excel files or two other objects or a reference obhct against a difference file, but not a reference file against an object.
[parameter(ParameterSetName='A',Mandatory=$true,Position=0)] #A = Compare two files default headers
[parameter(ParameterSetName='B',Mandatory=$true,Position=0)] #B = Compare two files user supplied headers
[parameter(ParameterSetName='C',Mandatory=$true,Position=0)] #C = Compare two files headers P1, P2, P3 etc
@@ -36,12 +43,12 @@
[parameter(ParameterSetName='A',Mandatory=$true,Position=1)]
[parameter(ParameterSetName='B',Mandatory=$true,Position=1)]
[parameter(ParameterSetName='C',Mandatory=$true,Position=1)]
[parameter(ParameterSetName='E',Mandatory=$true,Position=1)] #D Compat two objects; E = Compare one object one file that uses default headers
[parameter(ParameterSetName='E',Mandatory=$true,Position=1)] #D Compare two objects; E = Compare one object one file that uses default headers
[parameter(ParameterSetName='F',Mandatory=$true,Position=1)] #F = Compare one object one file that uses user supplied headers
[parameter(ParameterSetName='G',Mandatory=$true,Position=1)] #G Compare one object one file that uses headers P1, P2, P3 etc
$Differencefile ,
#Name(s) of Worksheets to compare,
#Name(s) of Worksheets to compare.
[parameter(ParameterSetName='A',Position=2)] #Applies to all sets EXCEPT D which is two objects (no sheets)
[parameter(ParameterSetName='B',Position=2)]
[parameter(ParameterSetName='C',Position=2)]
@@ -59,12 +66,12 @@
[parameter(ParameterSetName='G')]
[int]$Startrow = 1,
#Specifies custom property names to use, instead of the values defined in the column headers of the TopRow.
#Specifies custom property names to use, instead of the values defined in the column headers of the Start ROw.
[Parameter(ParameterSetName='B',Mandatory=$true)] #Compare object + sheet or 2 sheets with user supplied headers
[Parameter(ParameterSetName='F',Mandatory=$true)]
[String[]]$Headername,
#Automatically generate property names (P1, P2, P3, ..) instead of the using the values the top row of the sheet.
#Automatically generate property names (P1, P2, P3, ..) instead of using the values the top row of the sheet.
[Parameter(ParameterSetName='C',Mandatory=$true)] #Compare object + sheet or 2 sheets with headers of P1, P2, P3 ...
[Parameter(ParameterSetName='G',Mandatory=$true)]
[switch]$NoHeader,
@@ -101,16 +108,16 @@
#Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name".
$Key = "Name" ,
#Sets the font color for the "key" field; this means you can filter by color to get only changed rows.
[System.Drawing.Color]$KeyFontColor = "DarkRed",
$KeyFontColor = [System.Drawing.Color]::DarkRed ,
#Sets the background color for changed rows.
[System.Drawing.Color]$ChangeBackgroundColor = "Orange",
$ChangeBackgroundColor = [System.Drawing.Color]::Orange,
#Sets the background color for rows in the reference but deleted from the difference sheet.
[System.Drawing.Color]$DeleteBackgroundColor = "LightPink",
$DeleteBackgroundColor = [System.Drawing.Color]::LightPink,
#Sets the background color for rows not in the reference but added to the difference sheet.
[System.Drawing.Color]$AddBackgroundColor = "PaleGreen",
#if Specified hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows.
$AddBackgroundColor = [System.Drawing.Color]::PaleGreen,
#if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows.
[switch]$HideEqual ,
#If specified outputs the data to the pipeline (you can add -whatif so it the command only outputs to the pipeline).
#If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline).
[switch]$Passthru ,
#If specified, opens the output workbook.
[Switch]$Show
@@ -311,39 +318,59 @@ Function Merge-MultipleSheets {
.Synopsis
Merges Worksheets into a single Worksheet with differences marked up.
.Description
The Merge Worksheet command combines 2 sheets. Merge-MultipleSheets is designed to merge more than 2.
So if asked to merge sheets A,B,C which contain Services, with a Name, Displayname and Start mode, where "name" is treated as the key
Merge-MultipleSheets calls Merge-Worksheet to merge Name, Displayname and Start mode, from sheets A and C
the result has column headings -Row, Name, DisplayName, Startmode, C-DisplayName, C-StartMode C-Is, C-Row
Merge-MultipleSheets then calls Merge-Worsheet with this result and sheet B, comparing 'Name', 'Displayname' and 'Start mode' columns on each side
which outputs _Row, Name, DisplayName, Startmode, B-DisplayName, B-StartMode B-Is, B-Row, C-DisplayName, C-StartMode C-Is, C-Row
Any columns in the "reference" side which are not used in the comparison are appended on the right, which is we compare the sheets in reverse order.
The Merge Worksheet command combines two sheets. Merge-MultipleSheets is
designed to merge more than two. So if asked to merge sheets A,B,C which
contain Services, with a Name, Displayname and Start mode, where "Name" is
treated as the key, Merge-MultipleSheets calls Merge-Worksheet to merge
"Name", "Displayname" and "Startmode" from sheets A and C; the result has
column headings "_Row", "Name", "DisplayName", "Startmode", "C-DisplayName",
"C-StartMode", "C-Is" and "C-Row".
Merge-MultipleSheets then calls Merge-Worksheet again passing it the
intermediate result and sheet B, comparing "Name", "Displayname" and
"Start mode" columns on each side, and gets a result with columns "_Row",
"Name", "DisplayName", "Startmode", "B-DisplayName", "B-StartMode", "B-Is",
"B-Row", "C-DisplayName", "C-StartMode", "C-Is" and "C-Row". Any columns on
the "reference" side which are not used in the comparison are added on the
right, which is why we compare the sheets in reverse order.
The "Is" column holds "Same", "Added", "Removed" or "Changed" and is used for conditional formatting in the output sheet (this is hidden by default),
and when the data is written to Excel the "reference" columns, in this case "DisplayName" and "Start" are renamed to reflect their source,
so become "A-DisplayName" and "A-Start".
The "Is" columns hold "Same", "Added", "Removed" or "Changed" and is used for
conditional formatting in the output sheet (these columns are hidden by default),
and when the data is written to Excel the "reference" columns, in this case
"DisplayName" and "Start" are renamed to reflect their source, so become
"A-DisplayName" and "A-Start".
Conditional formatting is also applied to the "key" column (name in this case) so the view can be filtered to rows with changes by filtering this column on color.
Conditional formatting is also applied to the Key column ("Name" in this
case) so the view can be filtered to rows with changes by filtering this
column on color.
Note: the processing order can affect what is seen as a change. For example if there is an extra item in sheet B in the example above,
Sheet C will be processed and that row and will not be seen to be missing. When sheet B is processed it is marked as an addition, and the conditional formatting marks
the entries from sheet A to show that a values were added in at least one sheet.
However if Sheet B is the reference sheet, A and C will be seen to have an item removed;
and if B is processed before C, the extra item is known when C is processed and so C is considered to be missing that item.
Note: the processing order can affect what is seen as a change. For example
if there is an extra item in sheet B in the example above, Sheet C will be
processed and that row and will not be seen to be missing. When sheet B is
processed it is marked as an addition, and the conditional formatting marks
the entries from sheet A to show that a values were added in at least one
sheet. However if Sheet B is the reference sheet, A and C will be seen to
have an item removed; and if B is processed before C, the extra item is
known when C is processed and so C is considered to be missing that item.
.Example
dir Server*.xlsx | Merge-MulipleSheets -WorksheetName Services -OutputFile Test2.xlsx -OutputSheetName Services -Show
We are auditing servers and each one has a workbook in the current directory which contains a "Services" Worksheet (the result of
Get-WmiObject -Class win32_service | Select-Object -Property Name, Displayname, Startmode
No key is specified so the key is assumed to be the "Name" column. The files are merged and the result is opened on completion.
Here we are auditing servers and each one has a workbook in the current
directory which contains a "Services" Worksheet (the result of
Get-WmiObject -Class win32_service | Select-Object -Property Name, Displayname, Startmode)
No key is specified so the key is assumed to be the "Name" column.
The files are merged and the result is opened on completion.
.Example
dir Serv*.xlsx | Merge-MulipleSheets -WorksheetName Software -Key "*" -ExcludeProperty Install* -OutputFile Test2.xlsx -OutputSheetName Software -Show
The server audit files in the previous example also have "Software" Worksheet, but no single field on that sheet works as a key.
Specifying "*" for the key produces a compound key using all non-excluded fields (and the installation date and file location are excluded).
The server audit files in the previous example also have "Software" worksheet,
but no single field on that sheet works as a key. Specifying "*" for the key
produces a compound key using all non-excluded fields (and the installation
date and file location are excluded).
.Example
Merge-MulipleSheets -Path hotfixes.xlsx -WorksheetName Serv* -Key hotfixid -OutputFile test2.xlsx -OutputSheetName hotfixes -HideRowNumbers -Show
This time all the servers have written their hofix information to their own Worksheets in a shared Excel workbook named "Hotfixes"
(the information was obtained by running Get-Hotfix | Sort-Object -Property description,hotfixid | Select-Object -Property Description,HotfixID)
This ignores any sheets which are not named "Serv*", and uses the HotfixID as the key ; in this version the row numbers are hidden.
This time all the servers have written their hotfix information to their own
worksheets in a shared Excel workbook named "Hotfixes.xlsx" (the information was
obtained by running Get-Hotfix | Sort-Object -Property description,hotfixid | Select-Object -Property Description,HotfixID)
This ignores any sheets which are not named "Serv*", and uses the HotfixID as
the key; in this version the row numbers are hidden.
#>
[cmdletbinding()]
#[Alias("Merge-MulipleSheets")] #There was a spelling error in the first release. This was there to ensure things didn't break but intelisense gave the alias first.
@@ -351,40 +378,40 @@ Function Merge-MultipleSheets {
#Paths to the files to be merged.
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[string[]]$Path ,
#The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row.
#The row from where we start to import data, all rows above the Start row are disregarded. By default this is the first row.
[int]$Startrow = 1,
#Specifies custom property names to use, instead of the values defined in the column headers of the TopRow.
#Specifies custom property names to use, instead of the values defined in the column headers of the Start row.
[String[]]$Headername,
#Automatically generate property names (P1, P2, P3, ..) instead of the using the values the top row of the sheet.
#If specified, property names will be automatically generated (P1, P2, P3, ..) instead of using the values from the start row.
[switch]$NoHeader,
#Name(s) of Worksheets to compare,
#Name(s) of Worksheets to compare.
$WorksheetName = "Sheet1",
#File to write output to
#File to write output to.
[Alias('OutFile')]
$OutputFile = ".\temp.xlsx",
#Name of Worksheet to output - if none specified will use the reference Worksheet name.
[Alias('OutSheet')]
$OutputSheetName = "Sheet1",
#Properties to include in the DIFF - supports wildcards, default is "*".
#Properties to include in the comparison - supports wildcards, default is "*".
$Property = "*" ,
#Properties to exclude from the the search - supports wildcards.
#Properties to exclude from the the comparison - supports wildcards.
$ExcludeProperty ,
#Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name".
#Name of a column which is unique used to pair up rows from the reference and difference sides, default is "Name".
$Key = "Name" ,
#Sets the font color for the "key" field; this means you can filter by color to get only changed rows.
[System.Drawing.Color]$KeyFontColor = "Red",
#Sets the font color for the Key field; this means you can filter by color to get only changed rows.
$KeyFontColor = [System.Drawing.Color]::Red,
#Sets the background color for changed rows.
[System.Drawing.Color]$ChangeBackgroundColor = "Orange",
$ChangeBackgroundColor = [System.Drawing.Color]::Orange,
#Sets the background color for rows in the reference but deleted from the difference sheet.
[System.Drawing.Color]$DeleteBackgroundColor = "LightPink",
$DeleteBackgroundColor = [System.Drawing.Color]::LightPink,
#Sets the background color for rows not in the reference but added to the difference sheet.
[System.Drawing.Color]$AddBackgroundColor = "Orange",
#if Specified hides the columns in the spreadsheet that contain the row numbers
$AddBackgroundColor = [System.Drawing.Color]::Orange,
#If specified, hides the columns in the spreadsheet that contain the row numbers.
[switch]$HideRowNumbers ,
#If specified outputs the data to the pipeline (you can add -whatif so it the command only outputs to the command)
#If specified, outputs the data to the pipeline (you can add -whatif so it the command only outputs to the pipeline).
[switch]$Passthru ,
#If specified, opens the output workbook.
[Switch]$Show

View File

@@ -1,16 +1,16 @@
function New-ConditionalFormattingIconSet {
<#
.SYNOPSIS
Creates an object which describes a conditional formatting rule a for 3,4 or 5 icon set
Creates an object which describes a conditional formatting rule a for 3,4 or 5 icon set.
.DESCRIPTION
Export-Excel takes a -ConditionalFormat parameter which can hold one or more descriptions for conditional formats;
this command builds the
this command builds the defintion of a Conditional formatting rule for an icon set.
.PARAMETER Range
The range of cells that the conditional format applies to
The range of cells that the conditional format applies to.
.PARAMETER ConditionalFormat
The type of rule: one of "ThreeIconSet","FourIconSet" or "FiveIconSet"
.PARAMETER IconType
The name of an iconSet - different icons are available depending on whether 3,4 or 5 icon set is selected
The name of an iconSet - different icons are available depending on whether 3,4 or 5 icon set is selected.
.PARAMETER Reverse
Use the icons in the reverse order.
.Example
@@ -18,9 +18,14 @@ function New-ConditionalFormattingIconSet {
$cfdef = New-ConditionalFormattingIconSet -Range $cfrange -ConditionalFormat ThreeIconSet -IconType Arrows
Export-Excel -ExcelPackage $excel -ConditionalFormat $cfdef -show
The first line creates a range - one column wide in the column $column, running from $topRow to $lastDataRow.
The second creates a definition object using this range
and the third uses Export-Excel with an open package to apply the format and save and open the file.
The first line creates a range - one column wide in the column $column, running
from $topRow to $lastDataRow.
The second line creates a definition object using this range
and the third uses Export-Excel with an open package to apply the format and
save and open the file.
.Link
Add-Add-ConditionalFormatting
New-ConditionalText
#>
param(
[Parameter(Mandatory=$true)]

View File

@@ -5,7 +5,7 @@ function New-ConditionalText {
.DESCRIPTION
Some Conditional formatting rules don't apply styles to a cell (IconSets and Databars).
Some take two parameters (Between).
Some take none (ThisWeek , containsErrors, AboveAverage etc).
Some take none (ThisWeek, ContainsErrors, AboveAverage etc).
The others take a single parameter (Top, BottomPercent, GreaterThan, Contains etc).
This command creates an object to describe the last two categories, which can then be passed to Export-Excel.
.PARAMETER Range
@@ -13,35 +13,44 @@ function New-ConditionalText {
.PARAMETER ConditionalType
One of the supported rules; by default "ContainsText" is selected.
.PARAMETER Text
The text (or other value) to use in the rule. Not that Equals, GreaterThan/LessThan rules require text to wrapped in double quotes.
The text (or other value) to use in the rule. Note that Equals, GreaterThan/LessThan rules require text to wrapped in double quotes.
.PARAMETER ConditionalTextColor
The font color for the cell - by default: Dark red.
The font color for the cell - by default: "DarkRed".
.PARAMETER BackgroundColor
The fill color for the cell - by default: Light pink.
The fill color for the cell - by default: "LightPink".
.PARAMETER PatternType
The Background pattern for the cell - by default: Solid
The background pattern for the cell - by default: "Solid"
.EXAMPLE
>
$ct = New-ConditionalText -Text 'Ferrari'
Export-Excel -ExcelPackage $excel -ConditionalTest $ct -show
The first line creates a definition object which will highlight the word "Ferrari" in any cell.
and the second uses Export-Excel with an open package to apply the format and save and open the file.
The first line creates a definition object which will highlight the word
"Ferrari" in any cell. and the second uses Export-Excel with an open package
to apply the format and save and open the file.
.EXAMPLE
>
$ct = New-ConditionalText -Text "Ferrari"
$ct2 = New-ConditionalText -Range $worksheet.Names["FinishPosition"].Address -ConditionalType LessThanOrEqual -Text 3 -ConditionalTextColor Red -BackgroundColor White
Export-Excel -ExcelPackage $excel -ConditionalText $ct,$ct2 -show
This builds on the previous example, and specifies a condition of <=3 with a format of Red text on a white background; this applies to a named range "Finish Position"
the range could be written "C:C" to specify a named column, or "C2:C102" to specify certain cells in the column.
This builds on the previous example, and specifies a condition of <=3 with
a format of red text on a white background; this applies to a named range
"Finish Position". The range could be written "C:C" to specify a named
column, or "C2:C102" to specify certain cells in the column.
.Link
Add-Add-ConditionalFormatting
New-ConditionalFormattingIconSet
#>
[cmdletbinding()]
param(
#[Parameter(Mandatory=$true)]
[Alias("ConditionValue")]
$Text,
[Alias("ForeGroundColor")]
[System.Drawing.Color]$ConditionalTextColor="DarkRed",
[System.Drawing.Color]$BackgroundColor="LightPink",
$ConditionalTextColor=[System.Drawing.Color]::DarkRed,
$BackgroundColor=[System.Drawing.Color]::LightPink,
[String]$Range,
[OfficeOpenXml.Style.ExcelFillStyle]$PatternType=[OfficeOpenXml.Style.ExcelFillStyle]::Solid,
[ValidateSet(

View File

@@ -20,23 +20,23 @@
.PARAMETER YRange
The range(s) of cells holding values for the Y-Axis - usually "data".
.PARAMETER Width
Width of the chart in Pixels. Defaults to 500.
Width of the chart in pixels. Defaults to 500.
.PARAMETER Height
Height of the chart in Pixels. Defaults to 350.
Height of the chart in pixels. Defaults to 350.
.PARAMETER Row
Row position of the top left corner of the chart. 0 places at the top of the sheet, 1 below row 1 and so on.
.PARAMETER RowOffSetPixels
Offset to position the chart by a fraction of of a row.
Offset to position the chart by a fraction of a row.
.PARAMETER Column
Column position of the top left corner of the chart. 0 places at the edge of the sheet 1 to the right of column A and so on.
.PARAMETER ColumnOffSetPixels
Offset to position the chart by a fraction of of a column.
Offset to position the chart by a fraction of a column.
.PARAMETER NoLegend
If specified, turns of display of the key. If you only have one data series it may be preferable to use the title to say what the chart is.
If specified, turns off display of the key. If you only have one data series it may be preferable to use the title to say what the chart is.
.PARAMETER SeriesHeader
Specify explicit name(s) for the data series, which will appear in the legend/key
Specifies explicit name(s) for the data series, which will appear in the legend/key
.PARAMETER LegendPosition
Location of the key, either left, right, top, bottom or TopRight.
Location of the key, either "Left", "Right", "Top", "Bottom" or "TopRight".
.PARAMETER LegendSize
Font size for the key.
.PARAMETER LegendBold
@@ -62,7 +62,7 @@
.PARAMETER XMinValue
Minimum value for the scale along the X-axis.
.PARAMETER xAxisPosition
Postion for the X-axis (Top or Bottom).
Position for the X-axis ("Top" or" Bottom").
.PARAMETER YAxisTitleText
Specifies a title for the Y-axis.
.PARAMETER YAxisTitleBold
@@ -80,7 +80,7 @@
.PARAMETER YMinValue
Minimum value on the Y-axis.
.PARAMETER YAxisPosition
Postion for the Y-axis (Left or Right).
Position for the Y-axis ("Left" or "Right").
.PARAMETER Header
No longer used. This may be removed in future versions.
.Example
@@ -92,7 +92,8 @@
0..360 | ForEach-Object {[pscustomobject][ordered]@{x = $_; Sinx = "=Sin(Radians(x)) "}} | Export-Excel -AutoNameRange -now -WorkSheetname SinX -ExcelChartDefinition $cDef -Show
This reworks an example from Add-Excel-Chart but here the chart definition is defined and then it is used in a call to Export-Excel.
This reworks an example from Add-Excel-Chart but here the chart is defined
and the defintion stored in $cDef and then Export-Excel uses $cDef .
#>
[Alias("New-ExcelChart")] #This was the former name. The new name reflects that we are defining a chart, not making one in the workbook.
[cmdletbinding()]

View File

@@ -1,19 +1,22 @@
Function Open-ExcelPackage {
<#
.Synopsis
Returns an Excel Package Object for the specified XLSX file
Returns an ExcelPackage object for the specified XLSX fil.e
.Description
Import-Excel and Export-Excel open an Excel file, carry out their tasks and close it again.
Sometimes it is necessary to open a file and do other work on it. Open-Excel package allows the file to be opened for these tasks.
It takes a KillExcel switch to make sure Excel is not holding the file open; a password parameter for existing protected files,
and a create switch to set-up a new file if no file already exists.
Sometimes it is necessary to open a file and do other work on it.
Open-ExcelPackage allows the file to be opened for these tasks.
It takes a -KillExcel switch to make sure Excel is not holding the file open;
a -Password parameter for existing protected files,
and a -Create switch to set-up a new file if no file already exists.
.Example
>
PS> $excel = Open-ExcelPackage -Path "$env:TEMP\test99.xlsx" -Create
$ws = Add-WorkSheet -ExcelPackage $excel
This will create a new file in the temp folder if it doesn't already exist. It then adds a worksheet -
because no name is specified it will use the default name of "Sheet1"
This will create a new file in the temp folder if it doesn't already exist.
It then adds a worksheet - because no name is specified it will use the
default name of "Sheet1"
.Example
>
PS> $excel = Open-ExcelPackage -path "$xlPath" -Password $password
@@ -21,20 +24,21 @@
Set-ExcelRange -Range $sheet1.Cells["E1:S1048576"], $sheet1.Cells["V1:V1048576"] -NFormat ([cultureinfo]::CurrentCulture.DateTimeFormat.ShortDatePattern)
Close-ExcelPackage $excel -Show
This will open the password protected file at $xlPath using the password stored in $Password.
Sheet1 is selected and formatting applied to two blocks of the sheet; then the file is and saved and loaded into Excel.
This will open the password protected file at $xlPath using the password stored
in $Password. Sheet1 is selected and formatting applied to two blocks of the sheet;
then the file is and saved and loaded into Excel.
#>
[CmdLetBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")]
[OutputType([OfficeOpenXml.ExcelPackage])]
Param (
#The Path to the file to open
#The path to the file to open.
[Parameter(Mandatory=$true)]$Path,
#If specified, any running instances of Excel will be terminated before opening the file.
[switch]$KillExcel,
#The password for a protected worksheet, as a [normal] string (not a secure string.)
#The password for a protected worksheet, as a [normal] string (not a secure string).
[String]$Password,
#By default open only opens an existing file; -Create instructs it to create a new file if required.
#By default Open-ExcelPackage will only opens an existing file; -Create instructs it to create a new file if required.
[switch]$Create
)

View File

@@ -130,16 +130,27 @@
C:\> Send-SQLDataToExcel -MsSQLserver -Connection localhost -SQL "select name,type,type_desc from [master].[sys].[all_objects]" -Path .\temp.xlsx -WorkSheetname master -AutoSize -FreezeTopRow -AutoFilter -BoldTopRow
Connects to the local SQL server and selects 3 columns from [Sys].[all_objects] and exports then to a sheet named master with some basic header management
.EXAMPLE
C:\> $SQL="SELECT top 25 Name,Length From TestData ORDER BY Length DESC"
C:\> $Connection = ' Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\Users\James\Documents\Database1.accdb;'
C:\> Send-SQLDataToExcel -Connection $connection -SQL $sql -path .\demo1.xlsx -WorkSheetname "Sizes" -AutoSize
This declares a SQL statement and creates an ODBC connection string to read from an Access file and extracts data from it and sends it to a new worksheet
.EXAMPLE
C:\> $SQL="SELECT top 25 DriverName, Count(RaceDate) as Races, Count(Win) as Wins, Count(Pole) as Poles, Count(FastestLap) as Fastlaps FROM Results GROUP BY DriverName ORDER BY (count(win)) DESC"
C:\> $Connection = 'Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DriverId=790;ReadOnly=0;Dbq=C:\users\James\Documents\f1Results.xlsx;'
C:\> Send-SQLDataToExcel -Connection $connection -SQL $sql -path .\demo1.xlsx -WorkSheetname "Winners" -AutoSize -AutoNameRange
C:\> $Connection = 'Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};Dbq=C:\users\James\Documents\f1Results.xlsx;'
C:\> Send-SQLDataToExcel -Connection $connection -SQL $sql -path .\demo1.xlsx -WorkSheetname "Winners" -AutoSize -AutoNameRange -ConditionalFormat @{DataBarColor="Blue"; Range="Wins"}
This declares a SQL statement and creates an ODBC connection string to read from an Excel file, it then runs the statement and outputs the resulting data to a new spreadsheet.
The spreadsheet is formatted and a data bar added to show make the drivers' wins clearer.
(the F1 results database is available from https://1drv.ms/x/s!AhfYu7-CJv4ehNdZWxJE9LMAX_N5sg )
.EXAMPLE
C:\> $SQL = "SELECT top 25 DriverName, Count(RaceDate) as Races, Count(Win) as Wins, Count(Pole) as Poles, Count(FastestLap) as Fastlaps FROM Results GROUP BY DriverName ORDER BY (count(win)) DESC"
C:\> Get-SQL -Session F1 -excel -Connection "C:\Users\mcp\OneDrive\public\f1\f1Results.xlsx" -sql $sql -OutputVariable Table | out-null
C:\> Send-SQLDataToExcel -DataTable $Table -Path ".\demo3.xlsx" -WorkSheetname Gpwinners -autosize -TableName winners -TableStyle Light6 -show
This uses Get-SQL (at least V1.1 - download from the gallery with Install-Module -Name GetSQL - note the function is Get-SQL the module is GetSQL without the "-" )
@@ -185,7 +196,7 @@
[OfficeOpenXml.Style.ExcelFillStyle]$TitleFillPattern = 'None',
[Switch]$TitleBold,
[Int]$TitleSize = 22,
[System.Drawing.Color]$TitleBackgroundColor,
$TitleBackgroundColor,
[String]$Password,
[Hashtable]$PivotTableDefinition,
[Switch]$IncludePivotTable,

View File

@@ -4,9 +4,9 @@
$Row,
$LastColumn,
[OfficeOpenXml.Style.ExcelFillStyle]$Pattern,
[System.Drawing.Color]$Color
$Color
)
if ($Color -is [string]) {$Color = [System.Drawing.Color]::$Color }
$t=$WorkSheet.Cells["A$($Row):$($LastColumn)$($Row)"]
$t.Style.Fill.PatternType=$Pattern
$t.Style.Fill.BackgroundColor.SetColor($Color)

View File

@@ -1,47 +1,57 @@
Function Set-ExcelColumn {
<#
.SYNOPSIS
Adds or modifies a column in an Excel sheet, filling values, settings formatting and/or creating named ranges.
Adds or modifies a column in an Excel worksheet, filling values, setting formatting and/or creating named ranges.
.DESCRIPTION
Set-ExcelColumn can take a value which is either a string containing a value or formula or a scriptblock
which evaluates to a string, and optionally a column number and fills that value down the column.
Set-ExcelColumn can take a value which is either a string containing a
value or formula or a scriptblock which evaluates to a string,
and optionally a column number and fills that value down the column.
A column heading can be specified, and the column can be made a named range.
The column can be formatted in the same operation.
.EXAMPLE
Set-ExcelColumn -Worksheet $ws -Column 5 -NumberFormat 'Currency'
$ws contains a worksheet object - and column E is set to use the local currency format.
Intelisense will complete predefined number formats. You can see how currency is interpreted on the local computer with the command
$ws contains a worksheet object - and column "E" is set to use the
local currency format. Intelisense will complete the names of predefined
number formats. You can see how currency is interpreted on the
local computer with the command
Expand-NumberFormat currency
.EXAMPLE
Set-ExcelColumn -Worksheet $ws -Heading "WinsToFastLaps" -Value {"=E$row/C$row"} -Column 7 -AutoSize -AutoNameRange
Here, $WS already contains a worksheet which contains counts of races won and fastest laps recorded by racing drivers (in columns C and E).
Set-ExcelColumn specifies that Column 7 should have a heading of "WinsToFastLaps" and the data cells should contain =E2/C2 , =E3/C3 etc
the new data cells should become a named range, which will also be named "WinsToFastLaps" the column width will be set automatically.
.EXAMPLE.
Here, $WS already contains a worksheet which holds counts of races won
and fastest laps recorded by racing drivers (in columns C and E).
Set-ExcelColumn specifies that Column 7 should have a heading of
"WinsToFastLaps" and the data cells should contain =E2/C2 , =E3/C3 etc
the new data cells should become a named range, which will also be
named "WinsToFastLaps" and the column width will be set automatically.
.EXAMPLE
Set-ExcelColumn -Worksheet $ws -Heading "Link" -Value {"https://en.wikipedia.org" + $worksheet.cells["B$Row"].value } -AutoSize
In this example, the worksheet in $ws has partial links to wikipedia pages in column B.
The -Value parameter is is a script block and it outputs a string which begins https... and ends with the value of cell at
column B in the current row. When given a valid URI, Set-ExcelColumn makes it a hyperlink. The column will be autosized to fit the links.
In this example, the worksheet in $ws has partial links to Wikipedia
pages in column B. The -Value parameter is a script block which
outputs a string beginning "https..." and ending with the value of
the cell at column B in the current row.
When given a valid URI, Set-ExcelColumn makes it a hyperlink.
The column will be autosized to fit the links.
.EXAMPLE
4..6 | Set-ExcelColumn -Worksheet $ws -AutoNameRange
Again $ws contains a worksheet. Here columns 4 to 6 are made into named ranges, row 1 is used for the range name
Again $ws contains a worksheet. Here columns 4 to 6 are made into
named ranges, row 1 is used for the range name
and the rest of the column becomes the range.
#>
[cmdletbinding()]
[Alias("Set-Column")]
[OutputType([OfficeOpenXml.ExcelColumn],[String])]
Param (
#If specifying the worksheet by name, the ExcelPackage object which contains the Sheet also needs to be passed.
#If specifying the worksheet by name, the ExcelPackage object which contains the worksheet also needs to be passed.
[Parameter(ParameterSetName="Package",Mandatory=$true)]
[OfficeOpenXml.ExcelPackage]$ExcelPackage,
#The sheet to update can be a given as a name or an Excel Worksheet object - this sets it by name.
#The sheet to update can be given as a name or an Excel Worksheet object - this sets it by name.
[Parameter(ParameterSetName="Package")]
[String]$Worksheetname = "Sheet1",
#This passes the worksheet object instead of passing a sheet name and a package.
#This passes the worksheet object instead of passing a sheet name and an Excelpackage object.
[Parameter(ParameterSetName="sheet",Mandatory=$true)]
[OfficeOpenXml.ExcelWorksheet]$Worksheet,
#Column to fill down - the first column is 1. 0 will be interpreted as first empty column.
@@ -61,16 +71,16 @@
#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,
$FontColor,
#Make text bold; use -Bold:$false to remove bold.
[Switch]$Bold,
#Make text italic; use -Italic:$false to remove italic.
[Switch]$Italic,
#Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining.
[Switch]$Underline,
#Should Underline use single or double, normal or accounting mode ? the default is single normal.
#Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single".
[OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single,
#Strike through text; use -Strikethru:$false to remove Strike through.
#Strike through text; use -StrikeThru:$false to remove strike through.
[Switch]$StrikeThru,
#Subscript or Superscript (or None).
[OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift,
@@ -79,33 +89,33 @@
#Point size for the text.
[float]$FontSize,
#Change background color.
[System.Drawing.Color]$BackgroundColor,
#Background pattern - Solid by default.
$BackgroundColor,
#Background pattern - "Solid" by default.
[OfficeOpenXml.Style.ExcelFillStyle]$BackgroundPattern = [OfficeOpenXml.Style.ExcelFillStyle]::Solid ,
#Secondary color for background pattern.
[Alias("PatternColour")]
[System.Drawing.Color]$PatternColor,
#Turn on text wrapping; use -WrapText:$false to turn off word wrapping.
$PatternColor,
#Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping.
[Switch]$WrapText,
#Position cell contents to Left, Right, Center etc. Default is 'General'.
#Position cell contents to Left, Right, Center etc. Default is "General".
[OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment,
#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)]
[int]$TextRotation ,
#Autofit cells to width.
#Attempt to auto-fit cells to the width their contents.
[Alias("AutoFit")]
[Switch]$AutoSize,
#Set cells to a fixed width, ignored if -Autosize is specified.
#Set cells to a fixed width, ignored if -AutoSize is specified.
[float]$Width,
#Set the inserted data to be a named range.
[Switch]$AutoNameRange,
#Hide the column.
[Switch]$Hide,
#If Sepecified, returns the range of cells which were affected.
#If specified, returns the range of cells which were affected.
[Switch]$Specified,
#If Specified, return the Column to allow further work to be done on it.
#If specified, return an object representing the Column, to allow further work to be done on it.
[Switch]$PassThru
)
@@ -121,6 +131,7 @@
$endRow = $Worksheet.Dimension.End.Row
}
process {
if ($null -eq $workSheet.Dimension) {Write-Warning "Can't format an empty worksheet."; return}
if ($Column -eq 0 ) {$Column = $endColumn + 1 }
$columnName = [OfficeOpenXml.ExcelCellAddress]::new(1,$column).Address -replace "1",""
Write-Verbose -Message "Updating Column $columnName"

View File

@@ -1,32 +1,40 @@
Function Set-ExcelRow {
<#
.Synopsis
Fills values into a [new] row in an Excel spreadsheet. And sets row formats.
Fills values into a [new] row in an Excel spreadsheet, and sets row formats.
.Description
Set-ExcelRow 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.
The contents can be a constant e.g. "42", a formula or a script block which is converted into a constant or a formula.
Set-ExcelRow accepts either a Worksheet object or an ExcelPackage object
returned by Export-Excel and the name of a sheet, and inserts the chosen
contents into a row of the sheet. The contents can be a constant,
like "42", a formula or a script block which is converted into a
constant or a formula.
The first cell of the row can optionally be given a heading.
.Example
Set-ExcelRow -Worksheet $ws -Heading Total -Value {"=sum($columnName`2:$columnName$endrow)" }
$Ws contains a worksheet object, and no Row number is specified so Set-ExcelRow will select the next row after the end
of the data in the sheet. The first cell in the row will contain "Total", and each other cell will contain
=Sum(xx2:xx99) - where xx is the column name, and 99 is the last row of data.
$Ws contains a worksheet object, and no Row number is specified so
Set-ExcelRow will select the next row after the endof the data in
the sheet. The first cell in the row will contain "Total", and
each of the other cells will contain
=Sum(xx2:xx99)
where xx is the column name, and 99 is the last row of data.
Note the use of `2 to Prevent 2 becoming part of the variable "ColumnName"
The script block can use $Worksheet, $Row, $Column (number), $ColumnName (letter), $StartRow/Column and $EndRow/Column
The script block can use $Worksheet, $Row, $Column (number),
$ColumnName (letter), $StartRow/Column and $EndRow/Column.
.Example
Set-ExcelRow -Worksheet $ws -Heading Total -HeadingBold -Value {"=sum($columnName`2:$columnName$endrow)" } -NumberFormat 'Currency' -StartColumn 2 -Bold -BorderTop Double -BorderBottom Thin
This builds on the previous example, but this time the label "Total" appears in column 2 and the formula fills from column 3 onwards;
the formula and heading are set in bold face, and the formula is formatted for the local currency,
and given a double line border above and single line border below.
This builds on the previous example, but this time the label "Total"
appears in column 2 and the formula fills from column 3 onwards.
The formula and heading are set in bold face, and the formula is
formatted for the local currency, and given a double line border
above and single line border below.
#>
[cmdletbinding()]
[Alias("Set-Row")]
[OutputType([OfficeOpenXml.ExcelRow],[String])]
Param (
#An Excel package object - e.g. from Export-Excel -passthru - requires a sheet name.
#An Excel package object - e.g. from Export-Excel -PassThru - requires a sheet name.
[Parameter(ParameterSetName="Package",Mandatory=$true)]
[OfficeOpenXml.ExcelPackage]$ExcelPackage,
#The name of the sheet to update in the package.
@@ -40,21 +48,21 @@
$Row = 0 ,
#Position in the row to start from.
[int]$StartColumn,
#Value, formula or script block to fill in. Script block can use $worksheet, $row, $Column [number], $ColumnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn
#Value, Formula or ScriptBlock to fill in. A ScriptBlock can use $worksheet, $row, $Column [number], $ColumnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn.
$Value,
#Optional Row heading.
#Optional row-heading.
$Heading ,
#Set the heading in bold type.
[Switch]$HeadingBold,
#Change the size of the heading type.
#Change the font-size of the heading.
[Int]$HeadingSize ,
#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,
#Color of the border
[System.Drawing.Color]$BorderColor=[System.Drawing.Color]::Black,
#Color of the border.
$BorderColor=[System.Drawing.Color]::Black,
#Style for the bottom border.
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderBottom,
#Style for the top border.
@@ -63,17 +71,17 @@
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderLeft,
#Style for the right border.
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderRight,
#Colour for the text - if none specified it will be left as it it is.
[System.Drawing.Color]$FontColor,
#Color for the text - if none specified it will be left as it it is.
$FontColor,
#Make text bold; use -Bold:$false to remove bold.
[Switch]$Bold,
#Make text italic; use -Italic:$false to remove italic.
[Switch]$Italic,
#Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining.
[Switch]$Underline,
#Should Underline use single or double, normal or accounting mode : default is single normal.
#Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single".
[OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single,
#Strike through text; use -Strikethru:$false to remove Strike through.
#Strike through text; use -StrikeThru:$false to remove strike through.
[Switch]$StrikeThru,
#Subscript or Superscript (or none).
[OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift,
@@ -82,26 +90,26 @@
#Point size for the text.
[float]$FontSize,
#Change background color.
[System.Drawing.Color]$BackgroundColor,
$BackgroundColor,
#Background pattern - solid by default.
[OfficeOpenXml.Style.ExcelFillStyle]$BackgroundPattern = [OfficeOpenXml.Style.ExcelFillStyle]::Solid ,
#Secondary color for background pattern.
[Alias("PatternColour")]
[System.Drawing.Color]$PatternColor,
#Turn on text wrapping; use -WrapText:$false to turn off word wrapping.
$PatternColor,
#Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping.
[Switch]$WrapText,
#Position cell contents to Left, Right, Center etc. default is 'General'.
[OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment,
#Position cell contents to Top Bottom or Center.
#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)]
[int]$TextRotation ,
#Set cells to a fixed hieght.
#Set cells to a fixed height.
[float]$Height,
#Hide the Row.
#Hide the row.
[Switch]$Hide,
#If Sepecified returns the range of cells which were affected.
#If sepecified, returns the range of cells which were affected.
[Switch]$ReturnRange,
#If Specified, return a row object to allow further work to be done.
[Switch]$PassThru
@@ -118,6 +126,7 @@
$endRow = $Worksheet.Dimension.End.Row
}
process {
if ($null -eq $workSheet.Dimension) {Write-Warning "Can't format an empty worksheet."; return}
if ($Row -eq 0 ) {$Row = $endRow + 1 }
Write-Verbose -Message "Updating Row $Row"
#Add a row label

View File

@@ -1,27 +1,34 @@
Function Set-ExcelRange {
<#
.SYNOPSIS
Applies Number, font, alignment and color formatting, values or formulas to a range of Excel Cells.
Applies number, font, alignment and/or color formatting, values or formulas to a range of Excel cells.
.DESCRIPTION
Set-ExcelRange was created to set the style elements for a range of cells, this includes
auto-sizing and hiding, setting font elements (Name, Size, Bold, Italic, Underline & UnderlineStyle and Subscript & SuperScript),
font and background colors, borders, text wrapping, rotation, aliginment within cells, and number format.
It was orignally named "Set-Format",but it has been extended to set Values, Formulas and
ArrayFormulas (sometimes called Ctrl-shift-Enter [CSE] formulas); because of this
The name has become Set-ExcelRange - but the old name of Set-Format is preserved as an alias name.
Set-ExcelRange was created to set the style elements for a range of cells,
this includes auto-sizing and hiding, setting font elements (Name, Size,
Bold, Italic, Underline & UnderlineStyle and Subscript & SuperScript),
font and background colors, borders, text wrapping, rotation, alignment
within cells, and number format.
It was orignally named "Set-Format", but it has been extended to set
Values, Formulas and ArrayFormulas (sometimes called Ctrl-shift-Enter
[CSE] formulas); because of this, the name has become Set-ExcelRange
but the old name of Set-Format is preserved as an alias.
.EXAMPLE
$sheet.Column(3) | Set-ExcelRange -HorizontalAlignment Right -NumberFormat "#,###" -AutoFit
Selects column 3 from a sheet object (within a workbook object, which is a child of the ExcelPackage object) and passes it to Set-ExcelRange
which formats as an integer with comma-separated groups, aligns it right, and auto-fits the column to the contents.
Selects column 3 from a sheet object (within a workbook object, which
is a child of the ExcelPackage object) and passes it to Set-ExcelRange
which formats numbers as a integers with comma-separated groups,
aligns it right, and auto-fits the column to the contents.
.EXAMPLE
Set-ExcelRange -Range $sheet.Cells["E1:H1048576"] -HorizontalAlignment Right -NumberFormat "#,###"
Instead of piping the address, this version specifies a block of cells and applies similar formatting.
Instead of piping the address, this version specifies a block of cells
and applies similar formatting.
.EXAMPLE
Set-ExcelRange $excel.Workbook.Worksheets[1].Tables["Processes"] -Italic
This time instead of specifying a range of cells, a table is selected by name and formatted as italic.
This time instead of specifying a range of cells, a table is selected
by name and formatted as italic.
#>
[cmdletbinding()]
[Alias("Set-Format")]
@@ -38,7 +45,7 @@
#Style of border to draw around the range.
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderAround,
#Color of the border.
[System.Drawing.Color]$BorderColor=[System.Drawing.Color]::Black,
$BorderColor=[System.Drawing.Color]::Black,
#Style for the bottom border.
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderBottom,
#Style for the top border.
@@ -48,22 +55,22 @@
#Style for the right border.
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderRight,
#Colour for the text - if none is specified it will be left as it is.
[System.Drawing.Color]$FontColor,
$FontColor,
#Value for the cell.
$Value,
#Formula for the cell.
$Formula,
#Specifies formula should be an array formula (a.k.a CSE [ctrl-shift-enter] formula).
[Switch]$ArrayFormula,
#Clear Bold, Italic, StrikeThrough and Underline and set colour to black.
#Clear Bold, Italic, StrikeThrough and Underline and set color to Black.
[Switch]$ResetFont,
#Make text bold; use -Bold:$false to remove bold.
[Switch]$Bold,
#Make text italic; use -Italic:$false to remove italic.
[Switch]$Italic,
#Underline the text using the underline style in -underline type; use -Underline:$false to remove underlining.
#Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining.
[Switch]$Underline,
#Should Underline use single or double, normal or accounting mode: the default is single normal.
#Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single".
[OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single,
#Strike through text; use -Strikethru:$false to remove Strike through
[Switch]$StrikeThru,
@@ -74,17 +81,17 @@
#Point size for the text.
[float]$FontSize,
#Change background color.
[System.Drawing.Color]$BackgroundColor,
$BackgroundColor,
#Background pattern - Solid by default.
[OfficeOpenXml.Style.ExcelFillStyle]$BackgroundPattern = [OfficeOpenXml.Style.ExcelFillStyle]::Solid ,
#Secondary color for background pattern.
[Alias("PatternColour")]
[System.Drawing.Color]$PatternColor,
#Turn on text wrapping; use -WrapText:$false to turn off word wrapping.
$PatternColor,
#Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping.
[Switch]$WrapText,
#Position cell contents to Left, Right, Center etc. default is 'General'.
[OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment,
#Position cell contents to Top Bottom or Center.
#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)]
@@ -94,7 +101,7 @@
[Switch]$AutoSize,
#Set cells to a fixed width (columns or ranges only), ignored if Autosize is specified.
[float]$Width,
#Set cells to a fixed hieght (rows or ranges only).
#Set cells to a fixed height (rows or ranges only).
[float]$Height,
#Hide a row or column (not a range); use -Hidden:$false to unhide.
[Switch]$Hidden
@@ -113,7 +120,7 @@
elseif ($Range -is [string]) {Write-Warning -Message "The range pararameter you have specified also needs a worksheet parameter."}
if ($ResetFont) {
$Range.Style.Font.Color.SetColor("Black")
$Range.Style.Font.Color.SetColor( ([System.Drawing.Color]::Black))
$Range.Style.Font.Bold = $false
$Range.Style.Font.Italic = $false
$Range.Style.Font.UnderLine = $false
@@ -143,6 +150,7 @@
$Range.Style.Font.VerticalAlign = $FontShift
}
if ($PSBoundParameters.ContainsKey('FontColor')){
if ($FontColor -is [string]) {$FontColor = [System.Drawing.Color]::$FontColor }
$Range.Style.Font.Color.SetColor( $FontColor)
}
if ($PSBoundParameters.ContainsKey('TextRotation')) {
@@ -172,6 +180,7 @@
if ($PSBoundParameters.ContainsKey('NumberFormat')) {
$Range.Style.Numberformat.Format = (Expand-NumberFormat $NumberFormat)
}
if ($BorderColor -is [string]) {$BorderColor = [System.Drawing.Color]::$BorderColor }
if ($PSBoundParameters.ContainsKey('BorderAround')) {
$Range.Style.Border.BorderAround($BorderAround, $BorderColor)
}
@@ -193,8 +202,10 @@
}
if ($PSBoundParameters.ContainsKey('BackgroundColor')) {
$Range.Style.Fill.PatternType = $BackgroundPattern
if ($BackgroundColor -is [string]) {$BackgroundColor = [System.Drawing.Color]::$BackgroundColor }
$Range.Style.Fill.BackgroundColor.SetColor($BackgroundColor)
if ($PatternColor) {
if ($PatternColor -is [string]) {$PatternColor = [System.Drawing.Color]::$PatternColor }
$Range.Style.Fill.PatternColor.SetColor( $PatternColor)
}
}
@@ -291,12 +302,15 @@ if (Get-Command -ErrorAction SilentlyContinue -name Register-ArgumentCompleter)
Function Expand-NumberFormat {
<#
.SYNOPSIS
Converts short names for Number formats to the formatting strings used in Excel
Converts short names for number formats to the formatting strings used in Excel
.DESCRIPTION
Where you can type a number format you can write, for example 'Short-Date' and the module will translate it into the format string used by excel
Some formats, like Short-Date change how they are presented when Excel loads. (So date will use the local ordering of year, month and Day)
Other formats change how they appear when loaded with different cultures (depending on the country "," or "." or " " may be the thousand seperator
although excel always stores it as ",")
Where you can type a number format you can write, for example, 'Short-Date'
and the module will translate it into the format string used by Excel.
Some formats, like Short-Date change how they are presented when Excel
loads (so date will use the local ordering of year, month and Day). Other
formats change how they appear when loaded with different cultures
(depending on the country "," or "." or " " may be the thousand seperator
although Excel always stores it as ",")
.EXAMPLE
Expand-NumberFormat percentage
@@ -304,11 +318,15 @@ Function Expand-NumberFormat {
.EXAMPLE
Expand-NumberFormat Currency
Returns the currency format specified in the local regional settings. This may not be the same as Excel uses
The regional settings set the currency symbol and then whether it is before or after the number and seperated with a space or not;
for negative numbers the number by wrapped in parentheses or a - sign might appear before or after the number and symbol.
So this returns $#,##0.00;($#,##0.00) for English US, #,##0.00 €;€#,##0.00- for French. (Note some Eurozone countries write €1,23 and others 1,23€ )
In French the decimal point will be rendered as a "," and the thousand seperator as a space.
Returns the currency format specified in the local regional settings. This
may not be the same as Excel uses. The regional settings set the currency
symbol and then whether it is before or after the number and separated with
a space or not; for negative numbers the number may be wrapped in parentheses
or a - sign might appear before or after the number and symbol.
So this returns $#,##0.00;($#,##0.00) for English US, #,##0.00 €;€#,##0.00-
for French. (Note some Eurozone countries write €1,23 and others 1,23€ )
In French the decimal point will be rendered as a "," and the thousand
separator as a space.
#>
[cmdletbinding()]
[OutputType([String])]

View File

@@ -1,8 +1,7 @@
#Requires -Modules Pester
Import-Module $PSScriptRoot\..\ImportExcel.psd1 -Force
Add-Type -AssemblyName System.Windows.Forms
if ($PSVersionTable.PSVersion.Major -gt 5) { Write-Warning "Can't test grid view on V6" }
else {Add-Type -AssemblyName System.Windows.Forms }
Describe "Compare Worksheet" {
Context "Simple comparison output" {
BeforeAll {
@@ -51,8 +50,9 @@ Describe "Compare Worksheet" {
Context "Setting the background to highlight different rows, use of grid view." {
BeforeAll {
Compare-WorkSheet "$env:temp\Server1.xlsx" "$env:temp\Server2.xlsx" -BackgroundColor LightGreen -GridView
Start-Sleep -sec 5; [System.Windows.Forms.SendKeys]::Sendwait("%{F4}")
$useGrid = ($PSVersionTable.PSVersion.Major -LE 5)
$null = Compare-WorkSheet "$env:temp\Server1.xlsx" "$env:temp\Server2.xlsx" -BackgroundColor ([System.Drawing.Color]::LightGreen) -GridView:$useGrid
if ($useGrid) {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]
@@ -78,7 +78,7 @@ Describe "Compare Worksheet" {
Context "Setting the forgound to highlight changed properties" {
BeforeAll {
$null = compare-WorkSheet "$env:temp\Server1.xlsx" "$env:temp\Server2.xlsx" -AllDataBackgroundColor white -BackgroundColor LightGreen -FontColor DarkRed
$null = compare-WorkSheet "$env:temp\Server1.xlsx" "$env:temp\Server2.xlsx" -AllDataBackgroundColor([System.Drawing.Color]::white) -BackgroundColor ([System.Drawing.Color]::LightGreen) -FontColor ([System.Drawing.Color]::DarkRed)
$xl1 = Open-ExcelPackage -Path "$env:temp\Server1.xlsx"
$xl2 = Open-ExcelPackage -Path "$env:temp\Server2.xlsx"
$s1Sheet = $xl1.Workbook.Worksheets[1]
@@ -121,7 +121,7 @@ Describe "Compare Worksheet" {
$s[10].ServiceType = "Changed should not matter"
$s | Select-Object -Property ServiceName, DisplayName, StartType, ServiceType | Export-Excel -Path $env:temp\server2.xlsx -WorkSheetname server2
#Assume default worksheet name, (sheet1) and column header for key ("name")
$comp = compare-WorkSheet "$env:temp\Server1.xlsx" "$env:temp\Server2.xlsx" -WorkSheetName Server1,Server2 -Key ServiceName -Property DisplayName,StartType -AllDataBackgroundColor AliceBlue -BackgroundColor White -FontColor Red | Sort-Object _row,_file
$comp = compare-WorkSheet "$env:temp\Server1.xlsx" "$env:temp\Server2.xlsx" -WorkSheetName Server1,Server2 -Key ServiceName -Property DisplayName,StartType -AllDataBackgroundColor ([System.Drawing.Color]::AliceBlue) -BackgroundColor ([System.Drawing.Color]::White) -FontColor ([System.Drawing.Color]::Red) | Sort-Object _row,_file
$xl1 = Open-ExcelPackage -Path "$env:temp\Server1.xlsx"
$xl2 = Open-ExcelPackage -Path "$env:temp\Server2.xlsx"
$s1Sheet = $xl1.Workbook.Worksheets["server1"]

View File

@@ -355,13 +355,7 @@ Describe ExportExcel {
Context "#Example 5 # Adding a single conditional format " {
#Test New-ConditionalText builds correctly
$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
$ct.ConditionalTextColor -is [System.Drawing.Color] | Should be $true
$ct.ConditionalType -in [enum]::GetNames( [OfficeOpenXml.ConditionalFormatting.eExcelConditionalFormattingRuleType] ) |
Should be $true
}
$ct = New-ConditionalText -ConditionalType GreaterThan 525 -ConditionalTextColor ([System.Drawing.Color]::DarkRed) -BackgroundColor ([System.Drawing.Color]::LightPink)
$path = "$env:TEMP\Test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue
@@ -398,8 +392,8 @@ Describe ExportExcel {
#Testing -Passthrough
$Excel = Get-Service | Select-Object Name, Status, DisplayName, ServiceName |
Export-Excel $path -PassThru -ConditionalText $(
New-ConditionalText Stop DarkRed LightPink
New-ConditionalText Running Blue Cyan
New-ConditionalText Stop ([System.Drawing.Color]::DarkRed) ([System.Drawing.Color]::LightPink)
New-ConditionalText Running ([System.Drawing.Color]::Blue) ([System.Drawing.Color]::Cyan)
)
$ws = $Excel.Workbook.Worksheets[1]
it "Added two blocks of conditional formating for the data range " {
@@ -649,7 +643,7 @@ Describe ExportExcel {
$warnvar = $null
#Test create two data pages; as part of adding the second give both their own pivot table, test -autosize switch
Get-Service | Select-Object -Property Status, Name, DisplayName, StartType, CanPauseAndContinue | Export-Excel -Path $path -AutoSize -TableName "All Services" -TableStyle Medium1 -WarningAction SilentlyContinue -WarningVariable warnvar
Get-Process | Select-Object -Property Name, Company, Handles, CPU, VM | Export-Excel -Path $path -AutoSize -WorkSheetname 'sheet2' -TableName "Processes" -TableStyle Light1 -Title "Processes" -TitleFillPattern Solid -TitleBackgroundColor AliceBlue -TitleBold -TitleSize 22 -PivotTableDefinition $ptDef
Get-Process | Select-Object -Property Name, Company, Handles, CPU, VM | Export-Excel -Path $path -AutoSize -WorkSheetname 'sheet2' -TableName "Processes" -TableStyle Light1 -Title "Processes" -TitleFillPattern Solid -TitleBackgroundColor ([System.Drawing.Color]::AliceBlue) -TitleBold -TitleSize 22 -PivotTableDefinition $ptDef
$Excel = Open-ExcelPackage $path
$ws1 = $Excel.Workbook.Worksheets["Sheet1"]
$ws2 = $Excel.Workbook.Worksheets["Sheet2"]
@@ -722,10 +716,10 @@ Describe ExportExcel {
Set-ExcelRange -Address $sheet.Cells["E1:H1048576"] -HorizontalAlignment Right -NFormat "#,###"
Set-ExcelRange -Address $sheet.Column(4) -HorizontalAlignment Right -NFormat "#,##0.0" -Bold
Set-ExcelRange -Address $sheet.Row(1) -Bold -HorizontalAlignment Center
Add-ConditionalFormatting -WorkSheet $sheet -Range "D2:D1048576" -DataBarColor Red
Add-ConditionalFormatting -WorkSheet $sheet -Range "D2:D1048576" -DataBarColor ([System.Drawing.Color]::Red)
#test Add-ConditionalFormatting -passthru and using a range (and no worksheet)
$rule = Add-ConditionalFormatting -passthru -Address $sheet.cells["C:C"] -RuleType TopPercent -ConditionValue 20 -Bold -StrikeThru
Add-ConditionalFormatting -WorkSheet $sheet -Range "G2:G1048576" -RuleType GreaterThan -ConditionValue "104857600" -ForeGroundColor Red -Bold -Italic -Underline -BackgroundColor Beige -BackgroundPattern LightUp -PatternColor Gray
Add-ConditionalFormatting -WorkSheet $sheet -Range "G2:G1048576" -RuleType GreaterThan -ConditionValue "104857600" -ForeGroundColor ([System.Drawing.Color]::Red) -Bold -Italic -Underline -BackgroundColor ([System.Drawing.Color]::Beige) -BackgroundPattern LightUp -PatternColor ([System.Drawing.Color]::Gray)
#Test Set-ExcelRange with a column
foreach ($c in 5..9) {Set-ExcelRange $sheet.Column($c) -AutoFit }
Add-PivotTable -PivotTableName "PT_Procs" -ExcelPackage $excel -SourceWorkSheet 1 -PivotRows Company -PivotData @{'Name' = 'Count'} -IncludePivotChart -ChartType ColumnClustered -NoLegend
@@ -857,7 +851,7 @@ Describe ExportExcel {
-Column 2 -ColumnOffSetPixels 35 -Width 800 -XAxisTitleText "Degrees" -XAxisTitleBold -XAxisTitleSize 12 -XMajorUnit 30 -XMinorUnit 10 -XMinValue 0 -XMaxValue 361 -XAxisNumberformat "000" `
-YMinValue -1.25 -YMaxValue 1.25 -YMajorUnit 0.25 -YAxisNumberformat "0.00" -YAxisTitleText "Sine" -YAxisTitleBold -YAxisTitleSize 12 `
-LegendSize 8 -legendBold -LegendPosition Bottom
Add-ConditionalFormatting -WorkSheet $excel.Workbook.Worksheets["Sinx"] -Range "B2:B362" -RuleType LessThan -ConditionValue "=B1" -ForeGroundColor Red
Add-ConditionalFormatting -WorkSheet $excel.Workbook.Worksheets["Sinx"] -Range "B2:B362" -RuleType LessThan -ConditionValue "=B1" -ForeGroundColor ([System.Drawing.Color]::Red)
$ws = $Excel.Workbook.Worksheets["Sinx"]
$d = $ws.Drawings[0]
It "Controled the axes and title and legend of the chart " {
@@ -916,7 +910,7 @@ Describe ExportExcel {
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
$ct = New-ConditionalText -Text "Microsoft" -ConditionalTextColor ([System.Drawing.Color]::Red) -BackgroundColor([System.Drawing.Color]::AliceBlue) -ConditionalType ContainsText
it "Created the Conditional formatting rules " {
$cf.Formatter | Should be "ThreeIconSet"
$cf.IconType | Should be "Flags"

View File

@@ -10,8 +10,10 @@ Banana, London , 300, 200
Orange, Paris, 600, 500
Banana, Paris, 300, 200
Apple, New York, 1200,700
"@ | Export-Excel -Path $path -TableStyle Medium13 -tablename "RawData" -ConditionalFormat @{Range="C2:C7"; DataBarColor="Green"} -ExcelChartDefinition @{ChartType="Doughnut";XRange="A2:B7"; YRange="C2:C7"; width=800; } -PivotTableDefinition @{Sales=@{
PivotRows="City"; PivotColumns="Product"; PivotData=@{Gross="Sum";Net="Sum"}; PivotNumberFormat="$#,##0.00"; PivotTotals="Both"; PivotTableStyle="Medium12"; Activate=$true
PivotChartDefinition=@{Title="Gross and net by city and product"; ChartType="ColumnClustered"; Column=6; Width=600; Height=360; YMajorUnit=500; YMinorUnit=100; YAxisNumberformat="$#,##0"; LegendPosition="Bottom"}}}
$excel = Open-ExcelPackage $path

View File

@@ -34,10 +34,10 @@ Describe "Creating small named ranges with hyperlinks" {
$cf.Icon2.Type = $cf.Icon3.Type = "Num"
$cf.Icon2.Value = 0
$cf.Icon3.Value = 1
Add-ConditionalFormatting -Address $worksheet.cells["FinishPosition"] -RuleType Equal -ConditionValue 1 -ForeGroundColor Purple -Bold -Priority 1 -StopIfTrue #Test Priority and stopIfTrue and using range name
Add-ConditionalFormatting -Address $worksheet.cells["FinishPosition"] -RuleType Equal -ConditionValue 1 -ForeGroundColor ([System.Drawing.Color]::Purple) -Bold -Priority 1 -StopIfTrue #Test Priority and stopIfTrue and using range name
Add-ConditionalFormatting -Address $worksheet.Cells["GridPosition"] -RuleType ThreeColorScale -Reverse #Test Reverse
$ct = New-ConditionalText -Text "Ferrari"
$ct2 = New-ConditionalText -Range $worksheet.Names["FinishPosition"].Address -ConditionalType LessThanOrEqual -Text 3 -ConditionalText Red -Background White #Test new-conditionalText in shortest and longest forms.
$ct2 = New-ConditionalText -Range $worksheet.Names["FinishPosition"].Address -ConditionalType LessThanOrEqual -Text 3 -ConditionalText ([System.Drawing.Color]::Red) -Background ([System.Drawing.Color]::White) #Test new-conditionalText in shortest and longest forms.
#Create links for each group name (race) and Export them so they start at Cell A1; create a pivot table with definition just created, save the file and open in Excel
$results | ForEach-Object {(New-Object -TypeName OfficeOpenXml.ExcelHyperLink -ArgumentList "Sheet1!$($_.Name)" , "$($_.name) GP")} | #Test Exporting Hyperlinks with display property.
Export-Excel -ExcelPackage $excel -AutoSize -PivotTableDefinition $pt -Calculate -ConditionalFormat $ct,$ct2 #Test conditional text rules in conditional format (orignally icon sets only )

View File

@@ -22,7 +22,7 @@ ID,Product,Quantity,Price,Total
12012,Pliers,3,14.99,44.97
"@
Describe "Join Worksheet" {
Describe "Join Worksheet part 1" {
BeforeAll {
$path = "$Env:TEMP\test.xlsx"
Remove-Item -Path $path -ErrorAction SilentlyContinue
@@ -30,7 +30,7 @@ Describe "Join Worksheet" {
$data2 | Export-Excel -Path $path -WorkSheetname Abingdon
$data3 | Export-Excel -Path $path -WorkSheetname Banbury
$ptdef = New-PivotTableDefinition -PivotTableName "SummaryPivot" -PivotRows "Store" -PivotColumns "Product" -PivotData @{"Total"="SUM"} -IncludePivotChart -ChartTitle "Sales Breakdown" -ChartType ColumnStacked -ChartColumn 10
Join-Worksheet -Path $path -WorkSheetName "Total" -Clearsheet -FromLabel "Store" -TableName "SummaryTable" -TableStyle Light1 -AutoSize -BoldTopRow -FreezePane 2,1 -Title "Store Sales Summary" -TitleBold -TitleSize 14 -TitleBackgroundColor AliceBlue -PivotTableDefinition $ptdef
Join-Worksheet -Path $path -WorkSheetName "Total" -Clearsheet -FromLabel "Store" -TableName "SummaryTable" -TableStyle Light1 -AutoSize -BoldTopRow -FreezePane 2,1 -Title "Store Sales Summary" -TitleBold -TitleSize 14 -TitleBackgroundColor ([System.Drawing.Color]::AliceBlue) -PivotTableDefinition $ptdef
$excel = Export-Excel -path $path -WorkSheetname SummaryPivot -Activate -NoTotalsInPivot -PivotDataToColumn -HideSheet * -UnHideSheet "Total","SummaryPivot" -PassThru
# Open-ExcelPackage -Path $path
@@ -88,8 +88,11 @@ Describe "Join Worksheet" {
$pc.Title.text | Should be "Sales Breakdown"
}
}
}
$path = "$env:TEMP\Test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue
IF ($PSVersionTable.PSVersion.Major -gt 5) {Write-warning -message "Part 2 Does not run on V6"; return}
Describe "Join Worksheet part 2" {
Get-WmiObject -Class win32_logicaldisk |
Select-Object -Property DeviceId,VolumeName, Size,Freespace |
Export-Excel -Path $path -WorkSheetname Volumes -NumberFormat "0,000"

View File

@@ -19,7 +19,7 @@ describe "Consistent passing of ranges." {
$warnvar | should beNullOrEmpty
$excel.Services.ConditionalFormatting.Count | Should be 3
{Add-ConditionalFormatting "Status" -WorkSheet $excel.Services `
-ForeGroundColor Green -RuleType ContainsText -ConditionValue "Running"} | Should not throw
-ForeGroundColor ([System.Drawing.Color]::Green) -RuleType ContainsText -ConditionValue "Running"} | Should not throw
$excel.Services.ConditionalFormatting.Count | Should be 4
}
Close-ExcelPackage -NoSave $excel
@@ -32,7 +32,7 @@ describe "Consistent passing of ranges." {
-Bold -RuleType ContainsText -ConditionValue "windows" } | Should not throw
$excel.Services.ConditionalFormatting.Count | Should be 2
{Add-ConditionalFormatting -WorkSheet $excel.Services -Address "a:a" `
-RuleType ContainsText -ConditionValue "stopped" -ForeGroundColor Red } | Should not throw
-RuleType ContainsText -ConditionValue "stopped" -ForeGroundColor ([System.Drawing.Color]::Red) } | Should not throw
$excel.Services.ConditionalFormatting.Count | Should be 3
}
Close-ExcelPackage -NoSave $excel
@@ -62,7 +62,7 @@ describe "Consistent passing of ranges." {
$excel.Services.cells["C3"].Style.Font.UnderLine | Should be $true
{Set-ExcelRange -WorkSheet $excel.Services -Range "Name" -Bold } | Should not throw
$excel.Services.cells["B4"].Style.Font.Bold | Should be $true
{$excel.Services.Column(3) | Set-ExcelRange -FontColor red } | Should not throw
{$excel.Services.Column(3) | Set-ExcelRange -FontColor ([System.Drawing.Color]::Red) } | Should not throw
$excel.Services.cells["C4"].Style.Font.Color.Rgb | Should be "FFFF0000"
}
Close-ExcelPackage -NoSave $excel

View File

@@ -135,13 +135,13 @@ Describe "Set-ExcelColumn, Set-ExcelRow and Set-ExcelRange" {
$excel = $data| Export-Excel -Path $path -AutoNameRange -PassThru
$ws = $excel.Workbook.Worksheets["Sheet1"]
$c = Set-ExcelColumn -PassThru -Worksheet $ws -Heading "Total" -Value "=Quantity*Price" -NumberFormat "£#,###.00" -FontColor Blue -Bold -HorizontalAlignment Right -VerticalAlignment Top
$c = Set-ExcelColumn -PassThru -Worksheet $ws -Heading "Total" -Value "=Quantity*Price" -NumberFormat "£#,###.00" -FontColor ([System.Drawing.Color]::Blue) -Bold -HorizontalAlignment Right -VerticalAlignment Top
$r = Set-ExcelRow -PassThru -Worksheet $ws -StartColumn 3 -BorderAround Thin -Italic -Underline -FontSize 14 -Value {"=sum($columnName`2:$columnName$endrow)" } -VerticalAlignment Bottom
Set-ExcelRange -Address $excel.Workbook.Worksheets["Sheet1"].Cells["b3"] -HorizontalAlignment Right -VerticalAlignment Center -BorderAround Thick -BorderColor Red -StrikeThru
Set-ExcelRange -Address $excel.Workbook.Worksheets["Sheet1"].Cells["c3"] -BorderColor Red -BorderTop DashDot -BorderLeft DashDotDot -BorderBottom Dashed -BorderRight Dotted
Set-ExcelRange -Address $excel.Workbook.Worksheets["Sheet1"].Cells["b3"] -HorizontalAlignment Right -VerticalAlignment Center -BorderAround Thick -BorderColor ([System.Drawing.Color]::Red) -StrikeThru
Set-ExcelRange -Address $excel.Workbook.Worksheets["Sheet1"].Cells["c3"] -BorderColor ([System.Drawing.Color]::Red) -BorderTop DashDot -BorderLeft DashDotDot -BorderBottom Dashed -BorderRight Dotted
Set-ExcelRange -WorkSheet $ws -Range "E3" -Bold:$false -FontShift Superscript -HorizontalAlignment Left
Set-ExcelRange -WorkSheet $ws -Range "E1" -ResetFont -HorizontalAlignment General -FontName "Courier New" -fontSize 9
Set-ExcelRange -Address $ws.Cells["E7"] -ResetFont -WrapText -BackgroundColor AliceBlue -BackgroundPattern DarkTrellis -PatternColor Red -NumberFormat "£#,###.00"
Set-ExcelRange -Address $ws.Cells["E7"] -ResetFont -WrapText -BackgroundColor ([System.Drawing.Color]::AliceBlue) -BackgroundPattern DarkTrellis -PatternColor ([System.Drawing.Color]::Red) -NumberFormat "£#,###.00"
Set-ExcelRange -Address $ws.Column(1) -Width 0
Set-ExcelRange -Address $ws.Column(2) -AutoFit
Set-ExcelRange -Address $ws.Cells["E:E"] -AutoFit

View File

@@ -3,29 +3,37 @@
.Synopsis
Compares two worksheets and shows the differences.
.Description
This command takes two file names, one or two worksheet name and a name for a key column.
It reads the worksheet from each file and decides the column names.
It builds a hashtable of the key-column values and the rows in which they appear.
It then uses PowerShell's compare object command to compare the sheets (explicity checking
all the column names which have not been excluded). For the difference rows it adds the
row number for the key of that row - we have to add the key after doing the comparison,
otherwise identical rows at diffeent positions in the file will not will be considered to match.
This command takes two file names, one or two worksheet names and a name
for a "key" column. It reads the worksheet from each file and decides the
column names and builds a hashtable of the key-column values and the
rows in which they appear.
It then uses PowerShell's Compare-Object command to compare the sheets
(explicitly checkingall the column names which have not been excluded).
For the difference rows it adds the row number for the key of that row -
we have to add the key after doing the comparison, otherwise identical
rows at different positions in the file will not be considered a match.
We also add the name of the file and sheet in which the difference occurs.
If -BackgroundColor is specified the difference rows will be changed to that background in the orginal file.
If -BackgroundColor is specified the difference rows will be changed to
that background in the orginal file.
.Example
Compare-WorkSheet -Referencefile 'Server56.xlsx' -Differencefile 'Server57.xlsx' -WorkSheetName Products -key IdentifyingNumber -ExcludeProperty Install* | Format-Table
The two workbooks in this example contain the result of redirecting a subset of properties from Get-WmiObject -Class win32_product to Export-Excel.
The command compares the "Products" pages in the two workbooks, but we don't want to register a difference if the software was installed on a
different date or from a different place, and excluding Install* removes InstallDate and InstallSource.
This data doesn't have a "Name" column" so we specify the "IdentifyingNumber" column as the key.
The two workbooks in this example contain the result of redirecting a subset
of properties from Get-WmiObject -Class win32_product to Export-Excel.
The command compares the "Products" pages in the two workbooks, but we
don't want to register a difference if the software was installed on a
different date or from a different place, and excluding Install* removes
InstallDate and InstallSource. This data doesn't have a "Name" column, so
we specify the "IdentifyingNumber" column as the key.
The results will be presented as a table.
.Example
compare-WorkSheet "Server54.xlsx" "Server55.xlsx" -WorkSheetName Services -GridView
Compare-WorkSheet "Server54.xlsx" "Server55.xlsx" -WorkSheetName Services -GridView
This time two workbooks contain the result of redirecting Get-WmiObject -Class win32_service to Export-Excel.
Here the -Differencefile and -Referencefile parameter switches are assumed , and the default setting for -key ("Name") works for services
This will display the differences between the "Services" sheets using a grid view
This time two workbooks contain the result of redirecting the command
Get-WmiObject -Class win32_service to Export-Excel. Here the -Differencefile
and -Referencefile parameter switches are assumed and the default setting for
-Key ("Name") works for services. This will display the differences between
the "Services" sheets using a grid view
.Example
Compare-WorkSheet 'Server54.xlsx' 'Server55.xlsx' -WorkSheetName Services -BackgroundColor lightGreen
@@ -33,25 +41,32 @@
.Example
Compare-WorkSheet 'Server54.xlsx' 'Server55.xlsx' -WorkSheetName Services -BackgroundColor lightGreen -FontColor Red -Show
This example builds on the previous one: this time where two changed rows have the value in the "Name" column (the default value for -Key),
this version adds highlighting of the changed cells in red; and then opens the Excel file.
This example builds on the previous one: this time where two changed rows have
the value in the "Name" column (the default value for -Key), this version adds
highlighting of the changed cells in red; and then opens the Excel file.
.Example
Compare-WorkSheet 'Pester-tests.xlsx' 'Pester-tests.xlsx' -WorkSheetName 'Server1','Server2' -Property "full Description","Executed","Result" -Key "full Description"
This time the reference file and the difference file are the same file and two different sheets are used. Because the tests include the
machine name and time the test was run the command specifies that a limited set of columns should be used.
This time the reference file and the difference file are the same file and
two different sheets are used. Because the tests include the machine name
and time the test was run, the command specifies that a limited set of
columns should be used.
.Example
Compare-WorkSheet 'Server54.xlsx' 'Server55.xlsx' -WorkSheetName general -Startrow 2 -Headername Label,value -Key Label -GridView -ExcludeDifferent
The "General" page in the two workbooks has a title and two unlabelled columns with a row each for CPU, Memory, Domain, Disk and so on;
so the command is instructed to start at row 2 in order to skip the title and given names for the columns: the first is "label" and the Second "Value";
the label acts as the key. This time we interested the rows which are the same in both sheets,
and the result is displayed using grid view. Note that grid view works best when the number of columns is small.
The "General" page in the two workbooks has a title and two unlabelled columns
with a row each for CPU, Memory, Domain, Disk and so on. So the command is
told to start at row 2 in order to skip the title and given names for the
columns: the first is "label" and the second "Value"; the label acts as the key.
This time we are interested in those rows which are the same in both sheets,
and the result is displayed using grid view.
Note that grid view works best when the number of columns is small.
.Example
Compare-WorkSheet 'Server1.xlsx' 'Server2.xlsx' -WorkSheetName general -Startrow 2 -Headername Label,value -Key Label -BackgroundColor White -Show -AllDataBackgroundColor LightGray
This version of the previous command highlights all the cells in lightgray and then sets the changed rows back to white;
only the unchanged rows are highlighted
This version of the previous command highlights all the cells in LightGray
and then sets the changed rows back to white.
Only the unchanged rows are highlighted.
#>
[cmdletbinding(DefaultParameterSetName)]
Param(
@@ -63,9 +78,9 @@
$Differencefile ,
#Name(s) of worksheets to compare.
$WorkSheetName = "Sheet1",
#Properties to include in the DIFF - supports wildcards, default is "*".
#Properties to include in the comparison - supports wildcards, default is "*".
$Property = "*" ,
#Properties to exclude from the search - supports wildcards.
#Properties to exclude from the comparison - supports wildcards.
$ExcludeProperty ,
#Specifies custom property names to use, instead of the values defined in the starting row of the sheet.
[Parameter(ParameterSetName='B', Mandatory)]
@@ -75,25 +90,25 @@
[switch]$NoHeader,
#The row from where we start to import data: all rows above the start row are disregarded. By default, this is the first row.
[int]$Startrow = 1,
#If specified, highlights all the cells - so you can make Equal cells one colour, and Diff cells another.
[System.Drawing.Color]$AllDataBackgroundColor,
#If specified, highlights the DIFF rows.
[System.Drawing.Color]$BackgroundColor,
#If specified identifies the tabs which contain DIFF rows (ignored if -BackgroundColor is omitted).
[System.Drawing.Color]$TabColor,
#If specified, highlights all the cells - so you can make Equal cells one color, and Different cells another.
$AllDataBackgroundColor,
#If specified, highlights the rows with differences.
$BackgroundColor,
#If specified identifies the tabs which contain difference rows (ignored if -BackgroundColor is omitted).
$TabColor,
#Name of a column which is unique and will be used to add a row to the DIFF object, defaults to "Name".
$Key = "Name" ,
#If specified, highlights the DIFF columns in rows which have the same key.
[System.Drawing.Color]$FontColor,
#If specified opens the Excel workbooks instead of outputting the diff to the console (unless -Passthru is also specified).
$FontColor,
#If specified, opens the Excel workbooks instead of outputting the diff to the console (unless -PassThru is also specified).
[Switch]$Show,
#If specified, the command tries to the show the DIFF in a Grid-View and not on the console. (unless-Passthru is also specified). This Works best with few columns selected, and requires a key.
#If specified, the command tries to the show the DIFF in a Grid-View and not on the console. (unless-PassThru is also specified). This works best with few columns selected, and requires a key.
[switch]$GridView,
#If specified -Passthrough a full set of diff data is returned without filtering to the specified properties.
#If specifieda full set of DIFF data is returned without filtering to the specified properties.
[Switch]$PassThru,
#If specified the result will include Equal rows as well. By default only Different rows are returned.
#If specified the result will include equal rows as well. By default only different rows are returned.
[Switch]$IncludeEqual,
#If Specified the result includes only the rows where both are equal.
#If specified, the result includes only the rows where both are equal.
[Switch]$ExcludeDifferent
)
@@ -167,6 +182,7 @@
Set-Format -WorkSheet $ws -Range $range -BackgroundColor $BackgroundColor
}
if ($TabColor) {
if ($TabColor -is [string]) {$TabColor = [System.Drawing.Color]::$TabColor }
foreach ($tab in ($file.group._sheet | Select-Object -Unique)) {
$xl.Workbook.Worksheets[$tab].TabColor = $TabColor
}
@@ -174,7 +190,7 @@
$xl.save() ; $xl.Stream.Close() ; $xl.Dispose()
}
}
#if font colour was specified, set it on changed properties where the same key appears in both sheets.
#if font color was specified, set it on changed properties where the same key appears in both sheets.
if ($diff -and $FontColor -and ($propList -contains $Key) ) {
$updates = $diff.where({$_.SideIndicator -ne "=="}) | Group-object -Property $Key | Where-Object {$_.count -eq 2}
if ($updates) {