Add-ConditionalFormatting
Add
ConditionalFormatting
Adds conditional formatting to all or part of a worksheet.
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 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.
Add-ConditionalFormatting
Address
A block of cells to format - you can use a named range with -Address $ws.names[1] or $ws.cells["RangeName"]
Object
Object
None
RuleType
A standard named-rule - Top / Bottom / Less than / Greater than / Contains etc.
AboveAverage
AboveOrEqualAverage
BelowAverage
BelowOrEqualAverage
AboveStdDev
BelowStdDev
Bottom
BottomPercent
Top
TopPercent
Last7Days
LastMonth
LastWeek
NextMonth
NextWeek
ThisMonth
ThisWeek
Today
Tomorrow
Yesterday
BeginsWith
Between
ContainsBlanks
ContainsErrors
ContainsText
DuplicateValues
EndsWith
Equal
Expression
GreaterThan
GreaterThanOrEqual
LessThan
LessThanOrEqual
NotBetween
NotContains
NotContainsBlanks
NotContainsErrors
NotContainsText
NotEqual
UniqueValues
ThreeColorScale
TwoColorScale
ThreeIconSet
FourIconSet
FiveIconSet
DataBar
eExcelConditionalFormattingRuleType
eExcelConditionalFormattingRuleType
None
ConditionValue
A value for the condition (for example 2000 if the test is 'lessthan 2000'; Formulas should begin with "=" )
Object
Object
None
ConditionValue2
A second value for the conditions like "Between X and Y"
Object
Object
None
WorkSheet
The worksheet where the format is to be applied
ExcelWorksheet
ExcelWorksheet
None
ForegroundColor
Text color for matching objects
Object
Object
None
Reverse
Use the Icon-Set in reverse order, or reverse the orders of Two- & Three-Color Scales
SwitchParameter
False
BackgroundColor
Background color for matching items
Object
Object
None
BackgroundPattern
Background pattern for matching items
None
Solid
DarkGray
MediumGray
LightGray
Gray125
Gray0625
DarkVertical
DarkHorizontal
DarkDown
DarkUp
DarkGrid
DarkTrellis
LightVertical
LightHorizontal
LightDown
LightUp
LightGrid
LightTrellis
ExcelFillStyle
ExcelFillStyle
None
PatternColor
Secondary color when a background pattern requires it
Object
Object
None
NumberFormat
Sets the numeric format for matching items
Object
Object
None
Bold
Put matching items in bold face
SwitchParameter
False
Italic
Put matching items in italic
SwitchParameter
False
Underline
Underline matching items
SwitchParameter
False
StrikeThru
Strikethrough text of matching items
SwitchParameter
False
StopIfTrue
Prevent the processing of subsequent rules
SwitchParameter
False
Priority
Set the sequence for rule processing
Int32
Int32
0
PassThru
If specified pass the rule back to the caller to allow additional customization.
SwitchParameter
False
Add-ConditionalFormatting
Address
A block of cells to format - you can use a named range with -Address $ws.names[1] or $ws.cells["RangeName"]
Object
Object
None
WorkSheet
The worksheet where the format is to be applied
ExcelWorksheet
ExcelWorksheet
None
DataBarColor
Color for databar type charts
Object
Object
None
Priority
Set the sequence for rule processing
Int32
Int32
0
PassThru
If specified pass the rule back to the caller to allow additional customization.
SwitchParameter
False
Add-ConditionalFormatting
Address
A block of cells to format - you can use a named range with -Address $ws.names[1] or $ws.cells["RangeName"]
Object
Object
None
WorkSheet
The worksheet where the format is to be applied
ExcelWorksheet
ExcelWorksheet
None
ThreeIconsSet
One of the three-icon set types (e.g. Traffic Lights)
Arrows
ArrowsGray
Flags
Signs
Symbols
Symbols2
TrafficLights1
TrafficLights2
eExcelconditionalFormatting3IconsSetType
eExcelconditionalFormatting3IconsSetType
None
Reverse
Use the Icon-Set in reverse order, or reverse the orders of Two- & Three-Color Scales
SwitchParameter
False
Priority
Set the sequence for rule processing
Int32
Int32
0
PassThru
If specified pass the rule back to the caller to allow additional customization.
SwitchParameter
False
Add-ConditionalFormatting
Address
A block of cells to format - you can use a named range with -Address $ws.names[1] or $ws.cells["RangeName"]
Object
Object
None
WorkSheet
The worksheet where the format is to be applied
ExcelWorksheet
ExcelWorksheet
None
FourIconsSet
A four-icon set name
Arrows
ArrowsGray
Rating
RedToBlack
TrafficLights
eExcelconditionalFormatting4IconsSetType
eExcelconditionalFormatting4IconsSetType
None
Reverse
Use the Icon-Set in reverse order, or reverse the orders of Two- & Three-Color Scales
SwitchParameter
False
Priority
Set the sequence for rule processing
Int32
Int32
0
PassThru
If specified pass the rule back to the caller to allow additional customization.
SwitchParameter
False
Add-ConditionalFormatting
Address
A block of cells to format - you can use a named range with -Address $ws.names[1] or $ws.cells["RangeName"]
Object
Object
None
WorkSheet
The worksheet where the format is to be applied
ExcelWorksheet
ExcelWorksheet
None
FiveIconsSet
A five-icon set name
Arrows
ArrowsGray
Quarters
Rating
eExcelconditionalFormatting5IconsSetType
eExcelconditionalFormatting5IconsSetType
None
Reverse
Use the Icon-Set in reverse order, or reverse the orders of Two- & Three-Color Scales
SwitchParameter
False
Priority
Set the sequence for rule processing
Int32
Int32
0
PassThru
If specified pass the rule back to the caller to allow additional customization.
SwitchParameter
False
Address
A block of cells to format - you can use a named range with -Address $ws.names[1] or $ws.cells["RangeName"]
Object
Object
None
WorkSheet
The worksheet where the format is to be applied
ExcelWorksheet
ExcelWorksheet
None
RuleType
A standard named-rule - Top / Bottom / Less than / Greater than / Contains etc.
eExcelConditionalFormattingRuleType
eExcelConditionalFormattingRuleType
None
ForegroundColor
Text color for matching objects
Object
Object
None
DataBarColor
Color for databar type charts
Object
Object
None
ThreeIconsSet
One of the three-icon set types (e.g. Traffic Lights)
eExcelconditionalFormatting3IconsSetType
eExcelconditionalFormatting3IconsSetType
None
FourIconsSet
A four-icon set name
eExcelconditionalFormatting4IconsSetType
eExcelconditionalFormatting4IconsSetType
None
FiveIconsSet
A five-icon set name
eExcelconditionalFormatting5IconsSetType
eExcelconditionalFormatting5IconsSetType
None
Reverse
Use the Icon-Set in reverse order, or reverse the orders of Two- & Three-Color Scales
SwitchParameter
SwitchParameter
False
ConditionValue
A value for the condition (for example 2000 if the test is 'lessthan 2000'; Formulas should begin with "=" )
Object
Object
None
ConditionValue2
A second value for the conditions like "Between X and Y"
Object
Object
None
BackgroundColor
Background color for matching items
Object
Object
None
BackgroundPattern
Background pattern for matching items
ExcelFillStyle
ExcelFillStyle
None
PatternColor
Secondary color when a background pattern requires it
Object
Object
None
NumberFormat
Sets the numeric format for matching items
Object
Object
None
Bold
Put matching items in bold face
SwitchParameter
SwitchParameter
False
Italic
Put matching items in italic
SwitchParameter
SwitchParameter
False
Underline
Underline matching items
SwitchParameter
SwitchParameter
False
StrikeThru
Strikethrough text of matching items
SwitchParameter
SwitchParameter
False
StopIfTrue
Prevent the processing of subsequent rules
SwitchParameter
SwitchParameter
False
Priority
Set the sequence for rule processing
Int32
Int32
0
PassThru
If specified pass the rule back to the caller to allow additional customization.
SwitchParameter
SwitchParameter
False
-------------------------- EXAMPLE 1 --------------------------
PS\> $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 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 2 --------------------------
PS\> $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 accessto 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 3 --------------------------
PS\> Add-ConditionalFormatting -WorkSheet $sheet -Range "D2:D1048576" -DataBarColor Red
This time $sheet holds an ExcelWorkshseet object and databars are added to column D, excluding the top row.
-------------------------- EXAMPLE 4 --------------------------
PS\> 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 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 5 --------------------------
PS\> $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 6 --------------------------
PS\> 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.
Add-ExcelChart
Add
ExcelChart
Creates a chart in an existing Excel worksheet.
Creates a chart.
It is possible to configure the type of chart, the range of X values (labels) and Y values, the title, the legend, the ranges for both axes, the format and position of the axes.
Normally the command does not return anything, but if -passthru is specified the chart is returned so that it can be customized.
Add-ExcelChart
Worksheet
An existing Sheet where the chart will be created.
ExcelWorksheet
ExcelWorksheet
None
Title
The title for the chart.
String
String
None
ChartType
One of the built-in chart types, such as Pie, ClusteredColumn, Line etc. Defaults to "ColumnStacked".
Area
Line
Pie
Bubble
ColumnClustered
ColumnStacked
ColumnStacked100
ColumnClustered3D
ColumnStacked3D
ColumnStacked1003D
BarClustered
BarStacked
BarStacked100
BarClustered3D
BarStacked3D
BarStacked1003D
LineStacked
LineStacked100
LineMarkers
LineMarkersStacked
LineMarkersStacked100
PieOfPie
PieExploded
PieExploded3D
BarOfPie
XYScatterSmooth
XYScatterSmoothNoMarkers
XYScatterLines
XYScatterLinesNoMarkers
AreaStacked
AreaStacked100
AreaStacked3D
AreaStacked1003D
DoughnutExploded
RadarMarkers
RadarFilled
Surface
SurfaceWireframe
SurfaceTopView
SurfaceTopViewWireframe
Bubble3DEffect
StockHLC
StockOHLC
StockVHLC
StockVOHLC
CylinderColClustered
CylinderColStacked
CylinderColStacked100
CylinderBarClustered
CylinderBarStacked
CylinderBarStacked100
CylinderCol
ConeColClustered
ConeColStacked
ConeColStacked100
ConeBarClustered
ConeBarStacked
ConeBarStacked100
ConeCol
PyramidColClustered
PyramidColStacked
PyramidColStacked100
PyramidBarClustered
PyramidBarStacked
PyramidBarStacked100
PyramidCol
XYScatter
Radar
Doughnut
Pie3D
Line3D
Column3D
Area3D
eChartType
eChartType
ColumnStacked
ChartTrendLine
{{ Fill ChartTrendLine Description }}
Exponential
Linear
Logarithmic
MovingAvgerage
Polynomial
Power
eTrendLine[]
eTrendLine[]
None
XRange
The range of cells containing values for the X-Axis - usually labels.
Object
Object
None
YRange
The range(s) of cells holding values for the Y-Axis - usually "data".
Object
Object
None
Width
Width of the chart in Pixels; defaults to 500.
Int32
Int32
500
Height
Height of the chart in Pixels; defaults to 350.
Int32
Int32
350
Row
Row position of the top left corner of the chart. ) places at the top of the sheet, 1 below row 1 and so on.
Int32
Int32
0
RowOffSetPixels
Offset to position the chart by a fraction of a row.
Int32
Int32
10
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.
Int32
Int32
6
ColumnOffSetPixels
Offset to position the chart by a fraction of a column.
Int32
Int32
5
LegendPosition
Location of the key, either left, right, top, bottom or TopRight.
Top
Left
Right
Bottom
TopRight
eLegendPosition
eLegendPosition
None
LegendSize
Font size for the key.
Object
Object
None
LegendBold
Sets the key in bold type.
SwitchParameter
False
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.
SwitchParameter
False
ShowCategory
Attaches a category label, in charts which support this.
SwitchParameter
False
ShowPercent
Attaches a percentage label, in charts which support this.
SwitchParameter
False
SeriesHeader
Specify explicit name(s) for the data series, which will appear in the legend/key. The contents of a cell can be specified in the from =Sheet9!Z10 .
String[]
String[]
None
TitleBold
Sets the title in bold face.
SwitchParameter
False
TitleSize
Sets the point size for the title.
Int32
Int32
0
XAxisTitleText
Specifies a title for the X-axis.
String
String
None
XAxisTitleBold
Sets the X-axis title in bold face.
SwitchParameter
False
XAxisTitleSize
Sets the font size for the axis title.
Object
Object
None
XAxisNumberformat
A number formatting string, like "#,##0.00", for numbers along the X-axis.
String
String
None
XMajorUnit
Spacing for the major gridlines / tick marks along the X-axis.
Object
Object
None
XMinorUnit
Spacing for the minor gridlines / tick marks along the X-axis.
Object
Object
None
XMaxValue
Maximum value for the scale along the X-axis.
Object
Object
None
XMinValue
Minimum value for the scale along the X-axis.
Object
Object
None
XAxisPosition
Position for the X-axis (Top or Bottom).
Left
Bottom
Right
Top
eAxisPosition
eAxisPosition
None
YAxisTitleText
Specifies a title for the Y-axis.
String
String
None
YAxisTitleBold
Sets the Y-axis title in bold face.
SwitchParameter
False
YAxisTitleSize
Sets the font size for the Y-axis title
Object
Object
None
YAxisNumberformat
A number formatting string, like "#,##0.00", for numbers on the Y-axis.
String
String
None
YMajorUnit
Spacing for the major gridlines / tick marks on the Y-axis.
Object
Object
None
YMinorUnit
Spacing for the minor gridlines / tick marks on the Y-axis.
Object
Object
None
YMaxValue
Maximum value on the Y-axis.
Object
Object
None
YMinValue
Minimum value on the Y-axis.
Object
Object
None
YAxisPosition
Position for the Y-axis (Left or Right).
Left
Bottom
Right
Top
eAxisPosition
eAxisPosition
None
PassThru
Add-Excel chart doesn't normally return anything, but if -PassThru is specified it returns the newly created chart to allow it to be fine tuned.
SwitchParameter
False
Add-ExcelChart
PivotTable
Instead of specify X and Y ranges, get data from a PivotTable by passing a PivotTable Object.
ExcelPivotTable
ExcelPivotTable
None
Title
The title for the chart.
String
String
None
ChartType
One of the built-in chart types, such as Pie, ClusteredColumn, Line etc. Defaults to "ColumnStacked".
Area
Line
Pie
Bubble
ColumnClustered
ColumnStacked
ColumnStacked100
ColumnClustered3D
ColumnStacked3D
ColumnStacked1003D
BarClustered
BarStacked
BarStacked100
BarClustered3D
BarStacked3D
BarStacked1003D
LineStacked
LineStacked100
LineMarkers
LineMarkersStacked
LineMarkersStacked100
PieOfPie
PieExploded
PieExploded3D
BarOfPie
XYScatterSmooth
XYScatterSmoothNoMarkers
XYScatterLines
XYScatterLinesNoMarkers
AreaStacked
AreaStacked100
AreaStacked3D
AreaStacked1003D
DoughnutExploded
RadarMarkers
RadarFilled
Surface
SurfaceWireframe
SurfaceTopView
SurfaceTopViewWireframe
Bubble3DEffect
StockHLC
StockOHLC
StockVHLC
StockVOHLC
CylinderColClustered
CylinderColStacked
CylinderColStacked100
CylinderBarClustered
CylinderBarStacked
CylinderBarStacked100
CylinderCol
ConeColClustered
ConeColStacked
ConeColStacked100
ConeBarClustered
ConeBarStacked
ConeBarStacked100
ConeCol
PyramidColClustered
PyramidColStacked
PyramidColStacked100
PyramidBarClustered
PyramidBarStacked
PyramidBarStacked100
PyramidCol
XYScatter
Radar
Doughnut
Pie3D
Line3D
Column3D
Area3D
eChartType
eChartType
ColumnStacked
ChartTrendLine
{{ Fill ChartTrendLine Description }}
Exponential
Linear
Logarithmic
MovingAvgerage
Polynomial
Power
eTrendLine[]
eTrendLine[]
None
XRange
The range of cells containing values for the X-Axis - usually labels.
Object
Object
None
YRange
The range(s) of cells holding values for the Y-Axis - usually "data".
Object
Object
None
Width
Width of the chart in Pixels; defaults to 500.
Int32
Int32
500
Height
Height of the chart in Pixels; defaults to 350.
Int32
Int32
350
Row
Row position of the top left corner of the chart. ) places at the top of the sheet, 1 below row 1 and so on.
Int32
Int32
0
RowOffSetPixels
Offset to position the chart by a fraction of a row.
Int32
Int32
10
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.
Int32
Int32
6
ColumnOffSetPixels
Offset to position the chart by a fraction of a column.
Int32
Int32
5
LegendPosition
Location of the key, either left, right, top, bottom or TopRight.
Top
Left
Right
Bottom
TopRight
eLegendPosition
eLegendPosition
None
LegendSize
Font size for the key.
Object
Object
None
LegendBold
Sets the key in bold type.
SwitchParameter
False
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.
SwitchParameter
False
ShowCategory
Attaches a category label, in charts which support this.
SwitchParameter
False
ShowPercent
Attaches a percentage label, in charts which support this.
SwitchParameter
False
SeriesHeader
Specify explicit name(s) for the data series, which will appear in the legend/key. The contents of a cell can be specified in the from =Sheet9!Z10 .
String[]
String[]
None
TitleBold
Sets the title in bold face.
SwitchParameter
False
TitleSize
Sets the point size for the title.
Int32
Int32
0
XAxisTitleText
Specifies a title for the X-axis.
String
String
None
XAxisTitleBold
Sets the X-axis title in bold face.
SwitchParameter
False
XAxisTitleSize
Sets the font size for the axis title.
Object
Object
None
XAxisNumberformat
A number formatting string, like "#,##0.00", for numbers along the X-axis.
String
String
None
XMajorUnit
Spacing for the major gridlines / tick marks along the X-axis.
Object
Object
None
XMinorUnit
Spacing for the minor gridlines / tick marks along the X-axis.
Object
Object
None
XMaxValue
Maximum value for the scale along the X-axis.
Object
Object
None
XMinValue
Minimum value for the scale along the X-axis.
Object
Object
None
XAxisPosition
Position for the X-axis (Top or Bottom).
Left
Bottom
Right
Top
eAxisPosition
eAxisPosition
None
YAxisTitleText
Specifies a title for the Y-axis.
String
String
None
YAxisTitleBold
Sets the Y-axis title in bold face.
SwitchParameter
False
YAxisTitleSize
Sets the font size for the Y-axis title
Object
Object
None
YAxisNumberformat
A number formatting string, like "#,##0.00", for numbers on the Y-axis.
String
String
None
YMajorUnit
Spacing for the major gridlines / tick marks on the Y-axis.
Object
Object
None
YMinorUnit
Spacing for the minor gridlines / tick marks on the Y-axis.
Object
Object
None
YMaxValue
Maximum value on the Y-axis.
Object
Object
None
YMinValue
Minimum value on the Y-axis.
Object
Object
None
YAxisPosition
Position for the Y-axis (Left or Right).
Left
Bottom
Right
Top
eAxisPosition
eAxisPosition
None
PassThru
Add-Excel chart doesn't normally return anything, but if -PassThru is specified it returns the newly created chart to allow it to be fine tuned.
SwitchParameter
False
Worksheet
An existing Sheet where the chart will be created.
ExcelWorksheet
ExcelWorksheet
None
PivotTable
Instead of specify X and Y ranges, get data from a PivotTable by passing a PivotTable Object.
ExcelPivotTable
ExcelPivotTable
None
Title
The title for the chart.
String
String
None
ChartType
One of the built-in chart types, such as Pie, ClusteredColumn, Line etc. Defaults to "ColumnStacked".
eChartType
eChartType
ColumnStacked
ChartTrendLine
{{ Fill ChartTrendLine Description }}
eTrendLine[]
eTrendLine[]
None
XRange
The range of cells containing values for the X-Axis - usually labels.
Object
Object
None
YRange
The range(s) of cells holding values for the Y-Axis - usually "data".
Object
Object
None
Width
Width of the chart in Pixels; defaults to 500.
Int32
Int32
500
Height
Height of the chart in Pixels; defaults to 350.
Int32
Int32
350
Row
Row position of the top left corner of the chart. ) places at the top of the sheet, 1 below row 1 and so on.
Int32
Int32
0
RowOffSetPixels
Offset to position the chart by a fraction of a row.
Int32
Int32
10
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.
Int32
Int32
6
ColumnOffSetPixels
Offset to position the chart by a fraction of a column.
Int32
Int32
5
LegendPosition
Location of the key, either left, right, top, bottom or TopRight.
eLegendPosition
eLegendPosition
None
LegendSize
Font size for the key.
Object
Object
None
LegendBold
Sets the key in bold type.
SwitchParameter
SwitchParameter
False
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.
SwitchParameter
SwitchParameter
False
ShowCategory
Attaches a category label, in charts which support this.
SwitchParameter
SwitchParameter
False
ShowPercent
Attaches a percentage label, in charts which support this.
SwitchParameter
SwitchParameter
False
SeriesHeader
Specify explicit name(s) for the data series, which will appear in the legend/key. The contents of a cell can be specified in the from =Sheet9!Z10 .
String[]
String[]
None
TitleBold
Sets the title in bold face.
SwitchParameter
SwitchParameter
False
TitleSize
Sets the point size for the title.
Int32
Int32
0
XAxisTitleText
Specifies a title for the X-axis.
String
String
None
XAxisTitleBold
Sets the X-axis title in bold face.
SwitchParameter
SwitchParameter
False
XAxisTitleSize
Sets the font size for the axis title.
Object
Object
None
XAxisNumberformat
A number formatting string, like "#,##0.00", for numbers along the X-axis.
String
String
None
XMajorUnit
Spacing for the major gridlines / tick marks along the X-axis.
Object
Object
None
XMinorUnit
Spacing for the minor gridlines / tick marks along the X-axis.
Object
Object
None
XMaxValue
Maximum value for the scale along the X-axis.
Object
Object
None
XMinValue
Minimum value for the scale along the X-axis.
Object
Object
None
XAxisPosition
Position for the X-axis (Top or Bottom).
eAxisPosition
eAxisPosition
None
YAxisTitleText
Specifies a title for the Y-axis.
String
String
None
YAxisTitleBold
Sets the Y-axis title in bold face.
SwitchParameter
SwitchParameter
False
YAxisTitleSize
Sets the font size for the Y-axis title
Object
Object
None
YAxisNumberformat
A number formatting string, like "#,##0.00", for numbers on the Y-axis.
String
String
None
YMajorUnit
Spacing for the major gridlines / tick marks on the Y-axis.
Object
Object
None
YMinorUnit
Spacing for the minor gridlines / tick marks on the Y-axis.
Object
Object
None
YMaxValue
Maximum value on the Y-axis.
Object
Object
None
YMinValue
Minimum value on the Y-axis.
Object
Object
None
YAxisPosition
Position for the Y-axis (Left or Right).
eAxisPosition
eAxisPosition
None
PassThru
Add-Excel chart doesn't normally return anything, but if -PassThru is specified it returns the newly created chart to allow it to be fine tuned.
SwitchParameter
SwitchParameter
False
OfficeOpenXml.Drawing.Chart.ExcelChart
-------------------------- EXAMPLE 1 --------------------------
PS\> $Excel = ConvertFrom-Csv @"
Product, City, Sales
Apple, London, 300
Orange, London, 400
Banana, London, 300
Orange, Paris, 600
Banana, Paris, 300
Apple, New York, 1200
"@ | Export-Excel -Path test.xlsx -PassThru
Add-ExcelChart -Worksheet $Excel.Workbook.Worksheets[1] -ChartType "Doughnut" -XRange "A2:B7" -YRange "C2:C7" -width 500
Close-ExcelPackage -Show $Excel
The first command expands a multi-line string into 6 rows of data which is exported to new Excel file; leaving an ExcelPackage object in $excel The second command adds a chart - the cell ranges are explicitly specified.
Note that the XRange (labels) is TWO columns wide and the chart will combine the name of the product and the name of the City to create the label.
The width of the chart is set explictly, the default legend is used and there is no Chart title.
-------------------------- EXAMPLE 2 --------------------------
PS\> $Excel = Invoke-Sum (Get-Process) Company Handles, PM, VirtualMemorySize | Export-Excel $path -AutoSize -ExcelChartDefinition $c -AutoNameRange -PassThru
Add-ExcelChart -Worksheet $Excel.Workbook.Worksheets[1] -Title "VM use" -ChartType PieExploded3D -XRange "Name" -YRange "VirtualMemorySize" -NoLegend -ShowCategory
Close-ExcelPackage $Excel -Show
The first line exports information and creates named ranges for each column.
The Second line uses the ranges to specify a chart - the labels come from the range "Name" and the data from the range "VirtualMemorySize"
The chart is specified as a 3D exploded PIE chart, with a title of "VM Use" and instead of a legend the the pie slices are identified with a label.
-------------------------- EXAMPLE 3 --------------------------
PS\> $Excel = Invoke-Sum (Get-Process) Company Handles, PM, VirtualMemorySize | Export-Excel test.xlsx -TableName Processes -PassThru
Add-ExcelChart -Worksheet $Excel.Workbook.Worksheets[1] -Title Stats -ChartType LineMarkersStacked -XRange "Processes[Name]" -YRange "Processes[PM]", "Processes[VirtualMemorySize]" -SeriesHeader 'PM', 'VMSize'
Close-ExcelPackage $Excel -Show
The first line exports information to a table in new file; and captures the excel Package object in $Excel
The second line creates a chart on the first page of the work sheet, using the notation "TableName[ColumnnName]" to refer to the data, the labels come Name column in the table, and the data series from its PM and VirtualMemorySize columns. The display names for these in the header are set to 'PM' and 'VMSize'.
-------------------------- EXAMPLE 4 --------------------------
PS\> $excel = 0..360 | ForEach-Object {[pscustomobject][ordered]@{x = $_; Sinx = "=Sin(Radians(x)) "}} | Export-Excel -AutoNameRange -Path Text.xlsx -WorkSheetname SinX -PassThru
Add-ExcelChart -Worksheet $excel.Workbook.Worksheets["Sinx"] -ChartType line -XRange "X" -YRange "Sinx" -Title "Graph of Sine X" -TitleBold -TitleSize 14 \`
-Column 2 -ColumnOffSetPixels 35 -Width 800 -XAxisTitleText "Degrees" -XAxisTitleBold -XAxisTitleSize 12 -XMajorUnit 30 -XMinorUnit 10 -XMinValue 0 -XMaxValue 361 -XAxisNumberformat "000" \`
-YMinValue -1.25 -YMaxValue 1.25 -YMajorUnit 0.25 -YAxisNumberformat "0.00" -YAxisTitleText "Sine" -YAxisTitleBold -YAxisTitleSize 12 \`
-SeriesHeader "Sin(x)" -LegendSize 8 -legendBold -LegendPosition Bottom
Close-ExcelPackage $Excel -Show
The first line puts numbers from 0 to 360 into a sheet, as the first column, and a formula to calculate the Sine of that number of number of degrees in the second column. It creates named-ranges for the two columns - "X" and "SinX" respectively
The Add-ExcelChart command adds a chart to that worksheet, specifying a line chart with the X values coming from named-range "X" and the Y values coming from named-range "SinX". The chart has a title, and is positioned to the right of column 2 and sized 800 pixels wide
The X-axis is labelled "Degrees", in bold 12 point type and runs from 0 to 361 with labels every 30, and minor tick marks every 10. Degrees are shown padded to 3 digits.
The Y-axis is labelled "Sine" and to allow some room above and below its scale runs from -1.25 to 1.25, and is marked off in units of 0.25 shown to two decimal places.
The key will for the chart will be at the bottom in 8 point bold type and the line will be named "Sin(x)".
Add-ExcelDataValidationRule
Add
ExcelDataValidationRule
Adds data validation to a range of cells
Excel supports the validation of user input, and ranges of cells can be marked to only contain numbers, or date, or Text up to a particular length, or selections from a list. This command adds validation rules to a worksheet.
Add-ExcelDataValidationRule
Range
The range of cells to be validate, for example, "B2:C100"
Object
Object
None
WorkSheet
The worksheet where the cells should be validated
ExcelWorksheet
ExcelWorksheet
None
ValidationType
An option corresponding to a choice from the 'Allow' pull down on the settings page in the Excel dialog. "Any" means "any allowed" - in other words, no Validation
Object
Object
None
Operator
The operator to apply to Decimal, Integer, TextLength, DateTime and time fields, for example "equal" or "between"
between
notBetween
equal
notEqual
lessThan
lessThanOrEqual
greaterThan
greaterThanOrEqual
ExcelDataValidationOperator
ExcelDataValidationOperator
Equal
Value
For Decimal, Integer, TextLength, DateTime the [first] data value
Object
Object
None
Value2
When using the between operator, the second data value
Object
Object
None
Formula
The [first] data value as a formula. Use absolute formulas $A$1 if (e.g.) you want all cells to check against the same list
Object
Object
None
Formula2
When using the between operator, the second data value as a formula
Object
Object
None
ValueSet
When using the list validation type, a set of values (rather than refering to Sheet!B$2:B$100 )
Object
Object
None
ShowErrorMessage
Corresponds to the the 'Show Error alert ...' check box on error alert page in the Excel dialog
SwitchParameter
False
ErrorStyle
Stop, Warning, or Infomation, corresponding to to the style setting in the Excel dialog
undefined
stop
warning
information
ExcelDataValidationWarningStyle
ExcelDataValidationWarningStyle
None
ErrorTitle
The title for the message box corresponding to to the title setting in the Excel dialog
String
String
None
ErrorBody
The error message corresponding to to the Error message setting in the Excel dialog
String
String
None
ShowPromptMessage
Corresponds to the the 'Show Input message ...' check box on input message page in the Excel dialog
SwitchParameter
False
PromptBody
The prompt message corresponding to to the Input message setting in the Excel dialog
String
String
None
PromptTitle
The title for the message box corresponding to to the title setting in the Excel dialog
String
String
None
NoBlank
By default the 'Ignore blank' option will be selected, unless NoBlank is sepcified.
String
String
None
Range
The range of cells to be validate, for example, "B2:C100"
Object
Object
None
WorkSheet
The worksheet where the cells should be validated
ExcelWorksheet
ExcelWorksheet
None
ValidationType
An option corresponding to a choice from the 'Allow' pull down on the settings page in the Excel dialog. "Any" means "any allowed" - in other words, no Validation
Object
Object
None
Operator
The operator to apply to Decimal, Integer, TextLength, DateTime and time fields, for example "equal" or "between"
ExcelDataValidationOperator
ExcelDataValidationOperator
Equal
Value
For Decimal, Integer, TextLength, DateTime the [first] data value
Object
Object
None
Value2
When using the between operator, the second data value
Object
Object
None
Formula
The [first] data value as a formula. Use absolute formulas $A$1 if (e.g.) you want all cells to check against the same list
Object
Object
None
Formula2
When using the between operator, the second data value as a formula
Object
Object
None
ValueSet
When using the list validation type, a set of values (rather than refering to Sheet!B$2:B$100 )
Object
Object
None
ShowErrorMessage
Corresponds to the the 'Show Error alert ...' check box on error alert page in the Excel dialog
SwitchParameter
SwitchParameter
False
ErrorStyle
Stop, Warning, or Infomation, corresponding to to the style setting in the Excel dialog
ExcelDataValidationWarningStyle
ExcelDataValidationWarningStyle
None
ErrorTitle
The title for the message box corresponding to to the title setting in the Excel dialog
String
String
None
ErrorBody
The error message corresponding to to the Error message setting in the Excel dialog
String
String
None
ShowPromptMessage
Corresponds to the the 'Show Input message ...' check box on input message page in the Excel dialog
SwitchParameter
SwitchParameter
False
PromptBody
The prompt message corresponding to to the Input message setting in the Excel dialog
String
String
None
PromptTitle
The title for the message box corresponding to to the title setting in the Excel dialog
String
String
None
NoBlank
By default the 'Ignore blank' option will be selected, unless NoBlank is sepcified.
String
String
None
-------------------------- EXAMPLE 1 --------------------------
PS\>Add-ExcelDataValidationRule -WorkSheet $PlanSheet -Range 'E2:E1001' -ValidationType Integer -Operator between -Value 0 -Value2 100 \`
-ShowErrorMessage -ErrorStyle stop -ErrorTitle 'Invalid Data' -ErrorBody 'Percentage must be a whole number between 0 and 100'
This defines a validation rule on cells E2-E1001; it is an integer rule and requires a number between 0 and 100. If a value is input with a fraction, negative number, or positive number > 100 a stop dialog box appears.
-------------------------- EXAMPLE 2 --------------------------
PS\>Add-ExcelDataValidationRule -WorkSheet $PlanSheet -Range 'B2:B1001' -ValidationType List -Formula 'values!$a$2:$a$1000'
-ShowErrorMessage -ErrorStyle stop -ErrorTitle 'Invalid Data' -ErrorBody 'You must select an item from the list'
This defines a list rule on Cells B2:1001, and the posible values are in a sheet named "values" at cells A2 to A1000 Blank cells in this range are ignored.
If $ signs were left out of the fomrmula B2 would be checked against A2-A1000, B3, against A3-A1001, B4 against A4-A1002 up to B1001 beng checked against A1001-A1999
-------------------------- EXAMPLE 3 --------------------------
PS\>Add-ExcelDataValidationRule -WorkSheet $PlanSheet -Range 'I2:N1001' -ValidationType List -ValueSet @('yes','YES','Yes')
-ShowErrorMessage -ErrorStyle stop -ErrorTitle 'Invalid Data' -ErrorBody "Select Yes or leave blank for no"
Similar to the previous example but this time provides a value set; Excel comparisons are case sesnsitive, hence 3 versions of Yes.
Add-ExcelName
Add
ExcelName
Adds a named-range to an existing Excel worksheet.
It is often helpful to be able to refer to sets of cells with a name rather than using their co-ordinates; Add-ExcelName sets up these names.
Add-ExcelName
Range
The range of cells to assign as a name.
ExcelRange
ExcelRange
None
RangeName
The name to assign to the range. If the name exists it will be updated to the new range. If no name is specified, the first cell in the range will be used as the name.
String
String
None
Range
The range of cells to assign as a name.
ExcelRange
ExcelRange
None
RangeName
The name to assign to the range. If the name exists it will be updated to the new range. If no name is specified, the first cell in the range will be used as the name.
String
String
None
-------------------------- EXAMPLE 1 --------------------------
PS\> Add-ExcelName -Range $ws.Cells[$dataRange] -RangeName $rangeName
$WS is a worksheet, and $dataRange is a string describing a range of cells - for example "A1:Z10" - which will become a named range, using the name in $rangeName.
Add-ExcelTable
Add
ExcelTable
Adds Tables to Excel workbooks.
Unlike named ranges, where the name only needs to be unique within a sheet, Table names must be unique in the workbook.
Tables carry formatting and by default have a filter.
The filter, header, totals, first and last column highlights can all be configured.
Add-ExcelTable
Range
The range of cells to assign to a table.
ExcelRange
ExcelRange
None
TableName
The name for the Table - this should be unqiue in the Workbook - auto generated names will be used if this is left empty.
String
String
None
TableStyle
The Style for the table, by default "Medium6" is used
None
Custom
Light1
Light2
Light3
Light4
Light5
Light6
Light7
Light8
Light9
Light10
Light11
Light12
Light13
Light14
Light15
Light16
Light17
Light18
Light19
Light20
Light21
Medium1
Medium2
Medium3
Medium4
Medium5
Medium6
Medium7
Medium8
Medium9
Medium10
Medium11
Medium12
Medium13
Medium14
Medium15
Medium16
Medium17
Medium18
Medium19
Medium20
Medium21
Medium22
Medium23
Medium24
Medium25
Medium26
Medium27
Medium28
Dark1
Dark2
Dark3
Dark4
Dark5
Dark6
Dark7
Dark8
Dark9
Dark10
Dark11
TableStyles
TableStyles
Medium6
TotalSettings
A HashTable in the form ColumnName = "Average"|"Count"|"CountNums"|"Max"|"Min"|"None"|"StdDev"|"Sum"|"Var" - if specified, -ShowTotal is not needed.
Hashtable
Hashtable
None
ShowHeader
By default the header row is shown - it can be turned off with -ShowHeader:$false.
SwitchParameter
False
ShowFilter
By default the filter is enabled - it can be turned off with -ShowFilter:$false.
SwitchParameter
False
ShowTotal
Show total adds a totals row. This does not automatically sum the columns but provides a drop-down in each to select sum, average etc
SwitchParameter
False
ShowFirstColumn
Highlights the first column in bold.
SwitchParameter
False
ShowLastColumn
Highlights the last column in bold.
SwitchParameter
False
ShowRowStripes
By default the table formats show striped rows, the can be turned off with -ShowRowStripes:$false
SwitchParameter
False
ShowColumnStripes
Turns on column stripes.
SwitchParameter
False
PassThru
If -PassThru is specified, the table object will be returned to allow additional changes to be made.
SwitchParameter
False
Range
The range of cells to assign to a table.
ExcelRange
ExcelRange
None
TableName
The name for the Table - this should be unqiue in the Workbook - auto generated names will be used if this is left empty.
String
String
None
TableStyle
The Style for the table, by default "Medium6" is used
TableStyles
TableStyles
Medium6
ShowHeader
By default the header row is shown - it can be turned off with -ShowHeader:$false.
SwitchParameter
SwitchParameter
False
ShowFilter
By default the filter is enabled - it can be turned off with -ShowFilter:$false.
SwitchParameter
SwitchParameter
False
ShowTotal
Show total adds a totals row. This does not automatically sum the columns but provides a drop-down in each to select sum, average etc
SwitchParameter
SwitchParameter
False
TotalSettings
A HashTable in the form ColumnName = "Average"|"Count"|"CountNums"|"Max"|"Min"|"None"|"StdDev"|"Sum"|"Var" - if specified, -ShowTotal is not needed.
Hashtable
Hashtable
None
ShowFirstColumn
Highlights the first column in bold.
SwitchParameter
SwitchParameter
False
ShowLastColumn
Highlights the last column in bold.
SwitchParameter
SwitchParameter
False
ShowRowStripes
By default the table formats show striped rows, the can be turned off with -ShowRowStripes:$false
SwitchParameter
SwitchParameter
False
ShowColumnStripes
Turns on column stripes.
SwitchParameter
SwitchParameter
False
PassThru
If -PassThru is specified, the table object will be returned to allow additional changes to be made.
SwitchParameter
SwitchParameter
False
OfficeOpenXml.Table.ExcelTable
-------------------------- EXAMPLE 1 --------------------------
PS\> Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $TableName
$WS is a worksheet, and $dataRange is a string describing a range of cells - for example "A1:Z10". This range which will become a table, named $TableName
-------------------------- EXAMPLE 2 --------------------------
PS\> Add-ExcelTable -Range $ws.cells[$($ws.Dimension.address)] -TableStyle Light1 -TableName Musictable -ShowFilter:$false -ShowTotal -ShowFirstColumn
Again $ws is a worksheet, range here is the whole of the active part of the worksheet. The table style and name are set, the filter is turned off, and a "Totals" row added, and first column is set in bold.
Add-PivotTable
Add
PivotTable
Adds a PivotTable (and optional PivotChart) to a workbook.
If the PivotTable already exists, the source data will be updated.
Add-PivotTable
PivotTableName
Name for the new PivotTable - this will be the name of a sheet in the Workbook.
String
String
None
Address
By default, a PivotTable will be created on its own sheet, but it can be created on an existing sheet by giving the address where the top left corner of the table should go. (Allow two rows for the filter if one is used.)
ExcelAddressBase
ExcelAddressBase
None
ExcelPackage
An Excel-package object for the workbook.
Object
Object
None
SourceWorkSheet
Worksheet where the data is found.
Object
Object
None
SourceRange
Address range in the worksheet e.g "A10:F20" - the first row must be column names: if not specified the whole sheet will be used.
Object
Object
None
PivotRows
Fields to set as rows in the PivotTable.
Object
Object
None
PivotData
A hash table in form "FieldName"="Function", where function is one of Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP.
Object
Object
None
PivotColumns
Fields to set as columns in the PivotTable.
Object
Object
None
PivotFilter
Fields to use to filter in the PivotTable.
Object
Object
None
PivotDataToColumn
If there are multiple data items in a PivotTable, by default they are shown on separate rows; this switch makes them separate columns.
SwitchParameter
False
PivotTotals
Define whether totals should be added to rows, columns neither, or both (the default is both).
String
String
Both
NoTotalsInPivot
Included for compatibility - equivalent to -PivotTotals "None".
SwitchParameter
False
GroupDateRow
The name of a row field which should be grouped by parts of the date/time (ignored if GroupDateRow is not specified)
String
String
None
GroupDatePart
The Part(s) of the date to use in the grouping (ignored if GroupDateRow is not specified)
Years
Quarters
Months
Days
Hours
Minutes
Seconds
eDateGroupBy[]
eDateGroupBy[]
None
GroupNumericRow
The name of a row field which should be grouped by Number (e.g. 0-99, 100-199, 200-299 )
String
String
None
GroupNumericMin
The starting point for grouping
Double
Double
0
GroupNumericMax
The endpoint for grouping
Double
Double
1.79769313486232E+308
GroupNumericInterval
The interval for grouping
Double
Double
100
PivotNumberFormat
Number format to apply to the data cells in the PivotTable.
String
String
None
PivotTableStyle
Apply a table style to the PivotTable.
None
Custom
Light1
Light2
Light3
Light4
Light5
Light6
Light7
Light8
Light9
Light10
Light11
Light12
Light13
Light14
Light15
Light16
Light17
Light18
Light19
Light20
Light21
Medium1
Medium2
Medium3
Medium4
Medium5
Medium6
Medium7
Medium8
Medium9
Medium10
Medium11
Medium12
Medium13
Medium14
Medium15
Medium16
Medium17
Medium18
Medium19
Medium20
Medium21
Medium22
Medium23
Medium24
Medium25
Medium26
Medium27
Medium28
Dark1
Dark2
Dark3
Dark4
Dark5
Dark6
Dark7
Dark8
Dark9
Dark10
Dark11
TableStyles
TableStyles
None
PivotChartDefinition
Use a chart definition instead of specifying chart settings one by one.
Object
Object
None
Activate
If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified.
SwitchParameter
False
PassThru
Return the PivotTable so it can be customized.
SwitchParameter
False
Add-PivotTable
PivotTableName
Name for the new PivotTable - this will be the name of a sheet in the Workbook.
String
String
None
Address
By default, a PivotTable will be created on its own sheet, but it can be created on an existing sheet by giving the address where the top left corner of the table should go. (Allow two rows for the filter if one is used.)
ExcelAddressBase
ExcelAddressBase
None
ExcelPackage
An Excel-package object for the workbook.
Object
Object
None
SourceWorkSheet
Worksheet where the data is found.
Object
Object
None
SourceRange
Address range in the worksheet e.g "A10:F20" - the first row must be column names: if not specified the whole sheet will be used.
Object
Object
None
PivotRows
Fields to set as rows in the PivotTable.
Object
Object
None
PivotData
A hash table in form "FieldName"="Function", where function is one of Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP.
Object
Object
None
PivotColumns
Fields to set as columns in the PivotTable.
Object
Object
None
PivotFilter
Fields to use to filter in the PivotTable.
Object
Object
None
PivotDataToColumn
If there are multiple data items in a PivotTable, by default they are shown on separate rows; this switch makes them separate columns.
SwitchParameter
False
PivotTotals
Define whether totals should be added to rows, columns neither, or both (the default is both).
String
String
Both
NoTotalsInPivot
Included for compatibility - equivalent to -PivotTotals "None".
SwitchParameter
False
GroupDateRow
The name of a row field which should be grouped by parts of the date/time (ignored if GroupDateRow is not specified)
String
String
None
GroupDatePart
The Part(s) of the date to use in the grouping (ignored if GroupDateRow is not specified)
Years
Quarters
Months
Days
Hours
Minutes
Seconds
eDateGroupBy[]
eDateGroupBy[]
None
GroupNumericRow
The name of a row field which should be grouped by Number (e.g. 0-99, 100-199, 200-299 )
String
String
None
GroupNumericMin
The starting point for grouping
Double
Double
0
GroupNumericMax
The endpoint for grouping
Double
Double
1.79769313486232E+308
GroupNumericInterval
The interval for grouping
Double
Double
100
PivotNumberFormat
Number format to apply to the data cells in the PivotTable.
String
String
None
PivotTableStyle
Apply a table style to the PivotTable.
None
Custom
Light1
Light2
Light3
Light4
Light5
Light6
Light7
Light8
Light9
Light10
Light11
Light12
Light13
Light14
Light15
Light16
Light17
Light18
Light19
Light20
Light21
Medium1
Medium2
Medium3
Medium4
Medium5
Medium6
Medium7
Medium8
Medium9
Medium10
Medium11
Medium12
Medium13
Medium14
Medium15
Medium16
Medium17
Medium18
Medium19
Medium20
Medium21
Medium22
Medium23
Medium24
Medium25
Medium26
Medium27
Medium28
Dark1
Dark2
Dark3
Dark4
Dark5
Dark6
Dark7
Dark8
Dark9
Dark10
Dark11
TableStyles
TableStyles
None
IncludePivotChart
If specified, a chart will be included.
SwitchParameter
False
ChartTitle
Optional title for the pivot chart, by default the title omitted.
String
String
None
ChartHeight
Height of the chart in Pixels (400 by default).
Int32
Int32
400
ChartWidth
Width of the chart in Pixels (600 by default).
Int32
Int32
600
ChartRow
Cell position of the top left corner of the chart, there will be this number of rows above the top edge of the chart (default is 0, chart starts at top edge of row 1).
Int32
Int32
0
ChartColumn
Cell position of the top left corner of the chart, there will be this number of cells to the left of the chart (default is 4, chart starts at left edge of column E).
Int32
Int32
4
ChartRowOffSetPixels
Vertical offset of the chart from the cell corner.
Int32
Int32
0
ChartColumnOffSetPixels
Horizontal offset of the chart from the cell corner.
Int32
Int32
0
ChartType
Type of chart; defaults to "Pie".
Area
Line
Pie
Bubble
ColumnClustered
ColumnStacked
ColumnStacked100
ColumnClustered3D
ColumnStacked3D
ColumnStacked1003D
BarClustered
BarStacked
BarStacked100
BarClustered3D
BarStacked3D
BarStacked1003D
LineStacked
LineStacked100
LineMarkers
LineMarkersStacked
LineMarkersStacked100
PieOfPie
PieExploded
PieExploded3D
BarOfPie
XYScatterSmooth
XYScatterSmoothNoMarkers
XYScatterLines
XYScatterLinesNoMarkers
AreaStacked
AreaStacked100
AreaStacked3D
AreaStacked1003D
DoughnutExploded
RadarMarkers
RadarFilled
Surface
SurfaceWireframe
SurfaceTopView
SurfaceTopViewWireframe
Bubble3DEffect
StockHLC
StockOHLC
StockVHLC
StockVOHLC
CylinderColClustered
CylinderColStacked
CylinderColStacked100
CylinderBarClustered
CylinderBarStacked
CylinderBarStacked100
CylinderCol
ConeColClustered
ConeColStacked
ConeColStacked100
ConeBarClustered
ConeBarStacked
ConeBarStacked100
ConeCol
PyramidColClustered
PyramidColStacked
PyramidColStacked100
PyramidBarClustered
PyramidBarStacked
PyramidBarStacked100
PyramidCol
XYScatter
Radar
Doughnut
Pie3D
Line3D
Column3D
Area3D
eChartType
eChartType
Pie
NoLegend
If specified hides the chart legend.
SwitchParameter
False
ShowCategory
If specified attaches the category to slices in a pie chart : not supported on all chart types, this may give errors if applied to an unsupported type.
SwitchParameter
False
ShowPercent
If specified attaches percentages to slices in a pie chart.
SwitchParameter
False
Activate
If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified.
SwitchParameter
False
PassThru
Return the PivotTable so it can be customized.
SwitchParameter
False
PivotTableName
Name for the new PivotTable - this will be the name of a sheet in the Workbook.
String
String
None
Address
By default, a PivotTable will be created on its own sheet, but it can be created on an existing sheet by giving the address where the top left corner of the table should go. (Allow two rows for the filter if one is used.)
ExcelAddressBase
ExcelAddressBase
None
ExcelPackage
An Excel-package object for the workbook.
Object
Object
None
SourceWorkSheet
Worksheet where the data is found.
Object
Object
None
SourceRange
Address range in the worksheet e.g "A10:F20" - the first row must be column names: if not specified the whole sheet will be used.
Object
Object
None
PivotRows
Fields to set as rows in the PivotTable.
Object
Object
None
PivotData
A hash table in form "FieldName"="Function", where function is one of Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP.
Object
Object
None
PivotColumns
Fields to set as columns in the PivotTable.
Object
Object
None
PivotFilter
Fields to use to filter in the PivotTable.
Object
Object
None
PivotDataToColumn
If there are multiple data items in a PivotTable, by default they are shown on separate rows; this switch makes them separate columns.
SwitchParameter
SwitchParameter
False
PivotTotals
Define whether totals should be added to rows, columns neither, or both (the default is both).
String
String
Both
NoTotalsInPivot
Included for compatibility - equivalent to -PivotTotals "None".
SwitchParameter
SwitchParameter
False
GroupDateRow
The name of a row field which should be grouped by parts of the date/time (ignored if GroupDateRow is not specified)
String
String
None
GroupDatePart
The Part(s) of the date to use in the grouping (ignored if GroupDateRow is not specified)
eDateGroupBy[]
eDateGroupBy[]
None
GroupNumericRow
The name of a row field which should be grouped by Number (e.g. 0-99, 100-199, 200-299 )
String
String
None
GroupNumericMin
The starting point for grouping
Double
Double
0
GroupNumericMax
The endpoint for grouping
Double
Double
1.79769313486232E+308
GroupNumericInterval
The interval for grouping
Double
Double
100
PivotNumberFormat
Number format to apply to the data cells in the PivotTable.
String
String
None
PivotTableStyle
Apply a table style to the PivotTable.
TableStyles
TableStyles
None
PivotChartDefinition
Use a chart definition instead of specifying chart settings one by one.
Object
Object
None
IncludePivotChart
If specified, a chart will be included.
SwitchParameter
SwitchParameter
False
ChartTitle
Optional title for the pivot chart, by default the title omitted.
String
String
None
ChartHeight
Height of the chart in Pixels (400 by default).
Int32
Int32
400
ChartWidth
Width of the chart in Pixels (600 by default).
Int32
Int32
600
ChartRow
Cell position of the top left corner of the chart, there will be this number of rows above the top edge of the chart (default is 0, chart starts at top edge of row 1).
Int32
Int32
0
ChartColumn
Cell position of the top left corner of the chart, there will be this number of cells to the left of the chart (default is 4, chart starts at left edge of column E).
Int32
Int32
4
ChartRowOffSetPixels
Vertical offset of the chart from the cell corner.
Int32
Int32
0
ChartColumnOffSetPixels
Horizontal offset of the chart from the cell corner.
Int32
Int32
0
ChartType
Type of chart; defaults to "Pie".
eChartType
eChartType
Pie
NoLegend
If specified hides the chart legend.
SwitchParameter
SwitchParameter
False
ShowCategory
If specified attaches the category to slices in a pie chart : not supported on all chart types, this may give errors if applied to an unsupported type.
SwitchParameter
SwitchParameter
False
ShowPercent
If specified attaches percentages to slices in a pie chart.
SwitchParameter
SwitchParameter
False
Activate
If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified.
SwitchParameter
SwitchParameter
False
PassThru
Return the PivotTable so it can be customized.
SwitchParameter
SwitchParameter
False
OfficeOpenXml.Table.PivotTable.ExcelPivotTable
-------------------------- EXAMPLE 1 --------------------------
PS\> $excel = Get-Service | Export-Excel -Path test.xlsx -WorksheetName Services -PassThru -AutoSize -DisplayPropertySet -TableName ServiceTable -Title "Services on $Env:COMPUTERNAME"
Add-PivotTable -ExcelPackage $excel -PivotTableName ServiceSummary -SourceRange $excel.Workbook.Worksheets\[1\].Tables\[0\].Address -PivotRows Status -PivotData Name -NoTotalsInPivot -Activate
Close-ExcelPackage $excel -Show
This exports data to new workbook and creates a table with the data in it.
The Pivot table is added on its own page, the table created in the first command is used as the source for the PivotTable; which counts the service names in for each Status.
At the end the Pivot page is made active.
-------------------------- EXAMPLE 2 --------------------------
PS\> $chartdef = New-ExcelChartDefinition -Title "Gross and net by city and product" -ChartType ColumnClustered `
-Column 11 -Width 500 -Height 360 -YMajorUnit 500 -YMinorUnit 100 -YAxisNumberformat "$#,##0" -LegendPosition Bottom
$excel = ConvertFrom-Csv @"
Product, City, Gross, Net
Apple, London , 300, 250
Orange, London , 400, 350
Banana, London , 300, 200
Orange, Paris, 600, 500
Banana, Paris, 300, 200
Apple, New York, 1200,700
"@ | Export-Excel -Path "test.xlsx" -TableStyle Medium13 -tablename "RawData" -PassThru
Add-PivotTable -PivotTableName Sales -Address $excel.Workbook.Worksheets[1].Cells["F1"] `
-SourceWorkSheet $excel.Workbook.Worksheets[1] -PivotRows City -PivotColumns Product -PivotData @{Gross="Sum";Net="Sum"} `
-PivotNumberFormat "$#,##0.00" -PivotTotals Both -PivotTableStyle Medium12 -PivotChartDefinition $chartdef
Close-ExcelPackage -show $excel
This script starts by defining a chart.
Then it exports some data to an XLSX file and keeps the file open.
The next step is to add the pivot table, normally this would be on its own sheet in the workbook, but here -Address is specified to place it beside the data.
The Add-Pivot table is given the chart definition and told to create a tale using the City field to create rows, the Product field to create columns and the data should be the sum of the gross field and the sum of the net field; grand totals for both gross and net are included for rows (Cities) and columns (Products) and the data is explicitly formatted as a currency.
Note that in the chart definition the number format for the axis does not include any fraction part.
-------------------------- EXAMPLE 3 --------------------------
PS> $excel = Convertfrom-csv @"
Location,OrderDate,quantity
Boston,1/1/2017,100
New York,1/21/2017,200
Boston,1/11/2017,300
New York,1/9/2017,400
Boston,1/18/2017,500
Boston,2/1/2017,600
New York,2/21/2017,700
New York,2/11/2017,800
Boston,2/9/2017,900
Boston,2/18/2017,1000
New York,1/1/2018,100
Boston,1/21/2018,200
New York,1/11/2018,300
Boston,1/9/2018,400
New York,1/18/2018,500
Boston,2/1/2018,600
Boston,2/21/2018,700
New York,2/11/2018,800
New York,2/9/2018,900
Boston,2/18/2018,1000
"@ | Select-Object -Property @{n="OrderDate";e={[datetime]::ParseExact($_.OrderDate,"M/d/yyyy",(Get-Culture))}},
Location, Quantity | Export-Excel "test2.xlsx" -PassThru -AutoSize
Set-ExcelColumn -Worksheet $excel.sheet1 -Column 1 -NumberFormat 'Short Date'
$pt = Add-PivotTable -PassThru -PivotTableName "ByDate" -Address $excel.Sheet1.cells["F1"] -SourceWorkSheet $excel.Sheet1 -PivotRows location,orderdate -PivotData @{'quantity'='sum'} -GroupDateRow orderdate -GroupDatePart 'Months,Years' -PivotTotals None
$pt.RowFields[0].SubtotalTop=$false
$pt.RowFields[0].Compact=$false
Close-ExcelPackage $excel -Show
Here the data contains dates formatted as strings using US format.
These are converted to DateTime objects before being exported to Excel; the "OrderDate" column is formatted with the local short-date style.
Then the PivotTable is added; it groups information by date and location, the date is split into years and then months.
No grand totals are displayed.
The Pivot table object is caught in a variable, and the "Location" column has its subtotal moved from the top to the bottom of each location section, and the "Compact" option is disabled to prevent "Year" moving into the same column as location.
Finally the workbook is saved and shown in Excel.
Add-WorkSheet
Add
WorkSheet
Adds a worksheet to an existing workbook.
If the named worksheet already exists, the -Clearsheet parameter decides whether it should be deleted and a new one returned, or if not specified the existing sheet will be returned.
By default the sheet is created at the end of the work book, the -MoveXXXX switches allow the sheet to be [re]positioned at the start or before or after another sheet.
A new sheet will only be made the default sheet when excel opens if -Activate is specified.
Add-WorkSheet
ExcelPackage
An object representing an Excel Package.
ExcelPackage
ExcelPackage
None
WorksheetName
The name of the worksheet, 'Sheet1' by default.
String
String
None
ClearSheet
If the worksheet already exists, by default it will returned, unless -ClearSheet is specified in which case it will be deleted and re-created.
SwitchParameter
False
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.
SwitchParameter
False
MoveToEnd
If specified, the worksheet will be moved to the end of the workbook.
(This is the default position for newly created sheets, but it can be used to move existing sheets.)
SwitchParameter
False
MoveBefore
If specified, the worksheet will be moved before the nominated one (which can be an index starting from 1, or a name).
MoveBefore takes precedence over MoveAfter if both are specified.
Object
Object
None
MoveAfter
If specified, the worksheet will be moved after the nominated one (which can be an index starting from 1, or a name or *).
If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically.
Object
Object
None
Activate
If there is already content in the workbook the new sheet will not be active UNLESS Activate is specified.
SwitchParameter
False
CopySource
If worksheet is provided as a copy source the new worksheet will be a copy of it. The source can be in the same workbook, or in a different file.
ExcelWorksheet
ExcelWorksheet
None
NoClobber
Ignored but retained for backwards compatibility.
SwitchParameter
False
Add-WorkSheet
ExcelWorkbook
An Excel Workbook to which the Worksheet will be added - a Package contains one Workbook, so you can use whichever fits at the time.
ExcelWorkbook
ExcelWorkbook
None
WorksheetName
The name of the worksheet, 'Sheet1' by default.
String
String
None
ClearSheet
If the worksheet already exists, by default it will returned, unless -ClearSheet is specified in which case it will be deleted and re-created.
SwitchParameter
False
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.
SwitchParameter
False
MoveToEnd
If specified, the worksheet will be moved to the end of the workbook.
(This is the default position for newly created sheets, but it can be used to move existing sheets.)
SwitchParameter
False
MoveBefore
If specified, the worksheet will be moved before the nominated one (which can be an index starting from 1, or a name).
MoveBefore takes precedence over MoveAfter if both are specified.
Object
Object
None
MoveAfter
If specified, the worksheet will be moved after the nominated one (which can be an index starting from 1, or a name or *).
If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically.
Object
Object
None
Activate
If there is already content in the workbook the new sheet will not be active UNLESS Activate is specified.
SwitchParameter
False
CopySource
If worksheet is provided as a copy source the new worksheet will be a copy of it. The source can be in the same workbook, or in a different file.
ExcelWorksheet
ExcelWorksheet
None
NoClobber
Ignored but retained for backwards compatibility.
SwitchParameter
False
ExcelPackage
An object representing an Excel Package.
ExcelPackage
ExcelPackage
None
ExcelWorkbook
An Excel Workbook to which the Worksheet will be added - a Package contains one Workbook, so you can use whichever fits at the time.
ExcelWorkbook
ExcelWorkbook
None
WorksheetName
The name of the worksheet, 'Sheet1' by default.
String
String
None
ClearSheet
If the worksheet already exists, by default it will returned, unless -ClearSheet is specified in which case it will be deleted and re-created.
SwitchParameter
SwitchParameter
False
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.
SwitchParameter
SwitchParameter
False
MoveToEnd
If specified, the worksheet will be moved to the end of the workbook.
(This is the default position for newly created sheets, but it can be used to move existing sheets.)
SwitchParameter
SwitchParameter
False
MoveBefore
If specified, the worksheet will be moved before the nominated one (which can be an index starting from 1, or a name).
MoveBefore takes precedence over MoveAfter if both are specified.
Object
Object
None
MoveAfter
If specified, the worksheet will be moved after the nominated one (which can be an index starting from 1, or a name or *).
If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically.
Object
Object
None
Activate
If there is already content in the workbook the new sheet will not be active UNLESS Activate is specified.
SwitchParameter
SwitchParameter
False
CopySource
If worksheet is provided as a copy source the new worksheet will be a copy of it. The source can be in the same workbook, or in a different file.
ExcelWorksheet
ExcelWorksheet
None
NoClobber
Ignored but retained for backwards compatibility.
SwitchParameter
SwitchParameter
False
OfficeOpenXml.ExcelWorksheet
-------------------------- EXAMPLE 1 --------------------------
PS\> $WorksheetActors = $ExcelPackage | Add-WorkSheet -WorkSheetname Actors
$ExcelPackage holds an Excel package object (returned by Open-ExcelPackage, or Export-Excel -passthru). This command will add a sheet named 'Actors', or return the sheet if it exists, and the result is stored in $WorkSheetActors.
-------------------------- EXAMPLE 2 --------------------------
PS\> $WorksheetActors = Add-WorkSheet -ExcelPackage $ExcelPackage -WorkSheetname "Actors" -ClearSheet -MoveToStart
This time the Excel package object is passed as a parameter instead of piped.
If the 'Actors' sheet already exists it is deleted and re-created.
The new sheet will be created last in the workbook, and -MoveToStart Moves it to the start.
-------------------------- EXAMPLE 3 --------------------------
PS\> $null = Add-WorkSheet -ExcelWorkbook $wb -WorkSheetname $DestinationName -CopySource $sourceWs -Activate
This time a workbook is used instead of a package, and a worksheet is copied - $SourceWs is a worksheet object, which can come from the same workbook or a different one.
Here the new copy of the data is made the active sheet when the workbook is opened.
Close-ExcelPackage
Close
ExcelPackage
Closes an Excel Package, saving, saving under a new name or abandoning changes and opening the file in Excel as required.
When working with an ExcelPackage object, the Workbook is held in memory and not saved until the .Save() method of the package is called.
Close-ExcelPackage saves and disposes of the Package object.
It can be called with -NoSave to abandon the file without saving, with a new "SaveAs" filename, and/or with a password to protect the file. And -Show will open the file in Excel; -Calculate will try to update the workbook, although not everything can be recalculated
Close-ExcelPackage
ExcelPackage
Package to close.
ExcelPackage
ExcelPackage
None
SaveAs
Save file with a new name (ignored if -NoSave Specified).
Object
Object
None
Password
Password to protect the file.
String
String
None
Show
Open the file in Excel.
SwitchParameter
False
NoSave
Abandon the file without saving.
SwitchParameter
False
Calculate
Attempt to recalculation the workbook before saving
SwitchParameter
False
ExcelPackage
Package to close.
ExcelPackage
ExcelPackage
None
Show
Open the file in Excel.
SwitchParameter
SwitchParameter
False
NoSave
Abandon the file without saving.
SwitchParameter
SwitchParameter
False
SaveAs
Save file with a new name (ignored if -NoSave Specified).
Object
Object
None
Password
Password to protect the file.
String
String
None
Calculate
Attempt to recalculation the workbook before saving
SwitchParameter
SwitchParameter
False
-------------------------- EXAMPLE 1 --------------------------
Close-ExcelPackage -show $excel
$excel holds a package object, this saves the workbook and loads it into Excel.
-------------------------- EXAMPLE 2 --------------------------
Close-ExcelPackage -NoSave $excel
$excel holds a package object, this disposes of it without writing it to disk.
Compare-WorkSheet
Compare
WorkSheet
Compares two worksheets and shows the differences.
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 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 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.
Compare-WorkSheet
Referencefile
First file to compare.
Object
Object
None
Differencefile
Second file to compare.
Object
Object
None
WorkSheetName
Name(s) of worksheets to compare.
Object
Object
Sheet1
Property
Properties to include in the comparison - supports wildcards, default is "*".
Object
Object
*
ExcludeProperty
Properties to exclude from the comparison - supports wildcards.
Object
Object
None
Headername
Specifies custom property names to use, instead of the values defined in the starting row of the sheet.
String[]
String[]
None
Startrow
The row from where we start to import data: all rows above the start row are disregarded. By default, this is the first row.
Int32
Int32
1
AllDataBackgroundColor
If specified, highlights all the cells - so you can make Equal cells one color, and Different cells another.
Object
Object
None
BackgroundColor
If specified, highlights the rows with differences.
Object
Object
None
TabColor
If specified identifies the tabs which contain difference rows (ignored if -BackgroundColor is omitted).
Object
Object
None
Key
Name of a column which is unique and will be used to add a row to the DIFF object, defaults to "Name".
Object
Object
Name
FontColor
If specified, highlights the DIFF columns in rows which have the same key.
Object
Object
None
Show
If specified, opens the Excel workbooks instead of outputting the diff to the console (unless -PassThru is also specified).
SwitchParameter
False
GridView
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.
SwitchParameter
False
PassThru
If specified a full set of DIFF data is returned without filtering to the specified properties.
SwitchParameter
False
IncludeEqual
If specified the result will include equal rows as well. By default only different rows are returned.
SwitchParameter
False
ExcludeDifferent
If specified, the result includes only the rows where both are equal.
SwitchParameter
False
Compare-WorkSheet
Referencefile
First file to compare.
Object
Object
None
Differencefile
Second file to compare.
Object
Object
None
WorkSheetName
Name(s) of worksheets to compare.
Object
Object
Sheet1
Property
Properties to include in the comparison - supports wildcards, default is "*".
Object
Object
*
ExcludeProperty
Properties to exclude from the comparison - supports wildcards.
Object
Object
None
NoHeader
Automatically generate property names (P1, P2, P3 ...) instead of the using the values the starting row of the sheet.
SwitchParameter
False
Startrow
The row from where we start to import data: all rows above the start row are disregarded. By default, this is the first row.
Int32
Int32
1
AllDataBackgroundColor
If specified, highlights all the cells - so you can make Equal cells one color, and Different cells another.
Object
Object
None
BackgroundColor
If specified, highlights the rows with differences.
Object
Object
None
TabColor
If specified identifies the tabs which contain difference rows (ignored if -BackgroundColor is omitted).
Object
Object
None
Key
Name of a column which is unique and will be used to add a row to the DIFF object, defaults to "Name".
Object
Object
Name
FontColor
If specified, highlights the DIFF columns in rows which have the same key.
Object
Object
None
Show
If specified, opens the Excel workbooks instead of outputting the diff to the console (unless -PassThru is also specified).
SwitchParameter
False
GridView
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.
SwitchParameter
False
PassThru
If specified a full set of DIFF data is returned without filtering to the specified properties.
SwitchParameter
False
IncludeEqual
If specified the result will include equal rows as well. By default only different rows are returned.
SwitchParameter
False
ExcludeDifferent
If specified, the result includes only the rows where both are equal.
SwitchParameter
False
Referencefile
First file to compare.
Object
Object
None
Differencefile
Second file to compare.
Object
Object
None
WorkSheetName
Name(s) of worksheets to compare.
Object
Object
Sheet1
Property
Properties to include in the comparison - supports wildcards, default is "*".
Object
Object
*
ExcludeProperty
Properties to exclude from the comparison - supports wildcards.
Object
Object
None
Headername
Specifies custom property names to use, instead of the values defined in the starting row of the sheet.
String[]
String[]
None
NoHeader
Automatically generate property names (P1, P2, P3 ...) instead of the using the values the starting row of the sheet.
SwitchParameter
SwitchParameter
False
Startrow
The row from where we start to import data: all rows above the start row are disregarded. By default, this is the first row.
Int32
Int32
1
AllDataBackgroundColor
If specified, highlights all the cells - so you can make Equal cells one color, and Different cells another.
Object
Object
None
BackgroundColor
If specified, highlights the rows with differences.
Object
Object
None
TabColor
If specified identifies the tabs which contain difference rows (ignored if -BackgroundColor is omitted).
Object
Object
None
Key
Name of a column which is unique and will be used to add a row to the DIFF object, defaults to "Name".
Object
Object
Name
FontColor
If specified, highlights the DIFF columns in rows which have the same key.
Object
Object
None
Show
If specified, opens the Excel workbooks instead of outputting the diff to the console (unless -PassThru is also specified).
SwitchParameter
SwitchParameter
False
GridView
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.
SwitchParameter
SwitchParameter
False
PassThru
If specified a full set of DIFF data is returned without filtering to the specified properties.
SwitchParameter
SwitchParameter
False
IncludeEqual
If specified the result will include equal rows as well. By default only different rows are returned.
SwitchParameter
SwitchParameter
False
ExcludeDifferent
If specified, the result includes only the rows where both are equal.
SwitchParameter
SwitchParameter
False
-------------------------- EXAMPLE 1 --------------------------
PS\> 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 results will be presented as a table.
-------------------------- EXAMPLE 2 --------------------------
PS\> Compare-WorkSheet "Server54.xlsx" "Server55.xlsx" -WorkSheetName Services -GridView
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 3 --------------------------
PS\> Compare-WorkSheet 'Server54.xlsx' 'Server55.xlsx' -WorkSheetName Services -BackgroundColor lightGreen
This version of the command outputs the differences between the "services" pages and highlights any different rows in the spreadsheet files.
-------------------------- EXAMPLE 4 --------------------------
PS\> 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.
-------------------------- EXAMPLE 5 --------------------------
PS\> 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.
-------------------------- EXAMPLE 6 --------------------------
PS\> 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 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 7 --------------------------
PS\>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.
Convert-ExcelRangeToImage
Convert
ExcelRangeToImage
Gets the specified part of an Excel file and exports it as an image
Excel allows charts to be exported directly to a file, but it can't do this with the rest of a sheet. To work round this, this function
* Opens a copy of Excel and loads a file
* Selects a worksheet and then a range of cells in that worksheet
* Copies the select to the clipboard
* Saves the clipboard contents as an image file (it will save as .JPG unless the file name ends .BMP or .PNG)
* Copies a single cell to the clipboard (to prevent the "you have put a lot in the clipboard" message appearing)
* Closes Excel
Unlike most functions in the module it needs a local copy of Excel to be installed.
Convert-ExcelRangeToImage
Path
Path to the Excel file
Object
Object
None
WorkSheetname
Worksheet name - if none is specified "Sheet1" will be assumed
Object
Object
Sheet1
Range
Range of cells within the sheet, e.g "A1:Z99"
Object
Object
None
Destination
A bmp, png or jpg file where the result will be saved
Object
Object
"$pwd\temp.png"
Show
If specified opens the image in the default viewer.
SwitchParameter
False
Path
Path to the Excel file
Object
Object
None
WorkSheetname
Worksheet name - if none is specified "Sheet1" will be assumed
Object
Object
Sheet1
Range
Range of cells within the sheet, e.g "A1:Z99"
Object
Object
None
Destination
A bmp, png or jpg file where the result will be saved
Object
Object
"$pwd\temp.png"
Show
If specified opens the image in the default viewer.
SwitchParameter
SwitchParameter
False
ConvertFrom-ExcelSheet
ConvertFrom
ExcelSheet
Exports Sheets from Excel Workbooks to CSV files.
This command provides a convenient way to run Import-Excel @ImportParameters | Select-Object @selectParameters | export-Csv @ ExportParameters It can take the parameters -AsText , as used in Import-Excel, )Properties & -ExcludeProperties as used in Select-Object and -Append, -Delimiter and -Encoding as used in Export-CSV
ConvertFrom-ExcelSheet
Path
The path to the .XLSX file which will be exported.
String
String
None
OutputPath
The directory where the output file(s) will be created. The file name(s) will match the name of the workbook page which contained the data.
String
String
None
SheetName
The name of a sheet to export, or a regular expression which is used to identify sheets
String
String
None
Encoding
Sets the text encoding for the output data file; UTF8 bu default
Encoding
Encoding
None
Extension
Sets the file extension for the exported data, defaults to CSV
.txt
.log
.csv
String
String
None
Delimiter
Selects , or ; as the delimeter for the exported data - if not specified , is used by default.
;
String
String
None
Property
Specifies the properties to select. Wildcards are permitted - the default is "*". The value of the Property parameter can be a new calculated property, and follows the same pattern as Select-Item
Object
Object
None
ExcludeProperty
Specifies the properties that to exclude from the export. Wildcards are permitted. This parameter is effective only when the command also includes the Property parameter.
Object
Object
None
AsText
AsText allows selected columns to be returned as the text displayed in their cells, instead of their value. (* is supported as a wildcard.)
String[]
String[]
None
AsDate
Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.)
String[]
String[]
None
Append
Use this parameter to have the export add output to the end of the file. Without this parameter, the command replaces the file contents without warning.
SwitchParameter
False
Append
Use this parameter to have the export add output to the end of the file. Without this parameter, the command replaces the file contents without warning.
SwitchParameter
SwitchParameter
False
AsText
AsText allows selected columns to be returned as the text displayed in their cells, instead of their value. (* is supported as a wildcard.)
String[]
String[]
None
AsDate
Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.)
String[]
String[]
None
Delimiter
Selects , or ; as the delimeter for the exported data - if not specified , is used by default.
String
String
None
Encoding
Sets the text encoding for the output data file; UTF8 bu default
Encoding
Encoding
None
ExcludeProperty
Specifies the properties that to exclude from the export. Wildcards are permitted. This parameter is effective only when the command also includes the Property parameter.
Object
Object
None
Extension
Sets the file extension for the exported data, defaults to CSV
String
String
None
OutputPath
The directory where the output file(s) will be created. The file name(s) will match the name of the workbook page which contained the data.
String
String
None
Path
The path to the .XLSX file which will be exported.
String
String
None
Property
Specifies the properties to select. Wildcards are permitted - the default is "*". The value of the Property parameter can be a new calculated property, and follows the same pattern as Select-Item
Object
Object
None
SheetName
The name of a sheet to export, or a regular expression which is used to identify sheets
String
String
None
None
System.Object
-------------------------- Example 1 --------------------------
PS C:\> ConvertFrom-ExcelSheet Path .\__tests__\First10Races.xlsx -OutputPath .. -AsText GridPosition,date
First10Races.xlsx contains information about Motor races. The race date and grid (starting) position are stored with custom formats. The command specifies the path to the file, and the directory to create the output file, and specifies that the columns "GridPosition" and "Date" should be treated as text to preserve their formatting
-------------------------- Example 2 --------------------------
PS C:\> ConvertFrom-ExcelSheet Path .\__tests__\First10Races.xlsx -OutputPath .. -AsText "GridPosition" -Property driver, @{n="date"; e={[datetime]::FromOADate($_.Date).tostring("#MM/dd/yyyy#")}} , FinishPosition, GridPosition
This uses the same file as example 1. Because the race date has a custom format, it imports as a number, The requirement is to create a CSV file with the Driver, a specially formatted Date, FinishPostion and GridPostion (keeping its custom formatting). The command specifies the path to the file, and the directory to create the output file, specifies that the column "GridPosition" should be treated as text instead of a number, and the output properties should be Driver, a calculated "date" field, FinishPosition and GridPsition. FromOADate converts the dates used by Excel (Days since Jan 1 1900) to a datetime object.
Online Version:
https://github.com/dfinke/ImportExcel
ConvertFrom-ExcelToSQLInsert
ConvertFrom
ExcelToSQLInsert
Generate SQL insert statements from Excel spreadsheet.
Generate SQL insert statements from Excel spreadsheet.
ConvertFrom-ExcelToSQLInsert
TableName
Name of the target database table.
Object
Object
None
Path
Path to an existing .XLSX file This parameter is passed to Import-Excel as is.
Object
Object
None
WorkSheetname
Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported. This parameter is passed to Import-Excel as is.
Object
Object
1
StartRow
The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. When one of both parameters are provided, the property names are automatically created and this row will be treated as a regular row containing data.
Int32
Int32
0
Header
Specifies custom property names to use, instead of the values defined in the column headers of the TopRow. If you provide fewr header names than there is data in the worksheet, then only the data with a corresponding header name will be imported and the data without header name will be disregarded. If you provide more header names than there is data in the worksheet, then all data will be imported and all objects will have all the property names you defined in the header names. As such, the last properties will be blank as there is no data for them.
String[]
String[]
None
NoHeader
Automatically generate property names (P1, P2, P3, ..) instead of the ones defined in the column headers of the TopRow. This switch is best used when you want to import the complete worksheet 'as is' and are not concerned with the property names.
SwitchParameter
False
DataOnly
Import only rows and columns that contain data, empty rows and empty columns are not imported.
SwitchParameter
False
ConvertEmptyStringsToNull
If specified, cells without any data are replaced with NULL, instead of an empty string. This is to address behviors in certain DBMS where an empty string is insert as 0 for INT column, instead of a NULL value.
SwitchParameter
False
UseMSSQLSyntax
{{ Fill UseMSSQLSyntax Description }}
SwitchParameter
False
TableName
Name of the target database table.
Object
Object
None
Path
Path to an existing .XLSX file This parameter is passed to Import-Excel as is.
Object
Object
None
WorkSheetname
Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported. This parameter is passed to Import-Excel as is.
Object
Object
1
StartRow
The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. When one of both parameters are provided, the property names are automatically created and this row will be treated as a regular row containing data.
Int32
Int32
0
Header
Specifies custom property names to use, instead of the values defined in the column headers of the TopRow. If you provide fewr header names than there is data in the worksheet, then only the data with a corresponding header name will be imported and the data without header name will be disregarded. If you provide more header names than there is data in the worksheet, then all data will be imported and all objects will have all the property names you defined in the header names. As such, the last properties will be blank as there is no data for them.
String[]
String[]
None
NoHeader
Automatically generate property names (P1, P2, P3, ..) instead of the ones defined in the column headers of the TopRow. This switch is best used when you want to import the complete worksheet 'as is' and are not concerned with the property names.
SwitchParameter
SwitchParameter
False
DataOnly
Import only rows and columns that contain data, empty rows and empty columns are not imported.
SwitchParameter
SwitchParameter
False
ConvertEmptyStringsToNull
If specified, cells without any data are replaced with NULL, instead of an empty string. This is to address behviors in certain DBMS where an empty string is insert as 0 for INT column, instead of a NULL value.
SwitchParameter
SwitchParameter
False
UseMSSQLSyntax
{{ Fill UseMSSQLSyntax Description }}
SwitchParameter
SwitchParameter
False
-------------------------- EXAMPLE 1 --------------------------
Generate SQL insert statements from Movies.xlsx file, leaving blank cells as empty strings:
----------------------------------------------------------
| File: Movies.xlsx - Sheet: Sheet1 |
----------------------------------------------------------
| A B C |
|1 Movie Name Year Rating |
|2 The Bodyguard 1992 9 |
|3 The Matrix 1999 8 |
|4 Skyfall 2012 9 |
|5 The Avengers 2012 |
----------------------------------------------------------
PS C:\> ConvertFrom-ExcelToSQLInsert -TableName "Movies" -Path 'C:\Movies.xlsx'
INSERT INTO Movies ('Movie Name', 'Year', 'Rating') Values('The Bodyguard', '1992', '9');
INSERT INTO Movies ('Movie Name', 'Year', 'Rating') Values('The Matrix', '1999', '8');
INSERT INTO Movies ('Movie Name', 'Year', 'Rating') Values('Skyfall', '2012', '9');
INSERT INTO Movies ('Movie Name', 'Year', 'Rating') Values('The Avengers', '2012', '');
-------------------------- EXAMPLE 2 --------------------------
Generate SQL insert statements from Movies.xlsx file, specify NULL instead of an empty string.
----------------------------------------------------------
| File: Movies.xlsx - Sheet: Sheet1 |
----------------------------------------------------------
| A B C |
|1 Movie Name Year Rating |
|2 The Bodyguard 1992 9 |
|3 The Matrix 1999 8 |
|4 Skyfall 2012 9 |
|5 The Avengers 2012 |
----------------------------------------------------------
PS C:\> ConvertFrom-ExcelToSQLInsert -TableName "Movies" -Path "C:\Movies.xlsx" -ConvertEmptyStringsToNull
INSERT INTO Movies ('Movie Name', 'Year', 'Rating') Values('The Bodyguard', '1992', '9');
INSERT INTO Movies ('Movie Name', 'Year', 'Rating') Values('The Matrix', '1999', '8');
INSERT INTO Movies ('Movie Name', 'Year', 'Rating') Values('Skyfall', '2012', '9');
INSERT INTO Movies ('Movie Name', 'Year', 'Rating') Values('The Avengers', '2012', NULL);
Copy-ExcelWorkSheet
Copy
ExcelWorkSheet
Copies a worksheet between workbooks or within the same workbook.
Copy-ExcelWorkSheet takes a Source object which is either a worksheet, or a package, Workbook or path, in which case the source worksheet can be specified by name or number (starting from 1). The destination worksheet can be explicitly named, or will follow the name of the source if no name is specified. The Destination workbook can be given as the path to an XLSx file, an ExcelPackage object or an ExcelWorkbook object.
Copy-ExcelWorkSheet
SourceObject
An ExcelWorkbook or ExcelPackage object or the path to an XLSx file where the data is found.
Object
Object
None
SourceWorkSheet
Name or number (starting from 1) of the worksheet in the source workbook (defaults to 1).
Object
Object
1
DestinationWorkbook
An ExcelWorkbook or ExcelPackage object or the path to an XLSx file where the data should be copied.
Object
Object
None
DestinationWorksheet
Name of the worksheet in the destination workbook; by default the same as the source worksheet's name. If the sheet exists it will be deleted and re-copied.
Object
Object
None
Show
if the destination is an excel package or a path, launch excel and open the file on completion.
SwitchParameter
False
SourceObject
An ExcelWorkbook or ExcelPackage object or the path to an XLSx file where the data is found.
Object
Object
None
SourceWorkSheet
Name or number (starting from 1) of the worksheet in the source workbook (defaults to 1).
Object
Object
1
DestinationWorkbook
An ExcelWorkbook or ExcelPackage object or the path to an XLSx file where the data should be copied.
Object
Object
None
DestinationWorksheet
Name of the worksheet in the destination workbook; by default the same as the source worksheet's name. If the sheet exists it will be deleted and re-copied.
Object
Object
None
Show
if the destination is an excel package or a path, launch excel and open the file on completion.
SwitchParameter
SwitchParameter
False
-------------------------- EXAMPLE 1 --------------------------
Copy-ExcelWorkSheet -SourceWorkbook Test1.xlsx -DestinationWorkbook Test2.xlsx
This is the simplest version of the command: no source worksheet is specified so Copy-ExcelWorksheet uses the first sheet in the workbook No Destination sheet is specified so the new worksheet will be the same as the one which is being copied.
-------------------------- EXAMPLE 2 --------------------------
Copy-ExcelWorkSheet -SourceWorkbook Server1.xlsx -sourceWorksheet "Settings" -DestinationWorkbook Settings.xlsx -DestinationWorksheet "Server1"
Here the Settings page from Server1's workbook is copied to the 'Server1" page of a "Settings" workbook.
-------------------------- EXAMPLE 3 --------------------------
$excel = Open-ExcelPackage .\test.xlsx
C:\> Copy-ExcelWorkSheet -SourceWorkbook $excel -SourceWorkSheet "first" -DestinationWorkbook $excel -Show -DestinationWorksheet Duplicate This opens the workbook test.xlsx and copies the worksheet named "first" to a new worksheet named "Duplicate", because -Show is specified the file is saved and opened in Excel
-------------------------- EXAMPLE 4 --------------------------
$excel = Open-ExcelPackage .\test.xlsx
C:\> Copy-ExcelWorkSheet -SourceWorkbook $excel -SourceWorkSheet 1 -DestinationWorkbook $excel -DestinationWorksheet Duplicate C:\> Close-ExcelPackage $excel This is almost the same as the previous example, except source sheet is specified by position rather than name and because -Show is not specified, so other steps can be carried using the package object, at the end the file is saved by Close-ExcelPackage
Expand-NumberFormat
Expand
NumberFormat
Converts short names for number formats to the formatting strings used in Excel
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 when Excel loads (so date will use the local ordering of year, month and Day). Excel also changes how markers in the are presented different cultures "," is used in the format string to mean "local thousand seperator" but depending on the country "," or "." or " " may used as the thousand seperator.
Expand-NumberFormat
NumberFormat
The format string to Expand
Object
Object
None
NumberFormat
The format string to Expand
Object
Object
None
System.String
-------------------------- EXAMPLE 1 --------------------------
Expand-NumberFormat percentage
Returns "0.00%"
-------------------------- EXAMPLE 2 --------------------------
Expand-NumberFormat Currency
Returns the currency format specified in the local regional settings, which 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.
Export-Excel
Export
Excel
Exports data to an Excel worksheet.
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. The parameter -NoNumberConversion * can be used if number conversion is not desired.
Export-Excel
Path
Path to a new or existing .XLSX file.
String
String
None
InputObject
Date is usually piped into Export-Excel, but it also accepts data through the InputObject parameter
Object
Object
None
Calculate
If specified, a recalculation of the worksheet will be requested before saving.
SwitchParameter
False
Show
Opens the Excel file immediately after creation; convenient for viewing the results instantly without having to search for the file first.
SwitchParameter
False
WorksheetName
The name of a sheet within the workbook - "Sheet1" by default.
String
String
Sheet1
Password
Sets password protection on the workbook.
String
String
None
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).
SwitchParameter
False
Append
If specified data will be added to the end of an existing sheet, using the same column headings.
SwitchParameter
False
Title
Text of a title to be placed in the top left cell.
String
String
None
TitleFillPattern
Sets the fill pattern for the title cell.
None
Solid
DarkGray
MediumGray
LightGray
Gray125
Gray0625
DarkVertical
DarkHorizontal
DarkDown
DarkUp
DarkGrid
DarkTrellis
LightVertical
LightHorizontal
LightDown
LightUp
LightGrid
LightTrellis
ExcelFillStyle
ExcelFillStyle
Solid
TitleBold
Sets the title in boldface type.
SwitchParameter
False
TitleSize
Sets the point size for the title.
Int32
Int32
22
TitleBackgroundColor
Sets the cell background color for the title cell.
Object
Object
None
IncludePivotTable
Adds a PivotTable using the data in the worksheet.
SwitchParameter
False
PivotTableName
If a PivotTable is created from command line parameters, specifies the name of the new sheet holding the pivot. Defaults to "WorksheetName-PivotTable".
String
String
None
PivotRows
Name(s) of column(s) from the spreadsheet which will provide the Row name(s) in a PivotTable created from command line parameters.
String[]
String[]
None
PivotColumns
Name(s) of columns from the spreadsheet which will provide the Column name(s) in a PivotTable created from command line parameters.
String[]
String[]
None
PivotData
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.
Object
Object
None
PivotFilter
Name(s) columns from the spreadsheet which will provide the Filter name(s) in a PivotTable created from command line parameters.
String[]
String[]
None
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.
SwitchParameter
False
PivotTableDefinition
Instead of describing a single PivotTable with multiple command-line parameters; you can use a HashTable in the form PivotTableName = Definition;
In this table Definition is itself a Hashtable with Sheet, PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values. The New-PivotTableDefinition command will create the definition from a command line.
Hashtable
Hashtable
None
IncludePivotChart
Include a chart with the PivotTable - implies -IncludePivotTable.
SwitchParameter
False
ChartType
The type for PivotChart (one of Excel's defined chart types).
Area
Line
Pie
Bubble
ColumnClustered
ColumnStacked
ColumnStacked100
ColumnClustered3D
ColumnStacked3D
ColumnStacked1003D
BarClustered
BarStacked
BarStacked100
BarClustered3D
BarStacked3D
BarStacked1003D
LineStacked
LineStacked100
LineMarkers
LineMarkersStacked
LineMarkersStacked100
PieOfPie
PieExploded
PieExploded3D
BarOfPie
XYScatterSmooth
XYScatterSmoothNoMarkers
XYScatterLines
XYScatterLinesNoMarkers
AreaStacked
AreaStacked100
AreaStacked3D
AreaStacked1003D
DoughnutExploded
RadarMarkers
RadarFilled
Surface
SurfaceWireframe
SurfaceTopView
SurfaceTopViewWireframe
Bubble3DEffect
StockHLC
StockOHLC
StockVHLC
StockVOHLC
CylinderColClustered
CylinderColStacked
CylinderColStacked100
CylinderBarClustered
CylinderBarStacked
CylinderBarStacked100
CylinderCol
ConeColClustered
ConeColStacked
ConeColStacked100
ConeBarClustered
ConeBarStacked
ConeBarStacked100
ConeCol
PyramidColClustered
PyramidColStacked
PyramidColStacked100
PyramidBarClustered
PyramidBarStacked
PyramidBarStacked100
PyramidCol
XYScatter
Radar
Doughnut
Pie3D
Line3D
Column3D
Area3D
eChartType
eChartType
Pie
NoLegend
Exclude the legend from the PivotChart.
SwitchParameter
False
ShowCategory
Add category labels to the PivotChart.
SwitchParameter
False
ShowPercent
Add percentage labels to the PivotChart.
SwitchParameter
False
AutoSize
Sizes the width of the Excel column to the maximum width needed to display all the containing data in that cell.
SwitchParameter
False
MaxAutoSizeRows
Autosizing can be time consuming, so this sets a maximum number of rows to look at for the Autosize operation. Default is 1000; If 0 is specified ALL rows will be checked
Object
Object
1000
NoClobber
Not used. Left in to avoid problems with older scripts, it may be removed in future versions.
SwitchParameter
False
FreezeTopRow
Freezes headers etc. in the top row.
SwitchParameter
False
FreezeFirstColumn
Freezes titles etc. in the left column.
SwitchParameter
False
FreezeTopRowFirstColumn
Freezes top row and left column (equivalent to Freeze pane 2,2 ).
SwitchParameter
False
FreezePane
Freezes panes at specified coordinates (in the form RowNumber, ColumnNumber).
Int32[]
Int32[]
None
AutoFilter
Enables the Excel filter on the complete header row, so users can easily sort, filter and/or search the data in the selected column.
SwitchParameter
False
BoldTopRow
Makes the top row boldface.
SwitchParameter
False
NoHeader
Specifies that field names should not be put at the top of columns.
SwitchParameter
False
RangeName
Makes the data in the worksheet a named range.
String
String
None
TableName
Makes the data in the worksheet a table with a name, and applies a style to it. The name must not contain spaces. If the -Tablestyle parameter is specified without Tablename, "table1", "table2" etc. will be used.
Object
Object
None
TableStyle
Selects the style for the named table - if the Tablename parameter is specified without giving a style, 'Medium6' is used as a default.
None
Custom
Light1
Light2
Light3
Light4
Light5
Light6
Light7
Light8
Light9
Light10
Light11
Light12
Light13
Light14
Light15
Light16
Light17
Light18
Light19
Light20
Light21
Medium1
Medium2
Medium3
Medium4
Medium5
Medium6
Medium7
Medium8
Medium9
Medium10
Medium11
Medium12
Medium13
Medium14
Medium15
Medium16
Medium17
Medium18
Medium19
Medium20
Medium21
Medium22
Medium23
Medium24
Medium25
Medium26
Medium27
Medium28
Dark1
Dark2
Dark3
Dark4
Dark5
Dark6
Dark7
Dark8
Dark9
Dark10
Dark11
TableStyles
TableStyles
Medium6
Barchart
Creates a "quick" bar chart using the first text column as labels and the first numeric column as values.
SwitchParameter
False
PieChart
Creates a "quick" pie chart using the first text column as labels and the first numeric column as values.
SwitchParameter
False
LineChart
Creates a "quick" line chart using the first text column as labels and the first numeric column as values.
SwitchParameter
False
ColumnChart
Creates a "quick" column chart using the first text column as labels and the first numeric column as values.
SwitchParameter
False
ExcelChartDefinition
A hash-table containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-Pivot] charts. This can be created with the New-ExcelChartDefinition command.
Object[]
Object[]
None
HideSheet
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.
String[]
String[]
None
UnHideSheet
Name(s) of Sheet(s) to reveal in the workbook, supports wildcards.
String[]
String[]
None
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.
SwitchParameter
False
MoveToEnd
If specified, the worksheet will be moved to the end of the workbook. (This is the default position for newly created sheets, but the option can be specified to move existing sheets.)
SwitchParameter
False
MoveBefore
If specified, the worksheet will be moved before the nominated one (which can be a position starting from 1, or a name).
-MoveBefore takes precedence over -MoveAfter if both are specified.
Object
Object
None
MoveAfter
If specified, the worksheet will be moved after the nominated one (which can be a position starting from 1, or a name or *).
If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically.
Object
Object
None
KillExcel
Closes Excel without stopping to ask if work should be saved - prevents errors writing to the file because Excel has it open.
SwitchParameter
False
AutoNameRange
Makes each column a named range.
SwitchParameter
False
StartRow
Row to start adding data. 1 by default. Row 1 will contain the title, if any is specifed. Then headers will appear (Unless -No header is specified) then the data appears.
Int32
Int32
1
StartColumn
Column to start adding data - 1 by default.
Int32
Int32
1
PassThru
If specified, Export-Excel returns an object representing the Excel package without saving the package first. To save, you must either use the Close-ExcelPackage command, or send the package object back to Export-Excel which will save and close the file, or use the object's .Save() or SaveAs() method.
SwitchParameter
False
Numberformat
Formats all values that can be converted to a number to the format specified. For examples:
'0' integer (not really needed unless you need to round numbers, Excel will use default cell properties).
'#' integer without displaying the number 0 in the cell.
'0.0' number with 1 decimal place.
'0.00' number with 2 decimal places.
'#,##0.00' number with 2 decimal places and thousand-separator.
'€#,##0.00' number with 2 decimal places and thousand-separator and money-symbol.
'0%' number with 2 decimal places and thousand-separator and money-symbol.
'[Blue]$#,##0.00;[Red]-$#,##0.00'
blue for positive numbers and red for negative numbers; Both proceeded by a '$' sign
String
String
General
ExcludeProperty
Specifies properties which may exist in the target data but should not be placed on the worksheet.
String[]
String[]
None
NoAliasOrScriptPropeties
Some objects in PowerShell duplicate existing properties by adding aliases, or have Script properties which may take a long time to return a value and slow the export down, if specified this option removes these properties
SwitchParameter
False
DisplayPropertySet
Many (but not all) objects in PowerShell have a hidden property named psStandardmembers with a child property DefaultDisplayPropertySet ; this parameter reduces the properties exported to those in this set.
SwitchParameter
False
NoNumberConversion
By default the command will convert all values to numbers if possible, but this isn't always desirable. -NoNumberConversion allows you to add exceptions for the conversion.
The only Wildcard allowed is * for all properties
String[]
String[]
None
ConditionalFormat
One or more conditional formatting rules defined with New-ConditionalFormattingIconSet.
Object[]
Object[]
None
ConditionalText
Applies a Conditional formatting rule defined with New-ConditionalText. When specific conditions are met the format is applied.
Object[]
Object[]
None
Style
Takes style settings as a hash-table (which may be built with the New-ExcelStyle command) and applies them to the worksheet. If the hash-table contains a range the settings apply to the range, otherewise they apply to the whole sheet.
Object[]
Object[]
None
CellStyleSB
A script block which is run at the end of the export to apply styles to cells (although it can be used for other purposes). The script block is given three paramaters; an object containing the current worksheet, the Total number of Rows and the number of the last column.
ScriptBlock
ScriptBlock
None
Activate
If there is already content in the workbook, a new sheet will not be active UNLESS Activate is specified; when a PivotTable is created its sheet will be activated by this switch.
SwitchParameter
False
Now
The -Now switch is a shortcut that automatically creates a temporary file, enables "AutoSize", "TableName" and "Show", and opens the file immediately.
SwitchParameter
False
ReturnRange
If specified, Export-Excel returns the range of added cells in the format "A1:Z100".
SwitchParameter
False
PivotTotals
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.
String
String
Both
NoTotalsInPivot
In a PivotTable created from command line parameters, prevents the addition of totals to rows and columns.
SwitchParameter
False
ReZip
If specified, Export-Excel will expand the contents of the .XLSX file (which is multiple files in a zip archive) and rebuild it.
SwitchParameter
False
Export-Excel
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.
ExcelPackage
ExcelPackage
None
InputObject
Date is usually piped into Export-Excel, but it also accepts data through the InputObject parameter
Object
Object
None
Calculate
If specified, a recalculation of the worksheet will be requested before saving.
SwitchParameter
False
Show
Opens the Excel file immediately after creation; convenient for viewing the results instantly without having to search for the file first.
SwitchParameter
False
WorksheetName
The name of a sheet within the workbook - "Sheet1" by default.
String
String
Sheet1
Password
Sets password protection on the workbook.
String
String
None
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).
SwitchParameter
False
Append
If specified data will be added to the end of an existing sheet, using the same column headings.
SwitchParameter
False
Title
Text of a title to be placed in the top left cell.
String
String
None
TitleFillPattern
Sets the fill pattern for the title cell.
None
Solid
DarkGray
MediumGray
LightGray
Gray125
Gray0625
DarkVertical
DarkHorizontal
DarkDown
DarkUp
DarkGrid
DarkTrellis
LightVertical
LightHorizontal
LightDown
LightUp
LightGrid
LightTrellis
ExcelFillStyle
ExcelFillStyle
Solid
TitleBold
Sets the title in boldface type.
SwitchParameter
False
TitleSize
Sets the point size for the title.
Int32
Int32
22
TitleBackgroundColor
Sets the cell background color for the title cell.
Object
Object
None
IncludePivotTable
Adds a PivotTable using the data in the worksheet.
SwitchParameter
False
PivotTableName
If a PivotTable is created from command line parameters, specifies the name of the new sheet holding the pivot. Defaults to "WorksheetName-PivotTable".
String
String
None
PivotRows
Name(s) of column(s) from the spreadsheet which will provide the Row name(s) in a PivotTable created from command line parameters.
String[]
String[]
None
PivotColumns
Name(s) of columns from the spreadsheet which will provide the Column name(s) in a PivotTable created from command line parameters.
String[]
String[]
None
PivotData
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.
Object
Object
None
PivotFilter
Name(s) columns from the spreadsheet which will provide the Filter name(s) in a PivotTable created from command line parameters.
String[]
String[]
None
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.
SwitchParameter
False
PivotTableDefinition
Instead of describing a single PivotTable with multiple command-line parameters; you can use a HashTable in the form PivotTableName = Definition;
In this table Definition is itself a Hashtable with Sheet, PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values. The New-PivotTableDefinition command will create the definition from a command line.
Hashtable
Hashtable
None
IncludePivotChart
Include a chart with the PivotTable - implies -IncludePivotTable.
SwitchParameter
False
ChartType
The type for PivotChart (one of Excel's defined chart types).
Area
Line
Pie
Bubble
ColumnClustered
ColumnStacked
ColumnStacked100
ColumnClustered3D
ColumnStacked3D
ColumnStacked1003D
BarClustered
BarStacked
BarStacked100
BarClustered3D
BarStacked3D
BarStacked1003D
LineStacked
LineStacked100
LineMarkers
LineMarkersStacked
LineMarkersStacked100
PieOfPie
PieExploded
PieExploded3D
BarOfPie
XYScatterSmooth
XYScatterSmoothNoMarkers
XYScatterLines
XYScatterLinesNoMarkers
AreaStacked
AreaStacked100
AreaStacked3D
AreaStacked1003D
DoughnutExploded
RadarMarkers
RadarFilled
Surface
SurfaceWireframe
SurfaceTopView
SurfaceTopViewWireframe
Bubble3DEffect
StockHLC
StockOHLC
StockVHLC
StockVOHLC
CylinderColClustered
CylinderColStacked
CylinderColStacked100
CylinderBarClustered
CylinderBarStacked
CylinderBarStacked100
CylinderCol
ConeColClustered
ConeColStacked
ConeColStacked100
ConeBarClustered
ConeBarStacked
ConeBarStacked100
ConeCol
PyramidColClustered
PyramidColStacked
PyramidColStacked100
PyramidBarClustered
PyramidBarStacked
PyramidBarStacked100
PyramidCol
XYScatter
Radar
Doughnut
Pie3D
Line3D
Column3D
Area3D
eChartType
eChartType
Pie
NoLegend
Exclude the legend from the PivotChart.
SwitchParameter
False
ShowCategory
Add category labels to the PivotChart.
SwitchParameter
False
ShowPercent
Add percentage labels to the PivotChart.
SwitchParameter
False
AutoSize
Sizes the width of the Excel column to the maximum width needed to display all the containing data in that cell.
SwitchParameter
False
MaxAutoSizeRows
Autosizing can be time consuming, so this sets a maximum number of rows to look at for the Autosize operation. Default is 1000; If 0 is specified ALL rows will be checked
Object
Object
1000
NoClobber
Not used. Left in to avoid problems with older scripts, it may be removed in future versions.
SwitchParameter
False
FreezeTopRow
Freezes headers etc. in the top row.
SwitchParameter
False
FreezeFirstColumn
Freezes titles etc. in the left column.
SwitchParameter
False
FreezeTopRowFirstColumn
Freezes top row and left column (equivalent to Freeze pane 2,2 ).
SwitchParameter
False
FreezePane
Freezes panes at specified coordinates (in the form RowNumber, ColumnNumber).
Int32[]
Int32[]
None
AutoFilter
Enables the Excel filter on the complete header row, so users can easily sort, filter and/or search the data in the selected column.
SwitchParameter
False
BoldTopRow
Makes the top row boldface.
SwitchParameter
False
NoHeader
Specifies that field names should not be put at the top of columns.
SwitchParameter
False
RangeName
Makes the data in the worksheet a named range.
String
String
None
TableName
Makes the data in the worksheet a table with a name, and applies a style to it. The name must not contain spaces. If the -Tablestyle parameter is specified without Tablename, "table1", "table2" etc. will be used.
Object
Object
None
TableStyle
Selects the style for the named table - if the Tablename parameter is specified without giving a style, 'Medium6' is used as a default.
None
Custom
Light1
Light2
Light3
Light4
Light5
Light6
Light7
Light8
Light9
Light10
Light11
Light12
Light13
Light14
Light15
Light16
Light17
Light18
Light19
Light20
Light21
Medium1
Medium2
Medium3
Medium4
Medium5
Medium6
Medium7
Medium8
Medium9
Medium10
Medium11
Medium12
Medium13
Medium14
Medium15
Medium16
Medium17
Medium18
Medium19
Medium20
Medium21
Medium22
Medium23
Medium24
Medium25
Medium26
Medium27
Medium28
Dark1
Dark2
Dark3
Dark4
Dark5
Dark6
Dark7
Dark8
Dark9
Dark10
Dark11
TableStyles
TableStyles
Medium6
Barchart
Creates a "quick" bar chart using the first text column as labels and the first numeric column as values.
SwitchParameter
False
PieChart
Creates a "quick" pie chart using the first text column as labels and the first numeric column as values.
SwitchParameter
False
LineChart
Creates a "quick" line chart using the first text column as labels and the first numeric column as values.
SwitchParameter
False
ColumnChart
Creates a "quick" column chart using the first text column as labels and the first numeric column as values.
SwitchParameter
False
ExcelChartDefinition
A hash-table containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-Pivot] charts. This can be created with the New-ExcelChartDefinition command.
Object[]
Object[]
None
HideSheet
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.
String[]
String[]
None
UnHideSheet
Name(s) of Sheet(s) to reveal in the workbook, supports wildcards.
String[]
String[]
None
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.
SwitchParameter
False
MoveToEnd
If specified, the worksheet will be moved to the end of the workbook. (This is the default position for newly created sheets, but the option can be specified to move existing sheets.)
SwitchParameter
False
MoveBefore
If specified, the worksheet will be moved before the nominated one (which can be a position starting from 1, or a name).
-MoveBefore takes precedence over -MoveAfter if both are specified.
Object
Object
None
MoveAfter
If specified, the worksheet will be moved after the nominated one (which can be a position starting from 1, or a name or *).
If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically.
Object
Object
None
KillExcel
Closes Excel without stopping to ask if work should be saved - prevents errors writing to the file because Excel has it open.
SwitchParameter
False
AutoNameRange
Makes each column a named range.
SwitchParameter
False
StartRow
Row to start adding data. 1 by default. Row 1 will contain the title, if any is specifed. Then headers will appear (Unless -No header is specified) then the data appears.
Int32
Int32
1
StartColumn
Column to start adding data - 1 by default.
Int32
Int32
1
PassThru
If specified, Export-Excel returns an object representing the Excel package without saving the package first. To save, you must either use the Close-ExcelPackage command, or send the package object back to Export-Excel which will save and close the file, or use the object's .Save() or SaveAs() method.
SwitchParameter
False
Numberformat
Formats all values that can be converted to a number to the format specified. For examples:
'0' integer (not really needed unless you need to round numbers, Excel will use default cell properties).
'#' integer without displaying the number 0 in the cell.
'0.0' number with 1 decimal place.
'0.00' number with 2 decimal places.
'#,##0.00' number with 2 decimal places and thousand-separator.
'€#,##0.00' number with 2 decimal places and thousand-separator and money-symbol.
'0%' number with 2 decimal places and thousand-separator and money-symbol.
'[Blue]$#,##0.00;[Red]-$#,##0.00'
blue for positive numbers and red for negative numbers; Both proceeded by a '$' sign
String
String
General
ExcludeProperty
Specifies properties which may exist in the target data but should not be placed on the worksheet.
String[]
String[]
None
NoAliasOrScriptPropeties
Some objects in PowerShell duplicate existing properties by adding aliases, or have Script properties which may take a long time to return a value and slow the export down, if specified this option removes these properties
SwitchParameter
False
DisplayPropertySet
Many (but not all) objects in PowerShell have a hidden property named psStandardmembers with a child property DefaultDisplayPropertySet ; this parameter reduces the properties exported to those in this set.
SwitchParameter
False
NoNumberConversion
By default the command will convert all values to numbers if possible, but this isn't always desirable. -NoNumberConversion allows you to add exceptions for the conversion.
The only Wildcard allowed is * for all properties
String[]
String[]
None
ConditionalFormat
One or more conditional formatting rules defined with New-ConditionalFormattingIconSet.
Object[]
Object[]
None
ConditionalText
Applies a Conditional formatting rule defined with New-ConditionalText. When specific conditions are met the format is applied.
Object[]
Object[]
None
Style
Takes style settings as a hash-table (which may be built with the New-ExcelStyle command) and applies them to the worksheet. If the hash-table contains a range the settings apply to the range, otherewise they apply to the whole sheet.
Object[]
Object[]
None
CellStyleSB
A script block which is run at the end of the export to apply styles to cells (although it can be used for other purposes). The script block is given three paramaters; an object containing the current worksheet, the Total number of Rows and the number of the last column.
ScriptBlock
ScriptBlock
None
Activate
If there is already content in the workbook, a new sheet will not be active UNLESS Activate is specified; when a PivotTable is created its sheet will be activated by this switch.
SwitchParameter
False
ReturnRange
If specified, Export-Excel returns the range of added cells in the format "A1:Z100".
SwitchParameter
False
PivotTotals
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.
String
String
Both
NoTotalsInPivot
In a PivotTable created from command line parameters, prevents the addition of totals to rows and columns.
SwitchParameter
False
ReZip
If specified, Export-Excel will expand the contents of the .XLSX file (which is multiple files in a zip archive) and rebuild it.
SwitchParameter
False
Path
Path to a new or existing .XLSX file.
String
String
None
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.
ExcelPackage
ExcelPackage
None
InputObject
Date is usually piped into Export-Excel, but it also accepts data through the InputObject parameter
Object
Object
None
Calculate
If specified, a recalculation of the worksheet will be requested before saving.
SwitchParameter
SwitchParameter
False
Show
Opens the Excel file immediately after creation; convenient for viewing the results instantly without having to search for the file first.
SwitchParameter
SwitchParameter
False
WorksheetName
The name of a sheet within the workbook - "Sheet1" by default.
String
String
Sheet1
Password
Sets password protection on the workbook.
String
String
None
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).
SwitchParameter
SwitchParameter
False
Append
If specified data will be added to the end of an existing sheet, using the same column headings.
SwitchParameter
SwitchParameter
False
Title
Text of a title to be placed in the top left cell.
String
String
None
TitleFillPattern
Sets the fill pattern for the title cell.
ExcelFillStyle
ExcelFillStyle
Solid
TitleBold
Sets the title in boldface type.
SwitchParameter
SwitchParameter
False
TitleSize
Sets the point size for the title.
Int32
Int32
22
TitleBackgroundColor
Sets the cell background color for the title cell.
Object
Object
None
IncludePivotTable
Adds a PivotTable using the data in the worksheet.
SwitchParameter
SwitchParameter
False
PivotTableName
If a PivotTable is created from command line parameters, specifies the name of the new sheet holding the pivot. Defaults to "WorksheetName-PivotTable".
String
String
None
PivotRows
Name(s) of column(s) from the spreadsheet which will provide the Row name(s) in a PivotTable created from command line parameters.
String[]
String[]
None
PivotColumns
Name(s) of columns from the spreadsheet which will provide the Column name(s) in a PivotTable created from command line parameters.
String[]
String[]
None
PivotData
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.
Object
Object
None
PivotFilter
Name(s) columns from the spreadsheet which will provide the Filter name(s) in a PivotTable created from command line parameters.
String[]
String[]
None
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.
SwitchParameter
SwitchParameter
False
PivotTableDefinition
Instead of describing a single PivotTable with multiple command-line parameters; you can use a HashTable in the form PivotTableName = Definition;
In this table Definition is itself a Hashtable with Sheet, PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values. The New-PivotTableDefinition command will create the definition from a command line.
Hashtable
Hashtable
None
IncludePivotChart
Include a chart with the PivotTable - implies -IncludePivotTable.
SwitchParameter
SwitchParameter
False
ChartType
The type for PivotChart (one of Excel's defined chart types).
eChartType
eChartType
Pie
NoLegend
Exclude the legend from the PivotChart.
SwitchParameter
SwitchParameter
False
ShowCategory
Add category labels to the PivotChart.
SwitchParameter
SwitchParameter
False
ShowPercent
Add percentage labels to the PivotChart.
SwitchParameter
SwitchParameter
False
AutoSize
Sizes the width of the Excel column to the maximum width needed to display all the containing data in that cell.
SwitchParameter
SwitchParameter
False
MaxAutoSizeRows
Autosizing can be time consuming, so this sets a maximum number of rows to look at for the Autosize operation. Default is 1000; If 0 is specified ALL rows will be checked
Object
Object
1000
NoClobber
Not used. Left in to avoid problems with older scripts, it may be removed in future versions.
SwitchParameter
SwitchParameter
False
FreezeTopRow
Freezes headers etc. in the top row.
SwitchParameter
SwitchParameter
False
FreezeFirstColumn
Freezes titles etc. in the left column.
SwitchParameter
SwitchParameter
False
FreezeTopRowFirstColumn
Freezes top row and left column (equivalent to Freeze pane 2,2 ).
SwitchParameter
SwitchParameter
False
FreezePane
Freezes panes at specified coordinates (in the form RowNumber, ColumnNumber).
Int32[]
Int32[]
None
AutoFilter
Enables the Excel filter on the complete header row, so users can easily sort, filter and/or search the data in the selected column.
SwitchParameter
SwitchParameter
False
BoldTopRow
Makes the top row boldface.
SwitchParameter
SwitchParameter
False
NoHeader
Specifies that field names should not be put at the top of columns.
SwitchParameter
SwitchParameter
False
RangeName
Makes the data in the worksheet a named range.
String
String
None
TableName
Makes the data in the worksheet a table with a name, and applies a style to it. The name must not contain spaces. If the -Tablestyle parameter is specified without Tablename, "table1", "table2" etc. will be used.
Object
Object
None
TableStyle
Selects the style for the named table - if the Tablename parameter is specified without giving a style, 'Medium6' is used as a default.
TableStyles
TableStyles
Medium6
Barchart
Creates a "quick" bar chart using the first text column as labels and the first numeric column as values.
SwitchParameter
SwitchParameter
False
PieChart
Creates a "quick" pie chart using the first text column as labels and the first numeric column as values.
SwitchParameter
SwitchParameter
False
LineChart
Creates a "quick" line chart using the first text column as labels and the first numeric column as values.
SwitchParameter
SwitchParameter
False
ColumnChart
Creates a "quick" column chart using the first text column as labels and the first numeric column as values.
SwitchParameter
SwitchParameter
False
ExcelChartDefinition
A hash-table containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-Pivot] charts. This can be created with the New-ExcelChartDefinition command.
Object[]
Object[]
None
HideSheet
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.
String[]
String[]
None
UnHideSheet
Name(s) of Sheet(s) to reveal in the workbook, supports wildcards.
String[]
String[]
None
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.
SwitchParameter
SwitchParameter
False
MoveToEnd
If specified, the worksheet will be moved to the end of the workbook. (This is the default position for newly created sheets, but the option can be specified to move existing sheets.)
SwitchParameter
SwitchParameter
False
MoveBefore
If specified, the worksheet will be moved before the nominated one (which can be a position starting from 1, or a name).
-MoveBefore takes precedence over -MoveAfter if both are specified.
Object
Object
None
MoveAfter
If specified, the worksheet will be moved after the nominated one (which can be a position starting from 1, or a name or *).
If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically.
Object
Object
None
KillExcel
Closes Excel without stopping to ask if work should be saved - prevents errors writing to the file because Excel has it open.
SwitchParameter
SwitchParameter
False
AutoNameRange
Makes each column a named range.
SwitchParameter
SwitchParameter
False
StartRow
Row to start adding data. 1 by default. Row 1 will contain the title, if any is specifed. Then headers will appear (Unless -No header is specified) then the data appears.
Int32
Int32
1
StartColumn
Column to start adding data - 1 by default.
Int32
Int32
1
PassThru
If specified, Export-Excel returns an object representing the Excel package without saving the package first. To save, you must either use the Close-ExcelPackage command, or send the package object back to Export-Excel which will save and close the file, or use the object's .Save() or SaveAs() method.
SwitchParameter
SwitchParameter
False
Numberformat
Formats all values that can be converted to a number to the format specified. For examples:
'0' integer (not really needed unless you need to round numbers, Excel will use default cell properties).
'#' integer without displaying the number 0 in the cell.
'0.0' number with 1 decimal place.
'0.00' number with 2 decimal places.
'#,##0.00' number with 2 decimal places and thousand-separator.
'€#,##0.00' number with 2 decimal places and thousand-separator and money-symbol.
'0%' number with 2 decimal places and thousand-separator and money-symbol.
'[Blue]$#,##0.00;[Red]-$#,##0.00'
blue for positive numbers and red for negative numbers; Both proceeded by a '$' sign
String
String
General
ExcludeProperty
Specifies properties which may exist in the target data but should not be placed on the worksheet.
String[]
String[]
None
NoAliasOrScriptPropeties
Some objects in PowerShell duplicate existing properties by adding aliases, or have Script properties which may take a long time to return a value and slow the export down, if specified this option removes these properties
SwitchParameter
SwitchParameter
False
DisplayPropertySet
Many (but not all) objects in PowerShell have a hidden property named psStandardmembers with a child property DefaultDisplayPropertySet ; this parameter reduces the properties exported to those in this set.
SwitchParameter
SwitchParameter
False
NoNumberConversion
By default the command will convert all values to numbers if possible, but this isn't always desirable. -NoNumberConversion allows you to add exceptions for the conversion.
The only Wildcard allowed is * for all properties
String[]
String[]
None
ConditionalFormat
One or more conditional formatting rules defined with New-ConditionalFormattingIconSet.
Object[]
Object[]
None
ConditionalText
Applies a Conditional formatting rule defined with New-ConditionalText. When specific conditions are met the format is applied.
Object[]
Object[]
None
Style
Takes style settings as a hash-table (which may be built with the New-ExcelStyle command) and applies them to the worksheet. If the hash-table contains a range the settings apply to the range, otherewise they apply to the whole sheet.
Object[]
Object[]
None
CellStyleSB
A script block which is run at the end of the export to apply styles to cells (although it can be used for other purposes). The script block is given three paramaters; an object containing the current worksheet, the Total number of Rows and the number of the last column.
ScriptBlock
ScriptBlock
None
Activate
If there is already content in the workbook, a new sheet will not be active UNLESS Activate is specified; when a PivotTable is created its sheet will be activated by this switch.
SwitchParameter
SwitchParameter
False
Now
The -Now switch is a shortcut that automatically creates a temporary file, enables "AutoSize", "TableName" and "Show", and opens the file immediately.
SwitchParameter
SwitchParameter
False
ReturnRange
If specified, Export-Excel returns the range of added cells in the format "A1:Z100".
SwitchParameter
SwitchParameter
False
PivotTotals
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.
String
String
Both
NoTotalsInPivot
In a PivotTable created from command line parameters, prevents the addition of totals to rows and columns.
SwitchParameter
SwitchParameter
False
ReZip
If specified, Export-Excel will expand the contents of the .XLSX file (which is multiple files in a zip archive) and rebuild it.
SwitchParameter
SwitchParameter
False
OfficeOpenXml.ExcelPackage
-------------------------- EXAMPLE 1 --------------------------
PS\> Get-Process | Export-Excel .\Test.xlsx -show
Export all the processes to the Excel file 'Test.xlsx' and open the file immediately.
-------------------------- EXAMPLE 2 --------------------------
PS\> $ExcelParams = @{
Path = $env:TEMP + '\Excel.xlsx'
Show = $true
Verbose = $true
}
PS\> Remove-Item -Path $ExcelParams.Path -Force -EA Ignore
PS\> 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 numbers which use a thousand seperator and display to two decimal places.
-------------------------- EXAMPLE 3 --------------------------
PS\> $ExcelParams = @{
Path = $env:TEMP + '\Excel.xlsx'
Show = $true
Verbose = $true
}
PS\> Remove-Item -Path $ExcelParams.Path -Force -EA Ignore
PS\> [PSCustOmobject][Ordered]@{
Date = Get-Date
Formula1 = '=SUM(F2:G2)'
String1 = 'My String'
String2 = 'a'
IPAddress = '10.10.25.5'
Number1 = '07670'
Number2 = '0,26'
Number3 = '1.555,83'
Number4 = '1.2'
Number5 = '-31'
PhoneNr1 = '+32 44'
PhoneNr2 = '+32 4 4444 444'
PhoneNr3 = '+3244444444'
} | Export-Excel @ExcelParams -NoNumberConversion IPAddress, Number1
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 4 --------------------------
PS\> $ExcelParams = @{
Path = $env:TEMP + '\Excel.xlsx'
Show = $true
Verbose = $true
}
PS\> Remove-Item -Path $ExcelParams.Path -Force -EA Ignore
PS\> [PSCustOmobject][Ordered]@{
Date = Get-Date
Formula1 = '=SUM(F2:G2)'
String1 = 'My String'
String2 = 'a'
IPAddress = '10.10.25.5'
Number1 = '07670'
Number2 = '0,26'
Number3 = '1.555,83'
Number4 = '1.2'
Number5 = '-31'
PhoneNr1 = '+32 44'
PhoneNr2 = '+32 4 4444 444'
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.
-------------------------- EXAMPLE 5 --------------------------
PS\> $ExcelParams = @{
Path = $env:TEMP + '\Excel.xlsx'
Show = $true
Verbose = $true
}
PS\> Remove-Item -Path $ExcelParams.Path -Force -EA Ignore
PS\> Write-Output 489 668 299 777 860 151 119 497 234 788 |
Export-Excel @ExcelParams -ConditionalText $(
New-ConditionalText -ConditionalType GreaterThan 525 -ConditionalTextColor DarkRed -BackgroundColor LightPink
)
Exports data that will have a Conditional Formatting rule in Excel that will show cells with a value is greater than 525, with a background fill color of "LightPink" and the text in "DarkRed".
Where the condition is not met the color will be the default, black text on a white background.
-------------------------- EXAMPLE 6 --------------------------
PS\> $ExcelParams = @{
Path = $env:TEMP + '\Excel.xlsx'
Show = $true
Verbose = $true
}
PS\> Remove-Item -Path $ExcelParams.Path -Force -EA Ignore
PS\> Get-Service | Select-Object -Property Name, Status, DisplayName, ServiceName |
Export-Excel @ExcelParams -ConditionalText $(
New-ConditionalText Stop DarkRed LightPink
New-ConditionalText Running Blue Cyan
)
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 7 --------------------------
PS\> $ExcelParams = @{
Path = $env:TEMP + '\Excel.xlsx'
Show = $true
Verbose = $true
}
PS\> Remove-Item -Path $ExcelParams.Path -Force -EA Ignore
PS\> $Array = @()
PS\> $Obj1 = [PSCustomObject]@{
Member1 = 'First'
Member2 = 'Second'
}
PS\> $Obj2 = [PSCustomObject]@{
Member1 = 'First'
Member2 = 'Second'
Member3 = 'Third'
}
PS\> $Obj3 = [PSCustomObject]@{
Member1 = 'First'
Member2 = 'Second'
Member3 = 'Third'
Member4 = 'Fourth'
}
PS\> $Array = $Obj1, $Obj2, $Obj3
PS\> $Array | Out-GridView -Title 'Not showing Member3 and Member4'
PS\> $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.
-------------------------- EXAMPLE 8 --------------------------
PS\> Get-Process | Export-Excel .\test.xlsx -WorksheetName Processes -IncludePivotTable -Show -PivotRows Company -PivotData PM
-------------------------- EXAMPLE 9 --------------------------
PS\> Get-Process | Export-Excel .\test.xlsx -WorksheetName Processes -ChartType PieExploded3D -IncludePivotChart -IncludePivotTable -Show -PivotRows Company -PivotData PM
-------------------------- EXAMPLE 10 --------------------------
PS\> Get-Service | Export-Excel 'c:\temp\test.xlsx' -Show -IncludePivotTable -PivotRows status -PivotData @{status='count'}
-------------------------- EXAMPLE 11 --------------------------
PS\> $pt = [ordered]@{}
PS\> $pt.pt1=@{
SourceWorkSheet = 'Sheet1';
PivotRows = 'Status'
PivotData = @{'Status'='count'}
IncludePivotChart = $true
ChartType = 'BarClustered3D'
}
PS\> $pt.pt2=@
SourceWorkSheet = 'Sheet2';
PivotRows = 'Company'
PivotData = @{'Company'='count'}
IncludePivotChart = $true
ChartType = 'PieExploded3D'
}
PS\> Remove-Item -Path .\test.xlsx
PS\> Get-Service | Select-Object -Property Status,Name,DisplayName,StartType | Export-Excel -Path .\test.xlsx -AutoSize
PS\> Get-Process | Select-Object -Property Name,Company,Handles,CPU,VM | Export-Excel -Path .\test.xlsx -AutoSize -WorksheetName 'sheet2'
PS\> Export-Excel -Path .\test.xlsx -PivotTableDefinition $pt -Show
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 12 --------------------------
PS\> Remove-Item -Path .\test.xlsx
PS\> $excel = Get-Service | Select-Object -Property Status,Name,DisplayName,StartType | Export-Excel -Path .\test.xlsx -PassThru
PS\> $excel.Workbook.Worksheets ["Sheet1"].Row(1).style.font.bold = $true
PS\> $excel.Workbook.Worksheets ["Sheet1"].Column(3 ).width = 29
PS\> $excel.Workbook.Worksheets ["Sheet1"].Column(3 ).Style.wraptext = $true
PS\> $excel.Save()
PS\> $excel.Dispose()
PS\> Start-Process .\test.xlsx
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.
Note: Other commands in the module remove the need to work directly with the package object in this way.
-------------------------- EXAMPLE 13 --------------------------
PS\> Remove-Item -Path .\test.xlsx -ErrorAction Ignore
PS\> $excel = Get-Process | Select-Object -Property Name,Company,Handles,CPU,PM,NPM,WS |
Export-Excel -Path .\test.xlsx -ClearSheet -WorksheetName "Processes" -PassThru
PS\> $sheet = $excel.Workbook.Worksheets ["Processes"]
PS\> $sheet.Column(1) | Set-ExcelRange -Bold -AutoFit
PS\> $sheet.Column(2) | Set-ExcelRange -Width 29 -WrapText
PS\> $sheet.Column(3) | Set-ExcelRange -HorizontalAlignment Right -NFormat "#,###"
PS\> Set-ExcelRange -Address $sheet.Cells ["E1:H1048576"] -HorizontalAlignment Right -NFormat "#,###"
PS\> Set-ExcelRange -Address $sheet.Column(4) -HorizontalAlignment Right -NFormat "#,##0.0" -Bold
PS\> Set-ExcelRange -Address $sheet.Row(1) -Bold -HorizontalAlignment Center
PS\> Add-ConditionalFormatting -WorkSheet $sheet -Range "D2:D1048576" -DataBarColor Red
PS\> Add-ConditionalFormatting -WorkSheet $sheet -Range "G2:G1048576" -RuleType GreaterThan -ConditionValue "104857600" -ForeGroundColor Red
PS\> foreach ($c in 5..9) {Set-ExcelRange -Address $sheet.Column($c) -AutoFit }
PS\> 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 PivotChart is added and the workbook is opened in Excel.
-------------------------- EXAMPLE 14 --------------------------
PS\> 0..360 | ForEach-Object {[pscustomobject][ordered]@{X=$_; Sinx="=Sin(Radians(x)) "} } |
Export-Excel -now -LineChart -AutoNameRange
Creates a line chart showing the value of Sine(x) for values of X between 0 and 360 degrees.
-------------------------- EXAMPLE 15 --------------------------
PS\> Invoke-Sqlcmd -ServerInstance localhost\DEFAULT -Database AdventureWorks2014 -Query "select * from sys.tables" -OutputAs DataRows |
Export-Excel -Path .\SysTables_AdventureWorks2014.xlsx -WorksheetName Tables
Runs a query against a SQL Server database and outputs the resulting rows as DataRows using the -OutputAs parameter. The results are then piped to the Export-Excel function.
NOTE: You need to install the SqlServer module from the PowerShell Gallery in order to get the -OutputAs parameter for the Invoke-Sqlcmd cmdlet.
https://github.com/dfinke/ImportExcel
https://github.com/dfinke/ImportExcel
Get-ExcelSheetInfo
Get
ExcelSheetInfo
Get worksheet names and their indices of an Excel workbook.
The Get-ExcelSheetInfo cmdlet gets worksheet names and their indices of an Excel workbook.
Get-ExcelSheetInfo
Path
Specifies the path to the Excel file. (This parameter is required.)
Object
Object
None
Path
Specifies the path to the Excel file. (This parameter is required.)
Object
Object
None
CHANGELOG 2016/01/07 Added Created by Johan Akerstrom (https://github.com/CosmosKey)
-------------------------- EXAMPLE 1 --------------------------
Get-ExcelSheetInfo .\Test.xlsx
https://github.com/dfinke/ImportExcel
https://github.com/dfinke/ImportExcel
Get-ExcelWorkbookInfo
Get
ExcelWorkbookInfo
Retrieve information of an Excel workbook.
The Get-ExcelWorkbookInfo cmdlet retrieves information (LastModifiedBy, LastPrinted, Created, Modified, ...) fron an Excel workbook. These are the same details that are visible in Windows Explorer when right clicking the Excel file, selecting Properties and check the Details tabpage.
Get-ExcelWorkbookInfo
Path
Specifies the path to the Excel file. This parameter is required.
String
String
None
Path
Specifies the path to the Excel file. This parameter is required.
String
String
None
CHANGELOG 2016/01/07 Added Created by Johan Akerstrom (https://github.com/CosmosKey)
-------------------------- EXAMPLE 1 --------------------------
Get-ExcelWorkbookInfo .\Test.xlsx
CorePropertiesXml : #document Title : Subject : Author : Konica Minolta User Comments : Keywords : LastModifiedBy : Bond, James (London) GBR LastPrinted : 2017-01-21T12:36:11Z Created : 17/01/2017 13:51:32 Category : Status : ExtendedPropertiesXml : #document Application : Microsoft Excel HyperlinkBase : AppVersion : 14.0300 Company : Secret Service Manager : Modified : 10/02/2017 12:45:37 CustomPropertiesXml : #document
https://github.com/dfinke/ImportExcel
https://github.com/dfinke/ImportExcel
Import-Excel
Import
Excel
Create custom objects from the rows in an Excel worksheet.
The Import-Excel cmdlet creates custom objects from the rows in an Excel worksheet. Each row is represented as one object.
This is possible without installing Microsoft Excel by using the .NET library 'EPPLus.dll'.
By default, the property names of the objects are retrieved from the column headers. Because an object cannot have a blank property name, only columns with column headers will be imported.
If the default behavior is not desired and you want to import the complete worksheet 'as is', the parameter '-NoHeader' can be used. In case you want to provide your own property names, you can use the parameter '-HeaderName'.
Import-Excel
Path
Specifies the path to the Excel file.
String
String
None
WorksheetName
Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported.
String
String
None
NoHeader
Automatically generate property names (P1, P2, P3, ..) instead of the ones defined in the column headers of the TopRow.
This switch is best used when you want to import the complete worksheet 'as is' and are not concerned with the property names.
SwitchParameter
False
StartRow
The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row.
When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. If either is provided, the property names are automatically created and this row will be treated as a regular row containing data.
Int32
Int32
1
EndRow
By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row.
Int32
Int32
0
StartColumn
The number of the first column to read data from (1 by default).
Int32
Int32
1
EndColumn
By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number.
Int32
Int32
0
DataOnly
Import only rows and columns that contain data, empty rows and empty columns are not imported.
SwitchParameter
False
AsText
Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. (* is supported as a wildcard.)
String[]
String[]
None
AsDate
Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.)
String[]
String[]
None
Password
Accepts a string that will be used to open a password protected Excel file.
String
String
None
Import-Excel
Path
Specifies the path to the Excel file.
String
String
None
WorksheetName
Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported.
String
String
None
HeaderName
Specifies custom property names to use, instead of the values defined in the column headers of the TopRow.
If you provide fewer header names than there are columns of data in the worksheet, then data will only be imported from that number of columns - the others will be ignored.
If you provide more header names than there are columns of data in the worksheet, it will result in blank properties being added to the objects returned.
String[]
String[]
None
StartRow
The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row.
When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. If either is provided, the property names are automatically created and this row will be treated as a regular row containing data.
Int32
Int32
1
EndRow
By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row.
Int32
Int32
0
StartColumn
The number of the first column to read data from (1 by default).
Int32
Int32
1
EndColumn
By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number.
Int32
Int32
0
DataOnly
Import only rows and columns that contain data, empty rows and empty columns are not imported.
SwitchParameter
False
AsText
Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. (* is supported as a wildcard.)
String[]
String[]
None
AsDate
Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.)
String[]
String[]
None
Password
Accepts a string that will be used to open a password protected Excel file.
String
String
None
Import-Excel
Path
Specifies the path to the Excel file.
String
String
None
WorksheetName
Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported.
String
String
None
StartRow
The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row.
When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. If either is provided, the property names are automatically created and this row will be treated as a regular row containing data.
Int32
Int32
1
EndRow
By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row.
Int32
Int32
0
StartColumn
The number of the first column to read data from (1 by default).
Int32
Int32
1
EndColumn
By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number.
Int32
Int32
0
DataOnly
Import only rows and columns that contain data, empty rows and empty columns are not imported.
SwitchParameter
False
AsText
Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. (* is supported as a wildcard.)
String[]
String[]
None
AsDate
Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.)
String[]
String[]
None
Password
Accepts a string that will be used to open a password protected Excel file.
String
String
None
Import-Excel
WorksheetName
Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported.
String
String
None
ExcelPackage
Instead of specifying a path, provides an Excel Package object (from Open-ExcelPackage). Using this avoids re-reading the whole file when importing multiple parts of it.
To allow multiple read operations Import-Excel does NOT close the package, and you should use Close-ExcelPackage -noSave to close it.
ExcelPackage
ExcelPackage
None
NoHeader
Automatically generate property names (P1, P2, P3, ..) instead of the ones defined in the column headers of the TopRow.
This switch is best used when you want to import the complete worksheet 'as is' and are not concerned with the property names.
SwitchParameter
False
StartRow
The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row.
When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. If either is provided, the property names are automatically created and this row will be treated as a regular row containing data.
Int32
Int32
1
EndRow
By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row.
Int32
Int32
0
StartColumn
The number of the first column to read data from (1 by default).
Int32
Int32
1
EndColumn
By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number.
Int32
Int32
0
DataOnly
Import only rows and columns that contain data, empty rows and empty columns are not imported.
SwitchParameter
False
AsText
Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. (* is supported as a wildcard.)
String[]
String[]
None
AsDate
Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.)
String[]
String[]
None
Password
Accepts a string that will be used to open a password protected Excel file.
String
String
None
Import-Excel
WorksheetName
Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported.
String
String
None
ExcelPackage
Instead of specifying a path, provides an Excel Package object (from Open-ExcelPackage). Using this avoids re-reading the whole file when importing multiple parts of it.
To allow multiple read operations Import-Excel does NOT close the package, and you should use Close-ExcelPackage -noSave to close it.
ExcelPackage
ExcelPackage
None
HeaderName
Specifies custom property names to use, instead of the values defined in the column headers of the TopRow.
If you provide fewer header names than there are columns of data in the worksheet, then data will only be imported from that number of columns - the others will be ignored.
If you provide more header names than there are columns of data in the worksheet, it will result in blank properties being added to the objects returned.
String[]
String[]
None
StartRow
The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row.
When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. If either is provided, the property names are automatically created and this row will be treated as a regular row containing data.
Int32
Int32
1
EndRow
By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row.
Int32
Int32
0
StartColumn
The number of the first column to read data from (1 by default).
Int32
Int32
1
EndColumn
By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number.
Int32
Int32
0
DataOnly
Import only rows and columns that contain data, empty rows and empty columns are not imported.
SwitchParameter
False
AsText
Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. (* is supported as a wildcard.)
String[]
String[]
None
AsDate
Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.)
String[]
String[]
None
Password
Accepts a string that will be used to open a password protected Excel file.
String
String
None
Import-Excel
WorksheetName
Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported.
String
String
None
ExcelPackage
Instead of specifying a path, provides an Excel Package object (from Open-ExcelPackage). Using this avoids re-reading the whole file when importing multiple parts of it.
To allow multiple read operations Import-Excel does NOT close the package, and you should use Close-ExcelPackage -noSave to close it.
ExcelPackage
ExcelPackage
None
StartRow
The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row.
When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. If either is provided, the property names are automatically created and this row will be treated as a regular row containing data.
Int32
Int32
1
EndRow
By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row.
Int32
Int32
0
StartColumn
The number of the first column to read data from (1 by default).
Int32
Int32
1
EndColumn
By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number.
Int32
Int32
0
DataOnly
Import only rows and columns that contain data, empty rows and empty columns are not imported.
SwitchParameter
False
AsText
Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. (* is supported as a wildcard.)
String[]
String[]
None
AsDate
Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.)
String[]
String[]
None
Password
Accepts a string that will be used to open a password protected Excel file.
String
String
None
Path
Specifies the path to the Excel file.
String
String
None
ExcelPackage
Instead of specifying a path, provides an Excel Package object (from Open-ExcelPackage). Using this avoids re-reading the whole file when importing multiple parts of it.
To allow multiple read operations Import-Excel does NOT close the package, and you should use Close-ExcelPackage -noSave to close it.
ExcelPackage
ExcelPackage
None
WorksheetName
Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported.
String
String
None
HeaderName
Specifies custom property names to use, instead of the values defined in the column headers of the TopRow.
If you provide fewer header names than there are columns of data in the worksheet, then data will only be imported from that number of columns - the others will be ignored.
If you provide more header names than there are columns of data in the worksheet, it will result in blank properties being added to the objects returned.
String[]
String[]
None
NoHeader
Automatically generate property names (P1, P2, P3, ..) instead of the ones defined in the column headers of the TopRow.
This switch is best used when you want to import the complete worksheet 'as is' and are not concerned with the property names.
SwitchParameter
SwitchParameter
False
StartRow
The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row.
When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. If either is provided, the property names are automatically created and this row will be treated as a regular row containing data.
Int32
Int32
1
EndRow
By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row.
Int32
Int32
0
StartColumn
The number of the first column to read data from (1 by default).
Int32
Int32
1
EndColumn
By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number.
Int32
Int32
0
DataOnly
Import only rows and columns that contain data, empty rows and empty columns are not imported.
SwitchParameter
SwitchParameter
False
AsText
Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. (* is supported as a wildcard.)
String[]
String[]
None
AsDate
Not all date formats are recognized as indicating the number in the cell represents a date AsDate forces the number which would be returned to be converted to a date. (* is supported as a wildcard.)
String[]
String[]
None
Password
Accepts a string that will be used to open a password protected Excel file.
String
String
None
-------------------------- EXAMPLE 1 --------------------------
----------------------------------------------
| File: Movies.xlsx - Sheet: Actors |
----------------------------------------------
| A B C |
|1 First Name Address |
|2 Chuck Norris California |
|3 Jean-Claude Vandamme Brussels |
----------------------------------------------
PS C:> Import-Excel -Path 'C:\Movies.xlsx' -WorkSheetname Actors
First Name: Chuck
Address : California
First Name: Jean-Claude
Address : Brussels
Import data from an Excel worksheet. One object is created for each row. The property names of the objects consist of the column names defined in the first row. In case a column doesn't have a column header (usually in row 1 when '-StartRow' is not used), then the unnamed columns will be skipped and the data in those columns will not be imported.
Notice that column 'B' is not imported because there's no value in cell 'B1' that can be used as property name for the objects.
-------------------------- EXAMPLE 2 --------------------------
----------------------------------------------
| File: Movies.xlsx - Sheet: Actors |
----------------------------------------------
| A B C |
|1 First Name Address |
|2 Chuck Norris California |
|3 Jean-Claude Vandamme Brussels |
----------------------------------------------
PS\> Import-Excel -Path 'C:\Movies.xlsx' -WorkSheetname Actors -NoHeader
P1: First Name
P2:
P3: Address
P1: Chuck
P2: Norris
P3: California
P1: Jean-Claude
P2: Vandamme
P3: Brussels
Imports the complete Excel worksheet 'as is' by using the '-NoHeader' switch. One object is created for each row. The property names of the objects will be automatically generated (P1, P2, P3, ..).
Notice that the column header (row 1) is imported as an object too.
-------------------------- EXAMPLE 3 --------------------------
----------------------------------------------------------
| File: Movies.xlsx - Sheet: Movies |
----------------------------------------------------------
| A B C D |
|1 The Bodyguard 1992 9 |
|2 The Matrix 1999 8 |
|3 |
|4 Skyfall 2012 9 |
----------------------------------------------------------
PS\> Import-Excel -Path 'C:\Movies.xlsx' -WorkSheetname Movies -HeaderName 'Movie name', 'Year', 'Rating', 'Genre'
Movie name: The Bodyguard
Year : 1992
Rating : 9
Genre :
Movie name: The Matrix
Year : 1999
Rating : 8
Genre :
Movie name:
Year :
Rating :
Genre :
Movie name: Skyfall
Year : 2012
Rating : 9
Genre :
This imports data from an Excel worksheet, and as before one object is created for each row. The property names for the objects are defined in the parameter '-HeaderName'. The properties are named starting from the most left column (A) to the right. In case no value is present in one of the columns, that property will have an empty value.
Notice that empty rows are imported and that data for the property 'Genre' is not present in the worksheet. As such, the 'Genre' property will be blank for all objects.
-------------------------- EXAMPLE 4 --------------------------
----------------------------------------------------------
| File: Movies.xlsx - Sheet: Movies |
----------------------------------------------------------
| A B C D |
|1 The Bodyguard 1992 9 |
|2 The Matrix 1999 8 |
|3 |
|4 Skyfall 2012 9 |
----------------------------------------------------------
PS\> Import-Excel -Path 'C:\Movies.xlsx' -WorkSheetname Movies -NoHeader -DataOnly
P1: The Bodyguard
P2: 1992
P3: 9
P1: The Matrix
P2: 1999
P3: 8
P1: Skyfall
P2: 2012
P3: 9
Import data from an Excel worksheet, and one object is created for each non-blank row. The property names of the objects (P1, P2, P3, ..) are automatically generated by using the switch '-NoHeader' . The switch '-DataOnly' will speed up the import because empty rows and empty columns are not imported.
Notice that empty rows and empty columns are not imported.
-------------------------- EXAMPLE 5 --------------------------
----------------------------------------------------------
| File: Movies.xlsx - Sheet: Actors |
----------------------------------------------------------
| A B C D |
|1 Chuck Norris California |
|2 |
|3 Jean-Claude Vandamme Brussels |
----------------------------------------------------------
PS\> Import-Excel -Path 'C:\Movies.xlsx' -WorkSheetname Actors -DataOnly -HeaderName 'FirstName', 'SecondName', 'City' -StartRow 2
FirstName : Jean-Claude
SecondName: Vandamme
City : Brussels
Import data from an Excel worksheet. One object is created for each row. The property names are provided with the '-HeaderName' parameter. The import will start from row 2 and empty columns and rows are not imported.
Notice that only 1 object is imported with only 3 properties. Column B and row 2 are empty and have been disregarded by using the switch '-DataOnly'. The property names have been named with the values provided with the parameter '-HeaderName'. Row number 1 with 'Chuck Norris' has not been imported, because we started the import from row 2 with the parameter '-StartRow 2'.
-------------------------- EXAMPLE 6 --------------------------
PS\> ,(Import-Excel -Path .\SysTables_AdventureWorks2014.xlsx) |
Write-SqlTableData -ServerInstance localhost\DEFAULT -Database BlankDB -SchemaName dbo -TableName MyNewTable_fromExcel -Force
Imports data from an Excel file and pipes the result to the Write-SqlTableData command to be INSERTed into a table in a SQL Server database.
The ",( ... )" around the Import-Excel command allows all rows to be imported from the Excel file, prior to pipelining to the Write-SqlTableData cmdlet. This helps prevent a RBAR scenario and is important when trying to import thousands of rows.
The -Force parameter will be ignored if the table already exists. However, if a table is not found that matches the values provided by -SchemaName and -TableName parameters, it will create a new table in SQL Server database.
The Write-SqlTableData cmdlet will inherit the column names & datatypes for the new table from the object being piped in. NOTE: You need to install the SqlServer module from the PowerShell Gallery in oder to get the Write-SqlTableData cmdlet.
https://github.com/dfinke/ImportExcel
https://github.com/dfinke/ImportExcel
Join-Worksheet
Join
Worksheet
Combines data on all the sheets in an Excel worksheet onto a single sheet.
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
Path
Path to a new or existing .XLSX file.
String
String
None
WorkSheetName
The name of a sheet within the workbook where the other sheets will be joined together - "Combined" by default.
Object
Object
Combined
Clearsheet
If specified ,any pre-existing target for the joined data will be deleted and re-created; otherwise data will be appended on this sheet.
SwitchParameter
False
NoHeader
Join-Worksheet assumes each sheet has identical headers and the headers should be copied to the target sheet, unless -NoHeader is specified.
SwitchParameter
False
FromLabel
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.
String
String
From
LabelBlocks
If specified, the copied blocks of data will have the name of the sheet they were copied from inserted above them as a title.
SwitchParameter
False
AutoSize
Sets the width of the Excel columns to display all the data in their cells.
SwitchParameter
False
FreezeTopRow
Freezes headers etc. in the top row.
SwitchParameter
False
FreezeFirstColumn
Freezes titles etc. in the left column.
SwitchParameter
False
FreezeTopRowFirstColumn
Freezes top row and left column (equivalent to Freeze pane 2,2 ).
SwitchParameter
False
FreezePane
Freezes panes at specified coordinates (in the formRowNumber , ColumnNumber).
Int32[]
Int32[]
None
AutoFilter
Enables the Excel filter on the headers of the combined sheet.
SwitchParameter
False
BoldTopRow
Makes the top row boldface.
SwitchParameter
False
HideSource
If specified, hides the sheets that the data is copied from.
SwitchParameter
False
Title
Text of a title to be placed in Cell A1.
String
String
None
TitleFillPattern
Sets the fill pattern for the title cell.
None
Solid
DarkGray
MediumGray
LightGray
Gray125
Gray0625
DarkVertical
DarkHorizontal
DarkDown
DarkUp
DarkGrid
DarkTrellis
LightVertical
LightHorizontal
LightDown
LightUp
LightGrid
LightTrellis
ExcelFillStyle
ExcelFillStyle
Solid
TitleBackgroundColor
Sets the cell background color for the title cell.
Object
Object
None
TitleBold
Sets the title in boldface type.
SwitchParameter
False
TitleSize
Sets the point size for the title.
Int32
Int32
22
PivotTableDefinition
Hashtable(s) with Sheet PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values to specify a definition for one or morePivotTable(s).
Hashtable
Hashtable
None
ExcelChartDefinition
A hashtable containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-pivot] charts.
Object[]
Object[]
None
ConditionalFormat
One or more conditional formatting rules defined with New-ConditionalFormattingIconSet.
Object[]
Object[]
None
ConditionalText
Applies a Conditional formatting rule defined with New-ConditionalText.
Object[]
Object[]
None
AutoNameRange
Makes each column a named range.
SwitchParameter
False
RangeName
Makes the data in the worksheet a named range.
String
String
None
ReturnRange
If specified, returns the range of cells in the combined sheet, in the format "A1:Z100".
SwitchParameter
False
Show
Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first.
SwitchParameter
False
PassThru
If specified, an object representing the unsaved Excel package will be returned, it then needs to be saved.
SwitchParameter
False
Join-Worksheet
Path
Path to a new or existing .XLSX file.
String
String
None
WorkSheetName
The name of a sheet within the workbook where the other sheets will be joined together - "Combined" by default.
Object
Object
Combined
Clearsheet
If specified ,any pre-existing target for the joined data will be deleted and re-created; otherwise data will be appended on this sheet.
SwitchParameter
False
NoHeader
Join-Worksheet assumes each sheet has identical headers and the headers should be copied to the target sheet, unless -NoHeader is specified.
SwitchParameter
False
FromLabel
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.
String
String
From
LabelBlocks
If specified, the copied blocks of data will have the name of the sheet they were copied from inserted above them as a title.
SwitchParameter
False
AutoSize
Sets the width of the Excel columns to display all the data in their cells.
SwitchParameter
False
FreezeTopRow
Freezes headers etc. in the top row.
SwitchParameter
False
FreezeFirstColumn
Freezes titles etc. in the left column.
SwitchParameter
False
FreezeTopRowFirstColumn
Freezes top row and left column (equivalent to Freeze pane 2,2 ).
SwitchParameter
False
FreezePane
Freezes panes at specified coordinates (in the formRowNumber , ColumnNumber).
Int32[]
Int32[]
None
BoldTopRow
Makes the top row boldface.
SwitchParameter
False
HideSource
If specified, hides the sheets that the data is copied from.
SwitchParameter
False
Title
Text of a title to be placed in Cell A1.
String
String
None
TitleFillPattern
Sets the fill pattern for the title cell.
None
Solid
DarkGray
MediumGray
LightGray
Gray125
Gray0625
DarkVertical
DarkHorizontal
DarkDown
DarkUp
DarkGrid
DarkTrellis
LightVertical
LightHorizontal
LightDown
LightUp
LightGrid
LightTrellis
ExcelFillStyle
ExcelFillStyle
Solid
TitleBackgroundColor
Sets the cell background color for the title cell.
Object
Object
None
TitleBold
Sets the title in boldface type.
SwitchParameter
False
TitleSize
Sets the point size for the title.
Int32
Int32
22
PivotTableDefinition
Hashtable(s) with Sheet PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values to specify a definition for one or morePivotTable(s).
Hashtable
Hashtable
None
ExcelChartDefinition
A hashtable containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-pivot] charts.
Object[]
Object[]
None
ConditionalFormat
One or more conditional formatting rules defined with New-ConditionalFormattingIconSet.
Object[]
Object[]
None
ConditionalText
Applies a Conditional formatting rule defined with New-ConditionalText.
Object[]
Object[]
None
AutoNameRange
Makes each column a named range.
SwitchParameter
False
RangeName
Makes the data in the worksheet a named range.
String
String
None
TableName
Makes the data in the worksheet a table with a name and applies a style to it. Name must not contain spaces.
String
String
None
TableStyle
Selects the style for the named table - defaults to "Medium6".
None
Custom
Light1
Light2
Light3
Light4
Light5
Light6
Light7
Light8
Light9
Light10
Light11
Light12
Light13
Light14
Light15
Light16
Light17
Light18
Light19
Light20
Light21
Medium1
Medium2
Medium3
Medium4
Medium5
Medium6
Medium7
Medium8
Medium9
Medium10
Medium11
Medium12
Medium13
Medium14
Medium15
Medium16
Medium17
Medium18
Medium19
Medium20
Medium21
Medium22
Medium23
Medium24
Medium25
Medium26
Medium27
Medium28
Dark1
Dark2
Dark3
Dark4
Dark5
Dark6
Dark7
Dark8
Dark9
Dark10
Dark11
TableStyles
TableStyles
Medium6
ReturnRange
If specified, returns the range of cells in the combined sheet, in the format "A1:Z100".
SwitchParameter
False
Show
Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first.
SwitchParameter
False
PassThru
If specified, an object representing the unsaved Excel package will be returned, it then needs to be saved.
SwitchParameter
False
Join-Worksheet
ExcelPackage
An object representing an Excel Package - either from Open-ExcelPackage or specifying -PassThru to Export-Excel.
ExcelPackage
ExcelPackage
None
WorkSheetName
The name of a sheet within the workbook where the other sheets will be joined together - "Combined" by default.
Object
Object
Combined
Clearsheet
If specified ,any pre-existing target for the joined data will be deleted and re-created; otherwise data will be appended on this sheet.
SwitchParameter
False
NoHeader
Join-Worksheet assumes each sheet has identical headers and the headers should be copied to the target sheet, unless -NoHeader is specified.
SwitchParameter
False
FromLabel
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.
String
String
From
LabelBlocks
If specified, the copied blocks of data will have the name of the sheet they were copied from inserted above them as a title.
SwitchParameter
False
AutoSize
Sets the width of the Excel columns to display all the data in their cells.
SwitchParameter
False
FreezeTopRow
Freezes headers etc. in the top row.
SwitchParameter
False
FreezeFirstColumn
Freezes titles etc. in the left column.
SwitchParameter
False
FreezeTopRowFirstColumn
Freezes top row and left column (equivalent to Freeze pane 2,2 ).
SwitchParameter
False
FreezePane
Freezes panes at specified coordinates (in the formRowNumber , ColumnNumber).
Int32[]
Int32[]
None
BoldTopRow
Makes the top row boldface.
SwitchParameter
False
HideSource
If specified, hides the sheets that the data is copied from.
SwitchParameter
False
Title
Text of a title to be placed in Cell A1.
String
String
None
TitleFillPattern
Sets the fill pattern for the title cell.
None
Solid
DarkGray
MediumGray
LightGray
Gray125
Gray0625
DarkVertical
DarkHorizontal
DarkDown
DarkUp
DarkGrid
DarkTrellis
LightVertical
LightHorizontal
LightDown
LightUp
LightGrid
LightTrellis
ExcelFillStyle
ExcelFillStyle
Solid
TitleBackgroundColor
Sets the cell background color for the title cell.
Object
Object
None
TitleBold
Sets the title in boldface type.
SwitchParameter
False
TitleSize
Sets the point size for the title.
Int32
Int32
22
PivotTableDefinition
Hashtable(s) with Sheet PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values to specify a definition for one or morePivotTable(s).
Hashtable
Hashtable
None
ExcelChartDefinition
A hashtable containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-pivot] charts.
Object[]
Object[]
None
ConditionalFormat
One or more conditional formatting rules defined with New-ConditionalFormattingIconSet.
Object[]
Object[]
None
ConditionalText
Applies a Conditional formatting rule defined with New-ConditionalText.
Object[]
Object[]
None
AutoNameRange
Makes each column a named range.
SwitchParameter
False
RangeName
Makes the data in the worksheet a named range.
String
String
None
TableName
Makes the data in the worksheet a table with a name and applies a style to it. Name must not contain spaces.
String
String
None
TableStyle
Selects the style for the named table - defaults to "Medium6".
None
Custom
Light1
Light2
Light3
Light4
Light5
Light6
Light7
Light8
Light9
Light10
Light11
Light12
Light13
Light14
Light15
Light16
Light17
Light18
Light19
Light20
Light21
Medium1
Medium2
Medium3
Medium4
Medium5
Medium6
Medium7
Medium8
Medium9
Medium10
Medium11
Medium12
Medium13
Medium14
Medium15
Medium16
Medium17
Medium18
Medium19
Medium20
Medium21
Medium22
Medium23
Medium24
Medium25
Medium26
Medium27
Medium28
Dark1
Dark2
Dark3
Dark4
Dark5
Dark6
Dark7
Dark8
Dark9
Dark10
Dark11
TableStyles
TableStyles
Medium6
ReturnRange
If specified, returns the range of cells in the combined sheet, in the format "A1:Z100".
SwitchParameter
False
Show
Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first.
SwitchParameter
False
PassThru
If specified, an object representing the unsaved Excel package will be returned, it then needs to be saved.
SwitchParameter
False
Join-Worksheet
ExcelPackage
An object representing an Excel Package - either from Open-ExcelPackage or specifying -PassThru to Export-Excel.
ExcelPackage
ExcelPackage
None
WorkSheetName
The name of a sheet within the workbook where the other sheets will be joined together - "Combined" by default.
Object
Object
Combined
Clearsheet
If specified ,any pre-existing target for the joined data will be deleted and re-created; otherwise data will be appended on this sheet.
SwitchParameter
False
NoHeader
Join-Worksheet assumes each sheet has identical headers and the headers should be copied to the target sheet, unless -NoHeader is specified.
SwitchParameter
False
FromLabel
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.
String
String
From
LabelBlocks
If specified, the copied blocks of data will have the name of the sheet they were copied from inserted above them as a title.
SwitchParameter
False
AutoSize
Sets the width of the Excel columns to display all the data in their cells.
SwitchParameter
False
FreezeTopRow
Freezes headers etc. in the top row.
SwitchParameter
False
FreezeFirstColumn
Freezes titles etc. in the left column.
SwitchParameter
False
FreezeTopRowFirstColumn
Freezes top row and left column (equivalent to Freeze pane 2,2 ).
SwitchParameter
False
FreezePane
Freezes panes at specified coordinates (in the formRowNumber , ColumnNumber).
Int32[]
Int32[]
None
AutoFilter
Enables the Excel filter on the headers of the combined sheet.
SwitchParameter
False
BoldTopRow
Makes the top row boldface.
SwitchParameter
False
HideSource
If specified, hides the sheets that the data is copied from.
SwitchParameter
False
Title
Text of a title to be placed in Cell A1.
String
String
None
TitleFillPattern
Sets the fill pattern for the title cell.
None
Solid
DarkGray
MediumGray
LightGray
Gray125
Gray0625
DarkVertical
DarkHorizontal
DarkDown
DarkUp
DarkGrid
DarkTrellis
LightVertical
LightHorizontal
LightDown
LightUp
LightGrid
LightTrellis
ExcelFillStyle
ExcelFillStyle
Solid
TitleBackgroundColor
Sets the cell background color for the title cell.
Object
Object
None
TitleBold
Sets the title in boldface type.
SwitchParameter
False
TitleSize
Sets the point size for the title.
Int32
Int32
22
PivotTableDefinition
Hashtable(s) with Sheet PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values to specify a definition for one or morePivotTable(s).
Hashtable
Hashtable
None
ExcelChartDefinition
A hashtable containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-pivot] charts.
Object[]
Object[]
None
ConditionalFormat
One or more conditional formatting rules defined with New-ConditionalFormattingIconSet.
Object[]
Object[]
None
ConditionalText
Applies a Conditional formatting rule defined with New-ConditionalText.
Object[]
Object[]
None
AutoNameRange
Makes each column a named range.
SwitchParameter
False
RangeName
Makes the data in the worksheet a named range.
String
String
None
ReturnRange
If specified, returns the range of cells in the combined sheet, in the format "A1:Z100".
SwitchParameter
False
Show
Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first.
SwitchParameter
False
PassThru
If specified, an object representing the unsaved Excel package will be returned, it then needs to be saved.
SwitchParameter
False
Path
Path to a new or existing .XLSX file.
String
String
None
ExcelPackage
An object representing an Excel Package - either from Open-ExcelPackage or specifying -PassThru to Export-Excel.
ExcelPackage
ExcelPackage
None
WorkSheetName
The name of a sheet within the workbook where the other sheets will be joined together - "Combined" by default.
Object
Object
Combined
Clearsheet
If specified ,any pre-existing target for the joined data will be deleted and re-created; otherwise data will be appended on this sheet.
SwitchParameter
SwitchParameter
False
NoHeader
Join-Worksheet assumes each sheet has identical headers and the headers should be copied to the target sheet, unless -NoHeader is specified.
SwitchParameter
SwitchParameter
False
FromLabel
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.
String
String
From
LabelBlocks
If specified, the copied blocks of data will have the name of the sheet they were copied from inserted above them as a title.
SwitchParameter
SwitchParameter
False
AutoSize
Sets the width of the Excel columns to display all the data in their cells.
SwitchParameter
SwitchParameter
False
FreezeTopRow
Freezes headers etc. in the top row.
SwitchParameter
SwitchParameter
False
FreezeFirstColumn
Freezes titles etc. in the left column.
SwitchParameter
SwitchParameter
False
FreezeTopRowFirstColumn
Freezes top row and left column (equivalent to Freeze pane 2,2 ).
SwitchParameter
SwitchParameter
False
FreezePane
Freezes panes at specified coordinates (in the formRowNumber , ColumnNumber).
Int32[]
Int32[]
None
AutoFilter
Enables the Excel filter on the headers of the combined sheet.
SwitchParameter
SwitchParameter
False
BoldTopRow
Makes the top row boldface.
SwitchParameter
SwitchParameter
False
HideSource
If specified, hides the sheets that the data is copied from.
SwitchParameter
SwitchParameter
False
Title
Text of a title to be placed in Cell A1.
String
String
None
TitleFillPattern
Sets the fill pattern for the title cell.
ExcelFillStyle
ExcelFillStyle
Solid
TitleBackgroundColor
Sets the cell background color for the title cell.
Object
Object
None
TitleBold
Sets the title in boldface type.
SwitchParameter
SwitchParameter
False
TitleSize
Sets the point size for the title.
Int32
Int32
22
PivotTableDefinition
Hashtable(s) with Sheet PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values to specify a definition for one or morePivotTable(s).
Hashtable
Hashtable
None
ExcelChartDefinition
A hashtable containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-pivot] charts.
Object[]
Object[]
None
ConditionalFormat
One or more conditional formatting rules defined with New-ConditionalFormattingIconSet.
Object[]
Object[]
None
ConditionalText
Applies a Conditional formatting rule defined with New-ConditionalText.
Object[]
Object[]
None
AutoNameRange
Makes each column a named range.
SwitchParameter
SwitchParameter
False
RangeName
Makes the data in the worksheet a named range.
String
String
None
TableName
Makes the data in the worksheet a table with a name and applies a style to it. Name must not contain spaces.
String
String
None
TableStyle
Selects the style for the named table - defaults to "Medium6".
TableStyles
TableStyles
Medium6
ReturnRange
If specified, returns the range of cells in the combined sheet, in the format "A1:Z100".
SwitchParameter
SwitchParameter
False
Show
Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first.
SwitchParameter
SwitchParameter
False
PassThru
If specified, an object representing the unsaved Excel package will be returned, it then needs to be saved.
SwitchParameter
SwitchParameter
False
-------------------------- EXAMPLE 1 --------------------------
PS\> foreach ($computerName in @('Server1', 'Server2', 'Server3', 'Server4')) {
Get-Service -ComputerName $computerName |
Select-Object -Property Status, Name, DisplayName, StartType |
Export-Excel -Path .\test.xlsx -WorkSheetname $computerName -AutoSize
}
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 a list of services running on four servers and exports each list to its own page in Test.xlsx. And $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 2 --------------------------
PS\> Get-CimInstance -ClassName win32_logicaldisk |
Select-Object -Property DeviceId,VolumeName, Size,Freespace |
Export-Excel -Path "$env:computerName.xlsx" -WorkSheetname Volumes -NumberFormat "0,000"
PS\> Get-NetAdapter| Select-Object Name,InterfaceDescription,MacAddress,LinkSpeed |
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 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.
Online Version:
https://github.com/dfinke/ImportExcel
Merge-MultipleSheets
Merge
MultipleSheets
Merges Worksheets into a single Worksheet with differences marked up.
The Merge Worksheet command combines two sheets. Merge-MultipleSheets is designed to merge more than two.
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".
* 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" 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 they 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.
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 first 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.
Merge-MultipleSheets
Path
Paths to the files to be merged. Files are also accepted
Object
Object
None
KeyFontColor
Sets the font color for the Key field; this means you can filter by color to get only changed rows.
Object
Object
[System.Drawing.Color]::Red
ChangeBackgroundColor
Sets the background color for changed rows.
Object
Object
[System.Drawing.Color]::Orange
DeleteBackgroundColor
Sets the background color for rows in the reference but deleted from the difference sheet.
Object
Object
[System.Drawing.Color]::LightPink
AddBackgroundColor
Sets the background color for rows not in the reference but added to the difference sheet.
Object
Object
[System.Drawing.Color]::Orange
Startrow
The row from where we start to import data, all rows above the Start row are disregarded. By default this is the first row.
Int32
Int32
1
Headername
Specifies custom property names to use, instead of the values defined in the column headers of the Start row.
String[]
String[]
None
WorksheetName
Name(s) of Worksheets to compare.
Object
Object
Sheet1
OutputFile
File to write output to.
Object
Object
.\temp.xlsx
OutputSheetName
Name of Worksheet to output - if none specified will use the reference Worksheet name.
Object
Object
Sheet1
Property
Properties to include in the comparison - supports wildcards, default is "*".
Object
Object
*
ExcludeProperty
Properties to exclude from the the comparison - supports wildcards.
Object
Object
None
Key
Name of a column which is unique used to pair up rows from the reference and difference sides, default is "Name".
Object
Object
Name
NoHeader
If specified, property names will be automatically generated (P1, P2, P3, ..) instead of using the values from the start row.
SwitchParameter
False
HideRowNumbers
If specified, hides the columns in the spreadsheet that contain the row numbers.
SwitchParameter
False
Passthru
If specified, outputs the data to the pipeline (you can add -whatif so it the command only outputs to the pipeline).
SwitchParameter
False
Show
If specified, opens the output workbook.
SwitchParameter
False
Path
Paths to the files to be merged. Files are also accepted
Object
Object
None
Startrow
The row from where we start to import data, all rows above the Start row are disregarded. By default this is the first row.
Int32
Int32
1
Headername
Specifies custom property names to use, instead of the values defined in the column headers of the Start row.
String[]
String[]
None
NoHeader
If specified, property names will be automatically generated (P1, P2, P3, ..) instead of using the values from the start row.
SwitchParameter
SwitchParameter
False
WorksheetName
Name(s) of Worksheets to compare.
Object
Object
Sheet1
OutputFile
File to write output to.
Object
Object
.\temp.xlsx
OutputSheetName
Name of Worksheet to output - if none specified will use the reference Worksheet name.
Object
Object
Sheet1
Property
Properties to include in the comparison - supports wildcards, default is "*".
Object
Object
*
ExcludeProperty
Properties to exclude from the the comparison - supports wildcards.
Object
Object
None
Key
Name of a column which is unique used to pair up rows from the reference and difference sides, default is "Name".
Object
Object
Name
KeyFontColor
Sets the font color for the Key field; this means you can filter by color to get only changed rows.
Object
Object
[System.Drawing.Color]::Red
ChangeBackgroundColor
Sets the background color for changed rows.
Object
Object
[System.Drawing.Color]::Orange
DeleteBackgroundColor
Sets the background color for rows in the reference but deleted from the difference sheet.
Object
Object
[System.Drawing.Color]::LightPink
AddBackgroundColor
Sets the background color for rows not in the reference but added to the difference sheet.
Object
Object
[System.Drawing.Color]::Orange
HideRowNumbers
If specified, hides the columns in the spreadsheet that contain the row numbers.
SwitchParameter
SwitchParameter
False
Passthru
If specified, outputs the data to the pipeline (you can add -whatif so it the command only outputs to the pipeline).
SwitchParameter
SwitchParameter
False
Show
If specified, opens the output workbook.
SwitchParameter
SwitchParameter
False
-------------------------- EXAMPLE 1 --------------------------
PS\> dir Server*.xlsx | Merge-MulipleSheets -WorksheetName Services -OutputFile Test2.xlsx -OutputSheetName Services -Show
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 2 --------------------------
PS\> 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).
-------------------------- EXAMPLE 3 --------------------------
Merge-MulipleSheets -Path hotfixes.xlsx -WorksheetName Serv* -Key hotfixid -OutputFile test2.xlsx -OutputSheetName hotfixes -HideRowNumbers -Show
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.
Online Version:
https://github.com/dfinke/ImportExcel
Merge-Worksheet
Merge
Worksheet
Merges two Worksheets (or other objects) into a single Worksheet with differences marked up.
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 a Worksheet.
Merge-Worksheet
Referencefile
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. works with the following parameter sets
* A = Compare two files default headers
* B = Compare two files user supplied headers
* C = Compare two files headers P1, P2, P3 etc
Object
Object
None
Differencefile
Second Excel file to compare. Works with paramter sets A,B,C as well as the following
* D = Compare two objects;
* E = Compare one object one file that uses default headers
* F = Compare one object one file that uses user supplied headers
* G = Compare one object one file that uses headers P1, P2, P3 etc
Object
Object
None
WorksheetName
Name(s) of Worksheets to compare. Applies to all parameter sets EXCEPT D which is two objects (no sheets)
Object
Object
Sheet1
OutputFile
File to hold merged data.
Object
Object
None
OutputSheetName
Name of Worksheet to output - if none specified will use the reference Worksheet name.
Object
Object
Sheet1
Startrow
The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. Applies to all sets EXCEPT D which is two objects (no sheets, so no start row )
Int32
Int32
1
NoHeader
Automatically generate property names (P1, P2, P3, ..) instead of using the values the top row of the sheet. Works with parameter sets
* C 2 sheets with headers of P1, P2, P3 ...
* G Compare object + sheet
SwitchParameter
False
Property
Properties to include in the DIFF - supports wildcards, default is "*".
Object
Object
*
ExcludeProperty
Properties to exclude from the the search - supports wildcards.
Object
Object
None
Key
Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name".
Object
Object
Name
KeyFontColor
Sets the font color for the "key" field; this means you can filter by color to get only changed rows.
Object
Object
[System.Drawing.Color]::DarkRed
ChangeBackgroundColor
Sets the background color for changed rows.
Object
Object
[System.Drawing.Color]::Orange
DeleteBackgroundColor
Sets the background color for rows in the reference but deleted from the difference sheet.
Object
Object
[System.Drawing.Color]::LightPink
AddBackgroundColor
Sets the background color for rows not in the reference but added to the difference sheet.
Object
Object
[System.Drawing.Color]::PaleGreen
HideEqual
if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows.
SwitchParameter
False
Passthru
If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline).
SwitchParameter
False
Show
If specified, opens the output workbook.
SwitchParameter
False
WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
SwitchParameter
False
Confirm
Prompts you for confirmation before running the cmdlet.
SwitchParameter
False
Merge-Worksheet
Referencefile
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. works with the following parameter sets
* A = Compare two files default headers
* B = Compare two files user supplied headers
* C = Compare two files headers P1, P2, P3 etc
Object
Object
None
Differencefile
Second Excel file to compare. Works with paramter sets A,B,C as well as the following
* D = Compare two objects;
* E = Compare one object one file that uses default headers
* F = Compare one object one file that uses user supplied headers
* G = Compare one object one file that uses headers P1, P2, P3 etc
Object
Object
None
WorksheetName
Name(s) of Worksheets to compare. Applies to all parameter sets EXCEPT D which is two objects (no sheets)
Object
Object
Sheet1
OutputFile
File to hold merged data.
Object
Object
None
OutputSheetName
Name of Worksheet to output - if none specified will use the reference Worksheet name.
Object
Object
Sheet1
Startrow
The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. Applies to all sets EXCEPT D which is two objects (no sheets, so no start row )
Int32
Int32
1
Headername
Specifies custom property names to use, instead of the values defined in the column headers of the Start Row. Works with the following parameter sets:
* B 2 sheets with user supplied headers
* F Compare object + sheet
String[]
String[]
None
Property
Properties to include in the DIFF - supports wildcards, default is "*".
Object
Object
*
ExcludeProperty
Properties to exclude from the the search - supports wildcards.
Object
Object
None
Key
Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name".
Object
Object
Name
KeyFontColor
Sets the font color for the "key" field; this means you can filter by color to get only changed rows.
Object
Object
[System.Drawing.Color]::DarkRed
ChangeBackgroundColor
Sets the background color for changed rows.
Object
Object
[System.Drawing.Color]::Orange
DeleteBackgroundColor
Sets the background color for rows in the reference but deleted from the difference sheet.
Object
Object
[System.Drawing.Color]::LightPink
AddBackgroundColor
Sets the background color for rows not in the reference but added to the difference sheet.
Object
Object
[System.Drawing.Color]::PaleGreen
HideEqual
if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows.
SwitchParameter
False
Passthru
If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline).
SwitchParameter
False
Show
If specified, opens the output workbook.
SwitchParameter
False
WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
SwitchParameter
False
Confirm
Prompts you for confirmation before running the cmdlet.
SwitchParameter
False
Merge-Worksheet
Referencefile
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. works with the following parameter sets
* A = Compare two files default headers
* B = Compare two files user supplied headers
* C = Compare two files headers P1, P2, P3 etc
Object
Object
None
Differencefile
Second Excel file to compare. Works with paramter sets A,B,C as well as the following
* D = Compare two objects;
* E = Compare one object one file that uses default headers
* F = Compare one object one file that uses user supplied headers
* G = Compare one object one file that uses headers P1, P2, P3 etc
Object
Object
None
WorksheetName
Name(s) of Worksheets to compare. Applies to all parameter sets EXCEPT D which is two objects (no sheets)
Object
Object
Sheet1
OutputFile
File to hold merged data.
Object
Object
None
OutputSheetName
Name of Worksheet to output - if none specified will use the reference Worksheet name.
Object
Object
Sheet1
Startrow
The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. Applies to all sets EXCEPT D which is two objects (no sheets, so no start row )
Int32
Int32
1
Property
Properties to include in the DIFF - supports wildcards, default is "*".
Object
Object
*
ExcludeProperty
Properties to exclude from the the search - supports wildcards.
Object
Object
None
Key
Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name".
Object
Object
Name
KeyFontColor
Sets the font color for the "key" field; this means you can filter by color to get only changed rows.
Object
Object
[System.Drawing.Color]::DarkRed
ChangeBackgroundColor
Sets the background color for changed rows.
Object
Object
[System.Drawing.Color]::Orange
DeleteBackgroundColor
Sets the background color for rows in the reference but deleted from the difference sheet.
Object
Object
[System.Drawing.Color]::LightPink
AddBackgroundColor
Sets the background color for rows not in the reference but added to the difference sheet.
Object
Object
[System.Drawing.Color]::PaleGreen
HideEqual
if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows.
SwitchParameter
False
Passthru
If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline).
SwitchParameter
False
Show
If specified, opens the output workbook.
SwitchParameter
False
WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
SwitchParameter
False
Confirm
Prompts you for confirmation before running the cmdlet.
SwitchParameter
False
Merge-Worksheet
Differencefile
Second Excel file to compare. Works with paramter sets A,B,C as well as the following
* D = Compare two objects;
* E = Compare one object one file that uses default headers
* F = Compare one object one file that uses user supplied headers
* G = Compare one object one file that uses headers P1, P2, P3 etc
Object
Object
None
WorksheetName
Name(s) of Worksheets to compare. Applies to all parameter sets EXCEPT D which is two objects (no sheets)
Object
Object
Sheet1
DiffPrefix
If there isn't a filename to use to label data from the "Difference" side, DiffPrefix is used, it defaults to "=>"
Object
Object
=>
OutputFile
File to hold merged data.
Object
Object
None
OutputSheetName
Name of Worksheet to output - if none specified will use the reference Worksheet name.
Object
Object
Sheet1
Startrow
The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. Applies to all sets EXCEPT D which is two objects (no sheets, so no start row )
Int32
Int32
1
NoHeader
Automatically generate property names (P1, P2, P3, ..) instead of using the values the top row of the sheet. Works with parameter sets
* C 2 sheets with headers of P1, P2, P3 ...
* G Compare object + sheet
SwitchParameter
False
ReferenceObject
Reference object to compare if a Worksheet is NOT being used. Reference object can combine with a difference sheet or difference object
Object
Object
None
Property
Properties to include in the DIFF - supports wildcards, default is "*".
Object
Object
*
ExcludeProperty
Properties to exclude from the the search - supports wildcards.
Object
Object
None
Key
Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name".
Object
Object
Name
KeyFontColor
Sets the font color for the "key" field; this means you can filter by color to get only changed rows.
Object
Object
[System.Drawing.Color]::DarkRed
ChangeBackgroundColor
Sets the background color for changed rows.
Object
Object
[System.Drawing.Color]::Orange
DeleteBackgroundColor
Sets the background color for rows in the reference but deleted from the difference sheet.
Object
Object
[System.Drawing.Color]::LightPink
AddBackgroundColor
Sets the background color for rows not in the reference but added to the difference sheet.
Object
Object
[System.Drawing.Color]::PaleGreen
HideEqual
if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows.
SwitchParameter
False
Passthru
If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline).
SwitchParameter
False
Show
If specified, opens the output workbook.
SwitchParameter
False
WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
SwitchParameter
False
Confirm
Prompts you for confirmation before running the cmdlet.
SwitchParameter
False
Merge-Worksheet
Differencefile
Second Excel file to compare. Works with paramter sets A,B,C as well as the following
* D = Compare two objects;
* E = Compare one object one file that uses default headers
* F = Compare one object one file that uses user supplied headers
* G = Compare one object one file that uses headers P1, P2, P3 etc
Object
Object
None
WorksheetName
Name(s) of Worksheets to compare. Applies to all parameter sets EXCEPT D which is two objects (no sheets)
Object
Object
Sheet1
DiffPrefix
If there isn't a filename to use to label data from the "Difference" side, DiffPrefix is used, it defaults to "=>"
Object
Object
=>
OutputFile
File to hold merged data.
Object
Object
None
OutputSheetName
Name of Worksheet to output - if none specified will use the reference Worksheet name.
Object
Object
Sheet1
Startrow
The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. Applies to all sets EXCEPT D which is two objects (no sheets, so no start row )
Int32
Int32
1
Headername
Specifies custom property names to use, instead of the values defined in the column headers of the Start Row. Works with the following parameter sets:
* B 2 sheets with user supplied headers
* F Compare object + sheet
String[]
String[]
None
ReferenceObject
Reference object to compare if a Worksheet is NOT being used. Reference object can combine with a difference sheet or difference object
Object
Object
None
Property
Properties to include in the DIFF - supports wildcards, default is "*".
Object
Object
*
ExcludeProperty
Properties to exclude from the the search - supports wildcards.
Object
Object
None
Key
Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name".
Object
Object
Name
KeyFontColor
Sets the font color for the "key" field; this means you can filter by color to get only changed rows.
Object
Object
[System.Drawing.Color]::DarkRed
ChangeBackgroundColor
Sets the background color for changed rows.
Object
Object
[System.Drawing.Color]::Orange
DeleteBackgroundColor
Sets the background color for rows in the reference but deleted from the difference sheet.
Object
Object
[System.Drawing.Color]::LightPink
AddBackgroundColor
Sets the background color for rows not in the reference but added to the difference sheet.
Object
Object
[System.Drawing.Color]::PaleGreen
HideEqual
if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows.
SwitchParameter
False
Passthru
If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline).
SwitchParameter
False
Show
If specified, opens the output workbook.
SwitchParameter
False
WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
SwitchParameter
False
Confirm
Prompts you for confirmation before running the cmdlet.
SwitchParameter
False
Merge-Worksheet
Differencefile
Second Excel file to compare. Works with paramter sets A,B,C as well as the following
* D = Compare two objects;
* E = Compare one object one file that uses default headers
* F = Compare one object one file that uses user supplied headers
* G = Compare one object one file that uses headers P1, P2, P3 etc
Object
Object
None
WorksheetName
Name(s) of Worksheets to compare. Applies to all parameter sets EXCEPT D which is two objects (no sheets)
Object
Object
Sheet1
DiffPrefix
If there isn't a filename to use to label data from the "Difference" side, DiffPrefix is used, it defaults to "=>"
Object
Object
=>
OutputFile
File to hold merged data.
Object
Object
None
OutputSheetName
Name of Worksheet to output - if none specified will use the reference Worksheet name.
Object
Object
Sheet1
Startrow
The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. Applies to all sets EXCEPT D which is two objects (no sheets, so no start row )
Int32
Int32
1
ReferenceObject
Reference object to compare if a Worksheet is NOT being used. Reference object can combine with a difference sheet or difference object
Object
Object
None
Property
Properties to include in the DIFF - supports wildcards, default is "*".
Object
Object
*
ExcludeProperty
Properties to exclude from the the search - supports wildcards.
Object
Object
None
Key
Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name".
Object
Object
Name
KeyFontColor
Sets the font color for the "key" field; this means you can filter by color to get only changed rows.
Object
Object
[System.Drawing.Color]::DarkRed
ChangeBackgroundColor
Sets the background color for changed rows.
Object
Object
[System.Drawing.Color]::Orange
DeleteBackgroundColor
Sets the background color for rows in the reference but deleted from the difference sheet.
Object
Object
[System.Drawing.Color]::LightPink
AddBackgroundColor
Sets the background color for rows not in the reference but added to the difference sheet.
Object
Object
[System.Drawing.Color]::PaleGreen
HideEqual
if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows.
SwitchParameter
False
Passthru
If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline).
SwitchParameter
False
Show
If specified, opens the output workbook.
SwitchParameter
False
WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
SwitchParameter
False
Confirm
Prompts you for confirmation before running the cmdlet.
SwitchParameter
False
Merge-Worksheet
DifferenceObject
Difference object to compare if a Worksheet is NOT being used for either half. Can't have a reference sheet and difference object.
Object
Object
None
DiffPrefix
If there isn't a filename to use to label data from the "Difference" side, DiffPrefix is used, it defaults to "=>"
Object
Object
=>
OutputFile
File to hold merged data.
Object
Object
None
OutputSheetName
Name of Worksheet to output - if none specified will use the reference Worksheet name.
Object
Object
Sheet1
ReferenceObject
Reference object to compare if a Worksheet is NOT being used. Reference object can combine with a difference sheet or difference object
Object
Object
None
Property
Properties to include in the DIFF - supports wildcards, default is "*".
Object
Object
*
ExcludeProperty
Properties to exclude from the the search - supports wildcards.
Object
Object
None
Key
Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name".
Object
Object
Name
KeyFontColor
Sets the font color for the "key" field; this means you can filter by color to get only changed rows.
Object
Object
[System.Drawing.Color]::DarkRed
ChangeBackgroundColor
Sets the background color for changed rows.
Object
Object
[System.Drawing.Color]::Orange
DeleteBackgroundColor
Sets the background color for rows in the reference but deleted from the difference sheet.
Object
Object
[System.Drawing.Color]::LightPink
AddBackgroundColor
Sets the background color for rows not in the reference but added to the difference sheet.
Object
Object
[System.Drawing.Color]::PaleGreen
HideEqual
if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows.
SwitchParameter
False
Passthru
If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline).
SwitchParameter
False
Show
If specified, opens the output workbook.
SwitchParameter
False
WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
SwitchParameter
False
Confirm
Prompts you for confirmation before running the cmdlet.
SwitchParameter
False
Referencefile
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. works with the following parameter sets
* A = Compare two files default headers
* B = Compare two files user supplied headers
* C = Compare two files headers P1, P2, P3 etc
Object
Object
None
Differencefile
Second Excel file to compare. Works with paramter sets A,B,C as well as the following
* D = Compare two objects;
* E = Compare one object one file that uses default headers
* F = Compare one object one file that uses user supplied headers
* G = Compare one object one file that uses headers P1, P2, P3 etc
Object
Object
None
WorksheetName
Name(s) of Worksheets to compare. Applies to all parameter sets EXCEPT D which is two objects (no sheets)
Object
Object
Sheet1
Startrow
The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. Applies to all sets EXCEPT D which is two objects (no sheets, so no start row )
Int32
Int32
1
Headername
Specifies custom property names to use, instead of the values defined in the column headers of the Start Row. Works with the following parameter sets:
* B 2 sheets with user supplied headers
* F Compare object + sheet
String[]
String[]
None
NoHeader
Automatically generate property names (P1, P2, P3, ..) instead of using the values the top row of the sheet. Works with parameter sets
* C 2 sheets with headers of P1, P2, P3 ...
* G Compare object + sheet
SwitchParameter
SwitchParameter
False
ReferenceObject
Reference object to compare if a Worksheet is NOT being used. Reference object can combine with a difference sheet or difference object
Object
Object
None
DifferenceObject
Difference object to compare if a Worksheet is NOT being used for either half. Can't have a reference sheet and difference object.
Object
Object
None
DiffPrefix
If there isn't a filename to use to label data from the "Difference" side, DiffPrefix is used, it defaults to "=>"
Object
Object
=>
OutputFile
File to hold merged data.
Object
Object
None
OutputSheetName
Name of Worksheet to output - if none specified will use the reference Worksheet name.
Object
Object
Sheet1
Property
Properties to include in the DIFF - supports wildcards, default is "*".
Object
Object
*
ExcludeProperty
Properties to exclude from the the search - supports wildcards.
Object
Object
None
Key
Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name".
Object
Object
Name
KeyFontColor
Sets the font color for the "key" field; this means you can filter by color to get only changed rows.
Object
Object
[System.Drawing.Color]::DarkRed
ChangeBackgroundColor
Sets the background color for changed rows.
Object
Object
[System.Drawing.Color]::Orange
DeleteBackgroundColor
Sets the background color for rows in the reference but deleted from the difference sheet.
Object
Object
[System.Drawing.Color]::LightPink
AddBackgroundColor
Sets the background color for rows not in the reference but added to the difference sheet.
Object
Object
[System.Drawing.Color]::PaleGreen
HideEqual
if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows.
SwitchParameter
SwitchParameter
False
Passthru
If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline).
SwitchParameter
SwitchParameter
False
Show
If specified, opens the output workbook.
SwitchParameter
SwitchParameter
False
WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
SwitchParameter
SwitchParameter
False
Confirm
Prompts you for confirmation before running the cmdlet.
SwitchParameter
SwitchParameter
False
-------------------------- EXAMPLE 1 --------------------------
PS\> 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 2 --------------------------
PS\> 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 3 --------------------------
PS\> 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.
-------------------------- EXAMPLE 4 --------------------------
PS\> 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).
Online Version:
https://github.com/dfinke/ImportExcel
New-ConditionalFormattingIconSet
New
ConditionalFormattingIconSet
Creates an object which describes a conditional formatting rule a for 3,4 or 5 icon set.
Export-Excel takes a -ConditionalFormat parameter which can hold one or more descriptions for conditional formats; this command builds the defintion of a Conditional formatting rule for an icon set.
New-ConditionalFormattingIconSet
Range
The range of cells that the conditional format applies to.
Object
Object
None
ConditionalFormat
The type of rule: one of "ThreeIconSet","FourIconSet" or "FiveIconSet"
Object
Object
None
Reverse
Use the icons in the reverse order.
SwitchParameter
False
Range
The range of cells that the conditional format applies to.
Object
Object
None
ConditionalFormat
The type of rule: one of "ThreeIconSet","FourIconSet" or "FiveIconSet"
Object
Object
None
Reverse
Use the icons in the reverse order.
SwitchParameter
SwitchParameter
False
-------------------------- EXAMPLE 1 --------------------------
PS\> $cfRange = [OfficeOpenXml.ExcelAddress]::new($topRow, $column, $lastDataRow, $column)
PS\> $cfdef = New-ConditionalFormattingIconSet -Range $cfrange -ConditionalFormat ThreeIconSet -IconType Arrows
PS\> 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 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.
Add-Add-ConditionalFormatting
New-ConditionalText
New-ConditionalText
New
ConditionalText
Creates an object which describes a conditional formatting rule for single valued rules.
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).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.
New-ConditionalText
Text
The text (or other value) to use in the rule. Note that Equals, GreaterThan/LessThan rules require text to wrapped in double quotes.
Object
Object
None
ConditionalTextColor
The font color for the cell - by default: "DarkRed".
Object
Object
[System.Drawing.Color]::DarkRed
BackgroundColor
The fill color for the cell - by default: "LightPink".
Object
Object
[System.Drawing.Color]::LightPink
Range
The range of cells that the conditional format applies to; if none is specified the range will be apply to all the data in the sheet.
String
String
None
PatternType
The background pattern for the cell - by default: "Solid"
None
Solid
DarkGray
MediumGray
LightGray
Gray125
Gray0625
DarkVertical
DarkHorizontal
DarkDown
DarkUp
DarkGrid
DarkTrellis
LightVertical
LightHorizontal
LightDown
LightUp
LightGrid
LightTrellis
ExcelFillStyle
ExcelFillStyle
Solid
ConditionalType
One of the supported rules; by default "ContainsText" is selected.
Object
Object
ContainsText
Text
The text (or other value) to use in the rule. Note that Equals, GreaterThan/LessThan rules require text to wrapped in double quotes.
Object
Object
None
ConditionalTextColor
The font color for the cell - by default: "DarkRed".
Object
Object
[System.Drawing.Color]::DarkRed
BackgroundColor
The fill color for the cell - by default: "LightPink".
Object
Object
[System.Drawing.Color]::LightPink
Range
The range of cells that the conditional format applies to; if none is specified the range will be apply to all the data in the sheet.
String
String
None
PatternType
The background pattern for the cell - by default: "Solid"
ExcelFillStyle
ExcelFillStyle
Solid
ConditionalType
One of the supported rules; by default "ContainsText" is selected.
Object
Object
ContainsText
-------------------------- EXAMPLE 1 --------------------------
PS\> $ct = New-ConditionalText -Text 'Ferrari'
PS\> 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.
-------------------------- EXAMPLE 2 --------------------------
PS\> $ct = New-ConditionalText -Text "Ferrari"
PS\> $ct2 = New-ConditionalText -Range $worksheet.Names\["FinishPosition"\].Address -ConditionalType LessThanOrEqual -Text 3 -ConditionalTextColor Red -BackgroundColor White
PS\> 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 -Range "C:C" to specify a named column, or -Range "C2:C102" to specify certain cells in the column.
Add-ConditionalFormatting
New-ConditionalFormattingIconSet
New-ExcelChartDefinition
New
ExcelChartDefinition
Creates a Definition of a chart which can be added using Export-Excel, or Add-PivotTable
All the parameters which are passed to Add-ExcelChart can be added to a chart-definition object and passed to Export-Excel with the -ExcelChartDefinition parameter, or to Add-PivotTable with the -PivotChartDefinition parameter. This command sets up those definition objects.
New-ExcelChartDefinition
Title
The title for the chart.
Object
Object
Chart Title
RowOffSetPixels
Offset to position the chart by a fraction of a row.
Object
Object
10
Column
Column position of the top left corner of the chart. 0 places it at the edge of the sheet, 1 to the right of column A and so on.
Object
Object
6
ColumnOffSetPixels
Offset to position the chart by a fraction of a column.
Object
Object
5
LegendPosition
Location of the key, either "Left", "Right", "Top", "Bottom" or "TopRight".
Top
Left
Right
Bottom
TopRight
eLegendPosition
eLegendPosition
None
LegendSize
Font size for the key.
Object
Object
None
SeriesHeader
Specifies explicit name(s) for the data series, which will appear in the legend/key
Object
Object
None
TitleSize
Sets the point size for the title.
Int32
Int32
0
XAxisTitleText
Specifies a title for the X-axis.
String
String
None
XAxisTitleSize
Sets the font size for the axis title.
Object
Object
None
XAxisNumberformat
A number formatting string, like "#,##0.00", for numbers along the X-axis.
String
String
None
Header
No longer used. This may be removed in future versions.
Object
Object
None
XMajorUnit
Spacing for the major gridlines / tick marks along the X-axis.
Object
Object
None
XMinorUnit
Spacing for the minor gridlines / tick marks along the X-axis.
Object
Object
None
XMaxValue
Maximum value for the scale along the X-axis.
Object
Object
None
XMinValue
Minimum value for the scale along the X-axis.
Object
Object
None
XAxisPosition
Position for the X-axis ("Top" or" Bottom").
Left
Bottom
Right
Top
eAxisPosition
eAxisPosition
None
YAxisTitleText
Specifies a title for the Y-axis.
String
String
None
YAxisTitleSize
Sets the font size for the Y-axis title.
Object
Object
None
YAxisNumberformat
A number formatting string, like "#,##0.00", for numbers on the Y-axis
String
String
None
YMajorUnit
Spacing for the major gridlines / tick marks on the Y-axis.
Object
Object
None
YMinorUnit
Spacing for the minor gridlines / tick marks on the Y-axis.
Object
Object
None
ChartType
One of the built-in chart types, such as Pie, ClusteredColumn, Line etc. Defaults to "ColumnStacked".
Area
Line
Pie
Bubble
ColumnClustered
ColumnStacked
ColumnStacked100
ColumnClustered3D
ColumnStacked3D
ColumnStacked1003D
BarClustered
BarStacked
BarStacked100
BarClustered3D
BarStacked3D
BarStacked1003D
LineStacked
LineStacked100
LineMarkers
LineMarkersStacked
LineMarkersStacked100
PieOfPie
PieExploded
PieExploded3D
BarOfPie
XYScatterSmooth
XYScatterSmoothNoMarkers
XYScatterLines
XYScatterLinesNoMarkers
AreaStacked
AreaStacked100
AreaStacked3D
AreaStacked1003D
DoughnutExploded
RadarMarkers
RadarFilled
Surface
SurfaceWireframe
SurfaceTopView
SurfaceTopViewWireframe
Bubble3DEffect
StockHLC
StockOHLC
StockVHLC
StockVOHLC
CylinderColClustered
CylinderColStacked
CylinderColStacked100
CylinderBarClustered
CylinderBarStacked
CylinderBarStacked100
CylinderCol
ConeColClustered
ConeColStacked
ConeColStacked100
ConeBarClustered
ConeBarStacked
ConeBarStacked100
ConeCol
PyramidColClustered
PyramidColStacked
PyramidColStacked100
PyramidBarClustered
PyramidBarStacked
PyramidBarStacked100
PyramidCol
XYScatter
Radar
Doughnut
Pie3D
Line3D
Column3D
Area3D
eChartType
eChartType
ColumnStacked
YMaxValue
Maximum value on the Y-axis.
Object
Object
None
YMinValue
Minimum value on the Y-axis.
Object
Object
None
YAxisPosition
Position for the Y-axis ("Left" or "Right").
Left
Bottom
Right
Top
eAxisPosition
eAxisPosition
None
ChartTrendLine
Superimposes one of Excel's trenline types on the chart.
Exponential
Linear
Logarithmic
MovingAvgerage
Polynomial
Power
eTrendLine[]
eTrendLine[]
None
XRange
The range of cells containing values for the X-Axis - usually labels.
Object
Object
None
YRange
The range(s) of cells holding values for the Y-Axis - usually "data".
Object
Object
None
Width
Width of the chart in pixels. Defaults to 500.
Object
Object
500
Height
Height of the chart in pixels. Defaults to 350.
Object
Object
350
Row
Row position of the top left corner of the chart. 0 places it at the top of the sheet, 1 below row 1 and so on.
Object
Object
0
LegendBold
Sets the key in bold type.
SwitchParameter
False
NoLegend
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.
SwitchParameter
False
ShowCategory
Attaches a category label in charts which support this.
SwitchParameter
False
ShowPercent
Attaches a percentage label in charts which support this.
SwitchParameter
False
TitleBold
Sets the title in bold face.
SwitchParameter
False
XAxisTitleBold
Sets the X-axis title in bold face.
SwitchParameter
False
YAxisTitleBold
Sets the Y-axis title in bold face.
SwitchParameter
False
Title
The title for the chart.
Object
Object
Chart Title
Header
No longer used. This may be removed in future versions.
Object
Object
None
ChartType
One of the built-in chart types, such as Pie, ClusteredColumn, Line etc. Defaults to "ColumnStacked".
eChartType
eChartType
ColumnStacked
ChartTrendLine
Superimposes one of Excel's trenline types on the chart.
eTrendLine[]
eTrendLine[]
None
XRange
The range of cells containing values for the X-Axis - usually labels.
Object
Object
None
YRange
The range(s) of cells holding values for the Y-Axis - usually "data".
Object
Object
None
Width
Width of the chart in pixels. Defaults to 500.
Object
Object
500
Height
Height of the chart in pixels. Defaults to 350.
Object
Object
350
Row
Row position of the top left corner of the chart. 0 places it at the top of the sheet, 1 below row 1 and so on.
Object
Object
0
RowOffSetPixels
Offset to position the chart by a fraction of a row.
Object
Object
10
Column
Column position of the top left corner of the chart. 0 places it at the edge of the sheet, 1 to the right of column A and so on.
Object
Object
6
ColumnOffSetPixels
Offset to position the chart by a fraction of a column.
Object
Object
5
LegendPosition
Location of the key, either "Left", "Right", "Top", "Bottom" or "TopRight".
eLegendPosition
eLegendPosition
None
LegendSize
Font size for the key.
Object
Object
None
LegendBold
Sets the key in bold type.
SwitchParameter
SwitchParameter
False
NoLegend
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.
SwitchParameter
SwitchParameter
False
ShowCategory
Attaches a category label in charts which support this.
SwitchParameter
SwitchParameter
False
ShowPercent
Attaches a percentage label in charts which support this.
SwitchParameter
SwitchParameter
False
SeriesHeader
Specifies explicit name(s) for the data series, which will appear in the legend/key
Object
Object
None
TitleBold
Sets the title in bold face.
SwitchParameter
SwitchParameter
False
TitleSize
Sets the point size for the title.
Int32
Int32
0
XAxisTitleText
Specifies a title for the X-axis.
String
String
None
XAxisTitleBold
Sets the X-axis title in bold face.
SwitchParameter
SwitchParameter
False
XAxisTitleSize
Sets the font size for the axis title.
Object
Object
None
XAxisNumberformat
A number formatting string, like "#,##0.00", for numbers along the X-axis.
String
String
None
XMajorUnit
Spacing for the major gridlines / tick marks along the X-axis.
Object
Object
None
XMinorUnit
Spacing for the minor gridlines / tick marks along the X-axis.
Object
Object
None
XMaxValue
Maximum value for the scale along the X-axis.
Object
Object
None
XMinValue
Minimum value for the scale along the X-axis.
Object
Object
None
XAxisPosition
Position for the X-axis ("Top" or" Bottom").
eAxisPosition
eAxisPosition
None
YAxisTitleText
Specifies a title for the Y-axis.
String
String
None
YAxisTitleBold
Sets the Y-axis title in bold face.
SwitchParameter
SwitchParameter
False
YAxisTitleSize
Sets the font size for the Y-axis title.
Object
Object
None
YAxisNumberformat
A number formatting string, like "#,##0.00", for numbers on the Y-axis
String
String
None
YMajorUnit
Spacing for the major gridlines / tick marks on the Y-axis.
Object
Object
None
YMinorUnit
Spacing for the minor gridlines / tick marks on the Y-axis.
Object
Object
None
YMaxValue
Maximum value on the Y-axis.
Object
Object
None
YMinValue
Minimum value on the Y-axis.
Object
Object
None
YAxisPosition
Position for the Y-axis ("Left" or "Right").
eAxisPosition
eAxisPosition
None
-------------------------- EXAMPLE 1 --------------------------
PS\> $cDef = New-ExcelChartDefinition -ChartType line -XRange "X" -YRange "Sinx" -Title "Graph of Sine X" -TitleBold -TitleSize 14 -Column 2 -ColumnOffSetPixels 35 -Width 800 -XAxisTitleText "Degrees" -XAxisTitleBold -XAxisTitleSize 12 -XMajorUnit 30 -XMinorUnit 10 -XMinValue 0 -XMaxValue 361 -XAxisNumberformat "000" -YMinValue -1.25 -YMaxValue 1.25 -YMajorUnit 0.25 -YAxisNumberformat "0.00" -YAxisTitleText "Sine" -YAxisTitleBold -YAxisTitleSize 12 -SeriesHeader "Sin(x)" -LegendSize 8 -legendBold -LegendPosition Bottom
PS\> 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 is defined and the defintion stored in $cDef and then Export-Excel uses $cDef .
New-PivotTableDefinition
New
PivotTableDefinition
Creates PivotTable definitons for Export-Excel
Export-Excel allows a single PivotTable to be defined using the parameters -IncludePivotTable, -PivotColumns, -PivotRows, -PivotData, -PivotFilter, -PivotTotals, -PivotDataToColumn, -IncludePivotChart and -ChartType.
Its -PivotTableDefintion paramater allows multiple PivotTables to be defined, with additional parameters. New-PivotTableDefinition is a convenient way to build these definitions.
New-PivotTableDefinition
PivotTableName
Name for the new pivot table
This command previously had a typo - and has an alias to avoid breaking scripts This will be removed in a future release
Object
Object
None
SourceWorkSheet
Worksheet where the data is found
Object
Object
None
SourceRange
Address range in the worksheet e.g "A10:F20" - the first row must contain the column names to pivot by: if the range is not specified the whole source sheet will be used.
Object
Object
None
PivotRows
Fields to set as rows in the PivotTable
Object
Object
None
PivotData
A hash-table in form "FieldName"="Function", where function is one of Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP
Hashtable
Hashtable
None
PivotColumns
Fields to set as columns in the PivotTable
Object
Object
None
PivotFilter
Fields to use to filter in the PivotTable
Object
Object
None
PivotDataToColumn
If there are multiple datasets in a PivotTable, by default they are shown seperatate rows under the given row heading; this switch makes them seperate columns.
SwitchParameter
False
PivotTotals
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.
String
String
Both
NoTotalsInPivot
Included for compatibility - equivalent to -PivotTotals "None"
SwitchParameter
False
GroupDateRow
The name of a row field which should be grouped by parts of the date/time (ignored if GroupDateRow is not specified)
String
String
None
GroupDatePart
The Part(s) of the date to use in the grouping (ignored if GroupDateRow is not specified)
Years
Quarters
Months
Days
Hours
Minutes
Seconds
eDateGroupBy[]
eDateGroupBy[]
None
GroupNumericRow
The name of a row field which should be grouped by Number (e.g 0-99, 100-199, 200-299 )
String
String
None
GroupNumericMin
The starting point for grouping
Double
Double
0
GroupNumericMax
The endpoint for grouping
Double
Double
1.79769313486232E+308
GroupNumericInterval
The interval for grouping
Double
Double
100
PivotNumberFormat
Number format to apply to the data cells in the PivotTable
String
String
None
PivotTableStyle
Apply a table style to the PivotTable
None
Custom
Light1
Light2
Light3
Light4
Light5
Light6
Light7
Light8
Light9
Light10
Light11
Light12
Light13
Light14
Light15
Light16
Light17
Light18
Light19
Light20
Light21
Medium1
Medium2
Medium3
Medium4
Medium5
Medium6
Medium7
Medium8
Medium9
Medium10
Medium11
Medium12
Medium13
Medium14
Medium15
Medium16
Medium17
Medium18
Medium19
Medium20
Medium21
Medium22
Medium23
Medium24
Medium25
Medium26
Medium27
Medium28
Dark1
Dark2
Dark3
Dark4
Dark5
Dark6
Dark7
Dark8
Dark9
Dark10
Dark11
TableStyles
TableStyles
None
PivotChartDefinition
Use a chart definition instead of specifying chart settings one by one
Object
Object
None
Activate
If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified
SwitchParameter
False
New-PivotTableDefinition
PivotTableName
Name for the new pivot table
This command previously had a typo - and has an alias to avoid breaking scripts This will be removed in a future release
Object
Object
None
SourceWorkSheet
Worksheet where the data is found
Object
Object
None
SourceRange
Address range in the worksheet e.g "A10:F20" - the first row must contain the column names to pivot by: if the range is not specified the whole source sheet will be used.
Object
Object
None
PivotRows
Fields to set as rows in the PivotTable
Object
Object
None
PivotData
A hash-table in form "FieldName"="Function", where function is one of Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP
Hashtable
Hashtable
None
PivotColumns
Fields to set as columns in the PivotTable
Object
Object
None
PivotFilter
Fields to use to filter in the PivotTable
Object
Object
None
PivotDataToColumn
If there are multiple datasets in a PivotTable, by default they are shown seperatate rows under the given row heading; this switch makes them seperate columns.
SwitchParameter
False
PivotTotals
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.
String
String
Both
NoTotalsInPivot
Included for compatibility - equivalent to -PivotTotals "None"
SwitchParameter
False
GroupDateRow
The name of a row field which should be grouped by parts of the date/time (ignored if GroupDateRow is not specified)
String
String
None
GroupDatePart
The Part(s) of the date to use in the grouping (ignored if GroupDateRow is not specified)
Years
Quarters
Months
Days
Hours
Minutes
Seconds
eDateGroupBy[]
eDateGroupBy[]
None
GroupNumericRow
The name of a row field which should be grouped by Number (e.g 0-99, 100-199, 200-299 )
String
String
None
GroupNumericMin
The starting point for grouping
Double
Double
0
GroupNumericMax
The endpoint for grouping
Double
Double
1.79769313486232E+308
GroupNumericInterval
The interval for grouping
Double
Double
100
PivotNumberFormat
Number format to apply to the data cells in the PivotTable
String
String
None
PivotTableStyle
Apply a table style to the PivotTable
None
Custom
Light1
Light2
Light3
Light4
Light5
Light6
Light7
Light8
Light9
Light10
Light11
Light12
Light13
Light14
Light15
Light16
Light17
Light18
Light19
Light20
Light21
Medium1
Medium2
Medium3
Medium4
Medium5
Medium6
Medium7
Medium8
Medium9
Medium10
Medium11
Medium12
Medium13
Medium14
Medium15
Medium16
Medium17
Medium18
Medium19
Medium20
Medium21
Medium22
Medium23
Medium24
Medium25
Medium26
Medium27
Medium28
Dark1
Dark2
Dark3
Dark4
Dark5
Dark6
Dark7
Dark8
Dark9
Dark10
Dark11
TableStyles
TableStyles
None
IncludePivotChart
If specified a chart Will be included.
SwitchParameter
False
ChartTitle
Optional title for the pivot chart, by default the title omitted.
String
String
None
ChartHeight
Height of the chart in Pixels (400 by default)
Int32
Int32
400
ChartWidth
Width of the chart in Pixels (600 by default)
Int32
Int32
600
ChartRow
Cell position of the top left corner of the chart, there will be this number of rows above the top edge of the chart (default is 0, chart starts at top edge of row 1).
Int32
Int32
0
ChartColumn
Cell position of the top left corner of the chart, there will be this number of cells to the left of the chart (default is 4, chart starts at left edge of column E)
Int32
Int32
4
ChartRowOffSetPixels
Vertical offset of the chart from the cell corner.
Int32
Int32
0
ChartColumnOffSetPixels
Horizontal offset of the chart from the cell corner.
Int32
Int32
0
ChartType
Type of chart
Area
Line
Pie
Bubble
ColumnClustered
ColumnStacked
ColumnStacked100
ColumnClustered3D
ColumnStacked3D
ColumnStacked1003D
BarClustered
BarStacked
BarStacked100
BarClustered3D
BarStacked3D
BarStacked1003D
LineStacked
LineStacked100
LineMarkers
LineMarkersStacked
LineMarkersStacked100
PieOfPie
PieExploded
PieExploded3D
BarOfPie
XYScatterSmooth
XYScatterSmoothNoMarkers
XYScatterLines
XYScatterLinesNoMarkers
AreaStacked
AreaStacked100
AreaStacked3D
AreaStacked1003D
DoughnutExploded
RadarMarkers
RadarFilled
Surface
SurfaceWireframe
SurfaceTopView
SurfaceTopViewWireframe
Bubble3DEffect
StockHLC
StockOHLC
StockVHLC
StockVOHLC
CylinderColClustered
CylinderColStacked
CylinderColStacked100
CylinderBarClustered
CylinderBarStacked
CylinderBarStacked100
CylinderCol
ConeColClustered
ConeColStacked
ConeColStacked100
ConeBarClustered
ConeBarStacked
ConeBarStacked100
ConeCol
PyramidColClustered
PyramidColStacked
PyramidColStacked100
PyramidBarClustered
PyramidBarStacked
PyramidBarStacked100
PyramidCol
XYScatter
Radar
Doughnut
Pie3D
Line3D
Column3D
Area3D
eChartType
eChartType
Pie
NoLegend
If specified hides the chart legend
SwitchParameter
False
ShowCategory
if specified attaches the category to slices in a pie chart : not supported on all chart types, this may give errors if applied to an unsupported type.
SwitchParameter
False
ShowPercent
If specified attaches percentages to slices in a pie chart.
SwitchParameter
False
Activate
If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified
SwitchParameter
False
PivotTableName
Name for the new pivot table
This command previously had a typo - and has an alias to avoid breaking scripts This will be removed in a future release
Object
Object
None
SourceWorkSheet
Worksheet where the data is found
Object
Object
None
SourceRange
Address range in the worksheet e.g "A10:F20" - the first row must contain the column names to pivot by: if the range is not specified the whole source sheet will be used.
Object
Object
None
PivotRows
Fields to set as rows in the PivotTable
Object
Object
None
PivotData
A hash-table in form "FieldName"="Function", where function is one of Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP
Hashtable
Hashtable
None
PivotColumns
Fields to set as columns in the PivotTable
Object
Object
None
PivotFilter
Fields to use to filter in the PivotTable
Object
Object
None
PivotDataToColumn
If there are multiple datasets in a PivotTable, by default they are shown seperatate rows under the given row heading; this switch makes them seperate columns.
SwitchParameter
SwitchParameter
False
PivotTotals
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.
String
String
Both
NoTotalsInPivot
Included for compatibility - equivalent to -PivotTotals "None"
SwitchParameter
SwitchParameter
False
GroupDateRow
The name of a row field which should be grouped by parts of the date/time (ignored if GroupDateRow is not specified)
String
String
None
GroupDatePart
The Part(s) of the date to use in the grouping (ignored if GroupDateRow is not specified)
eDateGroupBy[]
eDateGroupBy[]
None
GroupNumericRow
The name of a row field which should be grouped by Number (e.g 0-99, 100-199, 200-299 )
String
String
None
GroupNumericMin
The starting point for grouping
Double
Double
0
GroupNumericMax
The endpoint for grouping
Double
Double
1.79769313486232E+308
GroupNumericInterval
The interval for grouping
Double
Double
100
PivotNumberFormat
Number format to apply to the data cells in the PivotTable
String
String
None
PivotTableStyle
Apply a table style to the PivotTable
TableStyles
TableStyles
None
PivotChartDefinition
Use a chart definition instead of specifying chart settings one by one
Object
Object
None
IncludePivotChart
If specified a chart Will be included.
SwitchParameter
SwitchParameter
False
ChartTitle
Optional title for the pivot chart, by default the title omitted.
String
String
None
ChartHeight
Height of the chart in Pixels (400 by default)
Int32
Int32
400
ChartWidth
Width of the chart in Pixels (600 by default)
Int32
Int32
600
ChartRow
Cell position of the top left corner of the chart, there will be this number of rows above the top edge of the chart (default is 0, chart starts at top edge of row 1).
Int32
Int32
0
ChartColumn
Cell position of the top left corner of the chart, there will be this number of cells to the left of the chart (default is 4, chart starts at left edge of column E)
Int32
Int32
4
ChartRowOffSetPixels
Vertical offset of the chart from the cell corner.
Int32
Int32
0
ChartColumnOffSetPixels
Horizontal offset of the chart from the cell corner.
Int32
Int32
0
ChartType
Type of chart
eChartType
eChartType
Pie
NoLegend
If specified hides the chart legend
SwitchParameter
SwitchParameter
False
ShowCategory
if specified attaches the category to slices in a pie chart : not supported on all chart types, this may give errors if applied to an unsupported type.
SwitchParameter
SwitchParameter
False
ShowPercent
If specified attaches percentages to slices in a pie chart.
SwitchParameter
SwitchParameter
False
Activate
If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified
SwitchParameter
SwitchParameter
False
-------------------------- EXAMPLE 1 --------------------------
PS\> $pt = New-PivotTableDefinition -PivotTableName "PT1" -SourceWorkSheet "Sheet1" -PivotRows "Status" -PivotData @{Status='Count'} -PivotFilter 'StartType' -IncludePivotChart -ChartType BarClustered3D
PS\> $Pt += New-PivotTableDefinition -PivotTableName "PT2" -SourceWorkSheet "Sheet2" -PivotRows "Company" -PivotData @{Company='Count'} -IncludePivotChart -ChartType PieExploded3D -ShowPercent -ChartTitle "Breakdown of processes by company"
PS\> Get-Service | Select-Object -Property Status,Name,DisplayName,StartType | Export-Excel -Path .\test.xlsx -AutoSize
PS\> Get-Process | Select-Object -Property Name,Company,Handles,CPU,VM | Export-Excel -Path .\test.xlsx -AutoSize -WorksheetName 'sheet2'
PS\> $excel = Export-Excel -Path .\test.xlsx -PivotTableDefinition $pt -Show
This is a re-work of one of the examples in Export-Excel - instead of writing out the pivot definition hash-table, it is built by calling New-PivotTableDefinition.
Open-ExcelPackage
Open
ExcelPackage
Returns an ExcelPackage object for the specified XLSX file.
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-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.
Open-ExcelPackage
Path
The path to the file to open.
Object
Object
None
Password
The password for a protected worksheet, as a [normal] string (not a secure string).
String
String
None
KillExcel
If specified, any running instances of Excel will be terminated before opening the file. This may result in lost work, so should be used with caution.
SwitchParameter
False
Create
By default Open-ExcelPackage will only open an existing file; -Create instructs it to create a new file if required.
SwitchParameter
False
Path
The path to the file to open.
Object
Object
None
KillExcel
If specified, any running instances of Excel will be terminated before opening the file. This may result in lost work, so should be used with caution.
SwitchParameter
SwitchParameter
False
Password
The password for a protected worksheet, as a [normal] string (not a secure string).
String
String
None
Create
By default Open-ExcelPackage will only open an existing file; -Create instructs it to create a new file if required.
SwitchParameter
SwitchParameter
False
OfficeOpenXml.ExcelPackage
-------------------------- EXAMPLE 1 --------------------------
PS\> $excel = Open-ExcelPackage -Path "$env:TEMP\test99.xlsx" -Create
PS\> $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"
-------------------------- EXAMPLE 2 --------------------------
PS\> $excela= Open-ExcelPackage -path "$xlPath" -Password $password
PS\> $sheet1 = $excel.Workbook.Worksheetsa"sheet1" ]
PS\> Set-ExcelRange -Range $sheet1.Cells ["E1:S1048576" ], $sheet1.Cells ["V1:V1048576" ] -NFormat ( [cultureinfo ]::CurrentCulture.DateTimeFormat.ShortDatePattern)
PS\> 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.
Remove-WorkSheet
Remove
WorkSheet
Removes one or more worksheets from one or more workbooks
Remove-WorkSheet
FullName
The fully qualified path to the XLSX file(s)
Object
Object
None
WorksheetName
The worksheet to be removed (sheet1 by default)
String[]
String[]
Sheet1
Show
If specified the file will be opened in excel after the sheet is removed.
SwitchParameter
False
WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
SwitchParameter
False
Confirm
Prompts you for confirmation before running the cmdlet.
SwitchParameter
False
FullName
The fully qualified path to the XLSX file(s)
Object
Object
None
WorksheetName
The worksheet to be removed (sheet1 by default)
String[]
String[]
Sheet1
Show
If specified the file will be opened in excel after the sheet is removed.
SwitchParameter
SwitchParameter
False
WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
SwitchParameter
SwitchParameter
False
Confirm
Prompts you for confirmation before running the cmdlet.
SwitchParameter
SwitchParameter
False
-------------------------- EXAMPLE 1 --------------------------
PS\> Remove-WorkSheet -Path Test1.xlsx -WorksheetName Sheet1
Removes the worksheet named 'Sheet1' from 'Test1.xlsx'
-------------------------- EXAMPLE 2 --------------------------
PS\> Remove-WorkSheet -Path Test1.xlsx -WorksheetName Sheet1,Target1
Removes the worksheet named 'Sheet1' and 'Target1' from 'Test1.xlsx'
-------------------------- EXAMPLE 3 --------------------------
PS\> Remove-WorkSheet -Path Test1.xlsx -WorksheetName Sheet1,Target1 -Show
Removes the worksheets and then launches the xlsx in Excel
-------------------------- EXAMPLE 1 --------------------------
PS\> dir c:\reports\*.xlsx | Remove-WorkSheet
Removes 'Sheet1' from all the xlsx files in the c:\reports directory
Select-Worksheet
Select
Worksheet
Sets the selected tab in an Excel workbook to be the chosen sheet and unselects all the others.
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 which sheet is the selected tab when Excel opens the file.
Select-Worksheet
ExcelPackage
An object representing an ExcelPackage.
ExcelPackage
ExcelPackage
None
WorksheetName
The name of the worksheet "Sheet1" by default.
String
String
None
Select-Worksheet
ExcelWorkbook
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.
ExcelWorkbook
ExcelWorkbook
None
WorksheetName
The name of the worksheet "Sheet1" by default.
String
String
None
Select-Worksheet
ExcelWorksheet
An object representing an Excel worksheet.
ExcelWorksheet
ExcelWorksheet
None
ExcelPackage
An object representing an ExcelPackage.
ExcelPackage
ExcelPackage
None
ExcelWorkbook
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.
ExcelWorkbook
ExcelWorkbook
None
WorksheetName
The name of the worksheet "Sheet1" by default.
String
String
None
ExcelWorksheet
An object representing an Excel worksheet.
ExcelWorksheet
ExcelWorksheet
None
-------------------------- EXAMPLE 1 --------------------------
PS\> Select-Worksheet -ExcelWorkbook $ExcelWorkbook -WorksheetName "NewSheet"
$ExcelWorkbook holds a workbook object containing a sheet named "NewSheet"; This sheet will become the [only] active sheet in the workbook
-------------------------- EXAMPLE 2 --------------------------
PS\> Select-Worksheet -ExcelPackage $Pkg -WorksheetName "NewSheet2"
$pkg holds an Excel Package, whose workbook contains a sheet named "NewSheet2" This sheet will become the [only] active sheet in the workbook.
-------------------------- EXAMPLE 3 --------------------------
PS\> Select-Worksheet -ExcelWorksheet $ws
$ws holds an Excel worksheet which will become the [only] active sheet in its workbook.
Send-SQLDataToExcel
Send
SQLDataToExcel
Inserts a DataTable - returned by a SQL query - into an ExcelSheet
This command takes a SQL statement and run it against a database connection; for the connection it accepts either
* an object representing a session with a SQL server or ODBC database, or
* a connection string to make a session (if -MSSQLServer is specified it uses the SQL Native client,
and -Connection can be a server name instead of a detailed connection string. Without this switch it uses ODBC)
The command takes all the parameters of Export-Excel, except for -InputObject (alias TargetData); after fetching the data it calls Export-Excel with the data as the value of InputParameter and whichever of Export-Excel's parameters it was passed; for details of these parameters see the help for Export-Excel.
Send-SQLDataToExcel
Connection
A database connection string to be used to create a database session; either
* A Data source name written in the form DSN=ODBC_Data_Source_Name, or
* A full ODBC or SQL Native Client Connection string, or
* The name of a SQL server.
Object
Object
None
SQL
The SQL query to run against the session which was passed in -Session or set up from -Connection.
String
String
None
QueryTimeout
Override the default query time of 30 seconds.
Int32
Int32
0
Force
If specified Export-Excel will be called with parameters specified, even if there is no data to send
SwitchParameter
False
Send-SQLDataToExcel
Connection
A database connection string to be used to create a database session; either
* A Data source name written in the form DSN=ODBC_Data_Source_Name, or
* A full ODBC or SQL Native Client Connection string, or
* The name of a SQL server.
Object
Object
None
MsSQLserver
Specifies the connection string is for SQL server, not ODBC.
SwitchParameter
False
DataBase
Switches to a specific database on a SQL server.
String
String
None
SQL
The SQL query to run against the session which was passed in -Session or set up from -Connection.
String
String
None
QueryTimeout
Override the default query time of 30 seconds.
Int32
Int32
0
Force
If specified Export-Excel will be called with parameters specified, even if there is no data to send
SwitchParameter
False
Send-SQLDataToExcel
Session
An active ODBC Connection or SQL connection object representing a session with a database which will be queried to get the data .
Object
Object
None
SQL
The SQL query to run against the session which was passed in -Session or set up from -Connection.
String
String
None
QueryTimeout
Override the default query time of 30 seconds.
Int32
Int32
0
Force
If specified Export-Excel will be called with parameters specified, even if there is no data to send
SwitchParameter
False
Send-SQLDataToExcel
QueryTimeout
Override the default query time of 30 seconds.
Int32
Int32
0
DataTable
A System.Data.DataTable object containing the data to be inserted into the spreadsheet without running a query. This remains supported to avoid breaking older scripts, but if you have a DataTable object you can pass the it into Export-Excel using -InputObject.
DataTable
DataTable
None
Force
If specified Export-Excel will be called with parameters specified, even if there is no data to send
SwitchParameter
False
Connection
A database connection string to be used to create a database session; either
* A Data source name written in the form DSN=ODBC_Data_Source_Name, or
* A full ODBC or SQL Native Client Connection string, or
* The name of a SQL server.
Object
Object
None
Session
An active ODBC Connection or SQL connection object representing a session with a database which will be queried to get the data .
Object
Object
None
MsSQLserver
Specifies the connection string is for SQL server, not ODBC.
SwitchParameter
SwitchParameter
False
DataBase
Switches to a specific database on a SQL server.
String
String
None
SQL
The SQL query to run against the session which was passed in -Session or set up from -Connection.
String
String
None
QueryTimeout
Override the default query time of 30 seconds.
Int32
Int32
0
DataTable
A System.Data.DataTable object containing the data to be inserted into the spreadsheet without running a query. This remains supported to avoid breaking older scripts, but if you have a DataTable object you can pass the it into Export-Excel using -InputObject.
DataTable
DataTable
None
Force
If specified Export-Excel will be called with parameters specified, even if there is no data to send
SwitchParameter
SwitchParameter
False
-------------------------- EXAMPLE 1 --------------------------
PS\> 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 2 --------------------------
PS\> $dbPath = 'C:\Users\James\Documents\Database1.accdb'
PS\> $Connection = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=$dbPath;"
PS\> $SQL="SELECT top 25 Name,Length From TestData ORDER BY Length DESC"
PS\> Send-SQLDataToExcel -Connection $connection -SQL $sql -path .\demo1.xlsx -WorkSheetname "Sizes" -AutoSize
This creates an ODBC connection string to read from an Access file and a SQL Statement to extracts data from it, and sends the resulting data to a new worksheet
-------------------------- EXAMPLE 3 --------------------------
PS\> $dbPath = 'C:\users\James\Documents\f1Results.xlsx'
PS\> $Connection = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};Dbq=$dbPath;"
PS\> $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"
PS\>Send-SQLDataToExcel -Connection $connection -SQL $sql -path .\demo2.xlsx -WorkSheetname "Winners" -AutoSize -AutoNameRange -ConditionalFormat @{DataBarColor="Blue"; Range="Wins"}
Similar to the previous example, this creates a connection string, this time for an Excel file, and runs a SQL statement to get a list of motor-racing results, outputting 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 4 --------------------------
PS\> $dbPath = 'C:\users\James\Documents\f1Results.xlsx'
PS\> $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"
PS\> $null = Get-SQL -Session F1 -excel -Connection $dbPath -sql $sql -OutputVariable Table
PS\> 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 PowerShell gallery with Install-Module -Name GetSQL - (note the function is Get-SQL the module is GetSQL without the "-" )
Get-SQL simplifies making database connections and building /submitting SQL statements. Here Get-SQL uses the same SQL statement as before; -OutputVariable leaves a System.Data.DataTable object in $table and Send-SQLDataToExcel puts $table into the worksheet and sets it as an Excel table. The command is equivalent to running
PS> Export-Excel -inputObject $Table -Path ".\demo3.xlsx" -WorkSheetname Gpwinners -autosize -TableName winners -TableStyle Light6 -show
This is quicker than using PS> Get-SQL <parameters> | export-excel -ExcludeProperty rowerror,rowstate,table,itemarray,haserrors <parameters>
(the F1 results database is available from https://1drv.ms/x/s!AhfYu7-CJv4ehNdZWxJE9LMAX_N5sg )
-------------------------- EXAMPLE 5 --------------------------
PS\>$SQL = "SELECT top 25 DriverName, Count(Win) as Wins FROM Results GROUP BY DriverName ORDER BY (count(win)) DESC"
PS\> Send-SQLDataToExcel -Session $DbSessions\["f1"\] -SQL $sql -Path ".\demo3.xlsx" -WorkSheetname Gpwinners -ClearSheet -autosize -ColumnChart
Like the previous example, this uses Get-SQL (download from the gallery with Install-Module -Name GetSQL). It uses the database session which Get-SQL created, rather than an ODBC connection string. The Session parameter can either be a object (as shown here), or the name used by Get-SQL ("F1" in this case).
Here the data is presented as a quick chart.
-------------------------- EXAMPLE 6 --------------------------
Send-SQLDataToExcel -path .\demo4.xlsx -WorkSheetname "LR" -Connection "DSN=LR" -sql "SELECT name AS CollectionName FROM AgLibraryCollection Collection ORDER BY CollectionName"
This example uses an Existing ODBC datasource name "LR" which maps to an adobe lightroom database and gets a list of collection names into a worksheet
Export-Excel
Set-ExcelColumn
Set
ExcelColumn
Adds or modifies a column in an Excel worksheet, filling values, setting formatting and/or creating named ranges.
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.
Set-ExcelColumn
ExcelPackage
If specifying the worksheet by name, the ExcelPackage object which contains the worksheet also needs to be passed.
ExcelPackage
ExcelPackage
None
Worksheetname
The sheet to update can be given as a name or an Excel Worksheet object - this sets it by name.
String
String
Sheet1
Column
Column to fill down - the first column is 1. 0 will be interpreted as first empty column.
Object
Object
0
StartRow
First row to fill data in.
Int32
Int32
0
Value
A value, formula or scriptblock to fill in. A script block can use $worksheet, $row, $column [number], $columnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn.
Object
Object
None
Heading
Optional column heading.
Object
Object
None
NumberFormat
Number format to apply to cells for example "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" or "0.0E+0" etc.
Object
Object
None
BorderAround
Style of border to draw around the row.
None
Hair
Dotted
DashDot
Thin
DashDotDot
Dashed
MediumDashDotDot
MediumDashed
MediumDashDot
Thick
Medium
Double
ExcelBorderStyle
ExcelBorderStyle
None
FontColor
Colour for the text - if none specified it will be left as it it is.
Object
Object
None
Bold
Make text bold; use -Bold:$false to remove bold.
SwitchParameter
False
Italic
Make text italic; use -Italic:$false to remove italic.
SwitchParameter
False
Underline
Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining.
SwitchParameter
False
UnderLineType
Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single".
None
Single
Double
SingleAccounting
DoubleAccounting
ExcelUnderLineType
ExcelUnderLineType
Single
StrikeThru
Strike through text; use -StrikeThru:$false to remove strike through.
SwitchParameter
False
FontShift
Subscript or Superscript (or None).
None
Baseline
Subscript
Superscript
ExcelVerticalAlignmentFont
ExcelVerticalAlignmentFont
None
FontName
Font to use - Excel defaults to Calibri.
String
String
None
FontSize
Point size for the text.
Single
Single
0
BackgroundColor
Change background color.
Object
Object
None
BackgroundPattern
Background pattern - "Solid" by default.
None
Solid
DarkGray
MediumGray
LightGray
Gray125
Gray0625
DarkVertical
DarkHorizontal
DarkDown
DarkUp
DarkGrid
DarkTrellis
LightVertical
LightHorizontal
LightDown
LightUp
LightGrid
LightTrellis
ExcelFillStyle
ExcelFillStyle
Solid
PatternColor
Secondary color for background pattern.
Object
Object
None
WrapText
Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping.
SwitchParameter
False
HorizontalAlignment
Position cell contents to Left, Right, Center etc. Default is "General".
General
Left
Center
CenterContinuous
Right
Fill
Distributed
Justify
ExcelHorizontalAlignment
ExcelHorizontalAlignment
None
VerticalAlignment
Position cell contents to Top, Bottom or Center.
Top
Center
Bottom
Distributed
Justify
ExcelVerticalAlignment
ExcelVerticalAlignment
None
TextRotation
Degrees to rotate text; up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise.
Int32
Int32
0
AutoSize
Attempt to auto-fit cells to the width their contents.
SwitchParameter
False
Width
Set cells to a fixed width, ignored if -AutoSize is specified.
Single
Single
0
AutoNameRange
Set the inserted data to be a named range.
SwitchParameter
False
Hide
Hide the column.
SwitchParameter
False
Specified
If specified, returns the range of cells which were affected.
SwitchParameter
False
PassThru
If specified, return an object representing the Column, to allow further work to be done on it.
SwitchParameter
False
Set-ExcelColumn
Worksheet
This passes the worksheet object instead of passing a sheet name and an Excelpackage object.
ExcelWorksheet
ExcelWorksheet
None
Column
Column to fill down - the first column is 1. 0 will be interpreted as first empty column.
Object
Object
0
StartRow
First row to fill data in.
Int32
Int32
0
Value
A value, formula or scriptblock to fill in. A script block can use $worksheet, $row, $column [number], $columnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn.
Object
Object
None
Heading
Optional column heading.
Object
Object
None
NumberFormat
Number format to apply to cells for example "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" or "0.0E+0" etc.
Object
Object
None
BorderAround
Style of border to draw around the row.
None
Hair
Dotted
DashDot
Thin
DashDotDot
Dashed
MediumDashDotDot
MediumDashed
MediumDashDot
Thick
Medium
Double
ExcelBorderStyle
ExcelBorderStyle
None
FontColor
Colour for the text - if none specified it will be left as it it is.
Object
Object
None
Bold
Make text bold; use -Bold:$false to remove bold.
SwitchParameter
False
Italic
Make text italic; use -Italic:$false to remove italic.
SwitchParameter
False
Underline
Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining.
SwitchParameter
False
UnderLineType
Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single".
None
Single
Double
SingleAccounting
DoubleAccounting
ExcelUnderLineType
ExcelUnderLineType
Single
StrikeThru
Strike through text; use -StrikeThru:$false to remove strike through.
SwitchParameter
False
FontShift
Subscript or Superscript (or None).
None
Baseline
Subscript
Superscript
ExcelVerticalAlignmentFont
ExcelVerticalAlignmentFont
None
FontName
Font to use - Excel defaults to Calibri.
String
String
None
FontSize
Point size for the text.
Single
Single
0
BackgroundColor
Change background color.
Object
Object
None
BackgroundPattern
Background pattern - "Solid" by default.
None
Solid
DarkGray
MediumGray
LightGray
Gray125
Gray0625
DarkVertical
DarkHorizontal
DarkDown
DarkUp
DarkGrid
DarkTrellis
LightVertical
LightHorizontal
LightDown
LightUp
LightGrid
LightTrellis
ExcelFillStyle
ExcelFillStyle
Solid
PatternColor
Secondary color for background pattern.
Object
Object
None
WrapText
Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping.
SwitchParameter
False
HorizontalAlignment
Position cell contents to Left, Right, Center etc. Default is "General".
General
Left
Center
CenterContinuous
Right
Fill
Distributed
Justify
ExcelHorizontalAlignment
ExcelHorizontalAlignment
None
VerticalAlignment
Position cell contents to Top, Bottom or Center.
Top
Center
Bottom
Distributed
Justify
ExcelVerticalAlignment
ExcelVerticalAlignment
None
TextRotation
Degrees to rotate text; up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise.
Int32
Int32
0
AutoSize
Attempt to auto-fit cells to the width their contents.
SwitchParameter
False
Width
Set cells to a fixed width, ignored if -AutoSize is specified.
Single
Single
0
AutoNameRange
Set the inserted data to be a named range.
SwitchParameter
False
Hide
Hide the column.
SwitchParameter
False
Specified
If specified, returns the range of cells which were affected.
SwitchParameter
False
PassThru
If specified, return an object representing the Column, to allow further work to be done on it.
SwitchParameter
False
ExcelPackage
If specifying the worksheet by name, the ExcelPackage object which contains the worksheet also needs to be passed.
ExcelPackage
ExcelPackage
None
Worksheetname
The sheet to update can be given as a name or an Excel Worksheet object - this sets it by name.
String
String
Sheet1
Worksheet
This passes the worksheet object instead of passing a sheet name and an Excelpackage object.
ExcelWorksheet
ExcelWorksheet
None
Column
Column to fill down - the first column is 1. 0 will be interpreted as first empty column.
Object
Object
0
StartRow
First row to fill data in.
Int32
Int32
0
Value
A value, formula or scriptblock to fill in. A script block can use $worksheet, $row, $column [number], $columnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn.
Object
Object
None
Heading
Optional column heading.
Object
Object
None
NumberFormat
Number format to apply to cells for example "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" or "0.0E+0" etc.
Object
Object
None
BorderAround
Style of border to draw around the row.
ExcelBorderStyle
ExcelBorderStyle
None
FontColor
Colour for the text - if none specified it will be left as it it is.
Object
Object
None
Bold
Make text bold; use -Bold:$false to remove bold.
SwitchParameter
SwitchParameter
False
Italic
Make text italic; use -Italic:$false to remove italic.
SwitchParameter
SwitchParameter
False
Underline
Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining.
SwitchParameter
SwitchParameter
False
UnderLineType
Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single".
ExcelUnderLineType
ExcelUnderLineType
Single
StrikeThru
Strike through text; use -StrikeThru:$false to remove strike through.
SwitchParameter
SwitchParameter
False
FontShift
Subscript or Superscript (or None).
ExcelVerticalAlignmentFont
ExcelVerticalAlignmentFont
None
FontName
Font to use - Excel defaults to Calibri.
String
String
None
FontSize
Point size for the text.
Single
Single
0
BackgroundColor
Change background color.
Object
Object
None
BackgroundPattern
Background pattern - "Solid" by default.
ExcelFillStyle
ExcelFillStyle
Solid
PatternColor
Secondary color for background pattern.
Object
Object
None
WrapText
Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping.
SwitchParameter
SwitchParameter
False
HorizontalAlignment
Position cell contents to Left, Right, Center etc. Default is "General".
ExcelHorizontalAlignment
ExcelHorizontalAlignment
None
VerticalAlignment
Position cell contents to Top, Bottom or Center.
ExcelVerticalAlignment
ExcelVerticalAlignment
None
TextRotation
Degrees to rotate text; up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise.
Int32
Int32
0
AutoSize
Attempt to auto-fit cells to the width their contents.
SwitchParameter
SwitchParameter
False
Width
Set cells to a fixed width, ignored if -AutoSize is specified.
Single
Single
0
AutoNameRange
Set the inserted data to be a named range.
SwitchParameter
SwitchParameter
False
Hide
Hide the column.
SwitchParameter
SwitchParameter
False
Specified
If specified, returns the range of cells which were affected.
SwitchParameter
SwitchParameter
False
PassThru
If specified, return an object representing the Column, to allow further work to be done on it.
SwitchParameter
SwitchParameter
False
OfficeOpenXml.ExcelColumn
System.String
-------------------------- EXAMPLE 1 --------------------------
PS\> 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 the names of predefined number formats.
You can see how currency is interpreted on the local computer with the command Expand-NumberFormat currency
-------------------------- EXAMPLE 2 --------------------------
PS\> Set-ExcelColumn -Worksheet $ws -Heading "WinsToFastLaps" -Value {"=E$row/C$row"} -Column 7 -AutoSize -AutoNameRange
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.
When a value begins with "=", it is treated as a formula.
If value is a script block it will be evaluated, so here the string "=E$row/C$Row" will have the number of the current row inserted; see the value parameter for a list of variables which can be used.
Note than when evaluating an expression in a string, it is necessary to wrap it in $() so $row is valid but $($row+1) is needed.
To preventVariables merging into other parts of the string, use the back tick "$columnName`4" will be "G4" - without the backtick the string will look for a variable named "columnName4"
-------------------------- EXAMPLE 3 --------------------------
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 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 --------------------------
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 and the rest of the column becomes the range.
Set-ExcelRange
Set
ExcelRange
Applies number, font, alignment and/or color formatting, values or formulas to a range of Excel cells.
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.
Set-ExcelRange
Range
One or more row(s), Column(s) and/or block(s) of cells to format.
Object
Object
None
WorkSheet
The worksheet where the format is to be applied.
ExcelWorksheet
ExcelWorksheet
None
NumberFormat
Number format to apply to cells for example "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" or "0.0E+0" etc.
Object
Object
None
BorderAround
Style of border to draw around the range.
None
Hair
Dotted
DashDot
Thin
DashDotDot
Dashed
MediumDashDotDot
MediumDashed
MediumDashDot
Thick
Medium
Double
ExcelBorderStyle
ExcelBorderStyle
None
BorderColor
Color of the border.
Object
Object
[System.Drawing.Color]::Black
BorderBottom
Style for the bottom border.
None
Hair
Dotted
DashDot
Thin
DashDotDot
Dashed
MediumDashDotDot
MediumDashed
MediumDashDot
Thick
Medium
Double
ExcelBorderStyle
ExcelBorderStyle
None
BorderTop
Style for the top border.
None
Hair
Dotted
DashDot
Thin
DashDotDot
Dashed
MediumDashDotDot
MediumDashed
MediumDashDot
Thick
Medium
Double
ExcelBorderStyle
ExcelBorderStyle
None
BorderLeft
Style for the left border.
None
Hair
Dotted
DashDot
Thin
DashDotDot
Dashed
MediumDashDotDot
MediumDashed
MediumDashDot
Thick
Medium
Double
ExcelBorderStyle
ExcelBorderStyle
None
BorderRight
Style for the right border.
None
Hair
Dotted
DashDot
Thin
DashDotDot
Dashed
MediumDashDotDot
MediumDashed
MediumDashDot
Thick
Medium
Double
ExcelBorderStyle
ExcelBorderStyle
None
FontColor
Colour for the text - if none is specified it will be left as it is.
Object
Object
None
Value
Value for the cell.
Object
Object
None
Formula
Formula for the cell.
Object
Object
None
ArrayFormula
Specifies formula should be an array formula (a.k.a CSE [ctrl-shift-enter] formula).
SwitchParameter
False
ResetFont
Clear Bold, Italic, StrikeThrough and Underline and set color to Black.
SwitchParameter
False
Bold
Make text bold; use -Bold:$false to remove bold.
SwitchParameter
False
Italic
Make text italic; use -Italic:$false to remove italic.
SwitchParameter
False
Underline
Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining.
SwitchParameter
False
UnderLineType
Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single".
None
Single
Double
SingleAccounting
DoubleAccounting
ExcelUnderLineType
ExcelUnderLineType
Single
StrikeThru
Strike through text; use -Strikethru:$false to remove Strike through
SwitchParameter
False
FontShift
Subscript or Superscript (or none).
None
Baseline
Subscript
Superscript
ExcelVerticalAlignmentFont
ExcelVerticalAlignmentFont
None
FontName
Font to use - Excel defaults to Calibri.
String
String
None
FontSize
Point size for the text.
Single
Single
0
BackgroundColor
Change background color.
Object
Object
None
BackgroundPattern
Background pattern - Solid by default.
None
Solid
DarkGray
MediumGray
LightGray
Gray125
Gray0625
DarkVertical
DarkHorizontal
DarkDown
DarkUp
DarkGrid
DarkTrellis
LightVertical
LightHorizontal
LightDown
LightUp
LightGrid
LightTrellis
ExcelFillStyle
ExcelFillStyle
Solid
PatternColor
Secondary color for background pattern.
Object
Object
None
WrapText
Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping.
SwitchParameter
False
HorizontalAlignment
Position cell contents to Left, Right, Center etc. default is 'General'.
General
Left
Center
CenterContinuous
Right
Fill
Distributed
Justify
ExcelHorizontalAlignment
ExcelHorizontalAlignment
None
VerticalAlignment
Position cell contents to Top, Bottom or Center.
Top
Center
Bottom
Distributed
Justify
ExcelVerticalAlignment
ExcelVerticalAlignment
None
TextRotation
Degrees to rotate text; up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise.
Int32
Int32
0
AutoSize
Autofit cells to width (columns or ranges only).
SwitchParameter
False
Width
Set cells to a fixed width (columns or ranges only), ignored if Autosize is specified.
Single
Single
0
Height
Set cells to a fixed height (rows or ranges only).
Single
Single
0
Hidden
Hide a row or column (not a range); use -Hidden:$false to unhide.
SwitchParameter
False
Locked
Locks cells. Cells are locked by default use -locked:$false on the whole sheet and then lock specific ones, and enable protection on the sheet.
SwitchParameter
False
Merge
Merges cells - it is recommended that you explicitly set -HorizontalAlignment
SwitchParameter
False
Range
One or more row(s), Column(s) and/or block(s) of cells to format.
Object
Object
None
WorkSheet
The worksheet where the format is to be applied.
ExcelWorksheet
ExcelWorksheet
None
NumberFormat
Number format to apply to cells for example "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" or "0.0E+0" etc.
Object
Object
None
BorderAround
Style of border to draw around the range.
ExcelBorderStyle
ExcelBorderStyle
None
BorderColor
Color of the border.
Object
Object
[System.Drawing.Color]::Black
BorderBottom
Style for the bottom border.
ExcelBorderStyle
ExcelBorderStyle
None
BorderTop
Style for the top border.
ExcelBorderStyle
ExcelBorderStyle
None
BorderLeft
Style for the left border.
ExcelBorderStyle
ExcelBorderStyle
None
BorderRight
Style for the right border.
ExcelBorderStyle
ExcelBorderStyle
None
FontColor
Colour for the text - if none is specified it will be left as it is.
Object
Object
None
Value
Value for the cell.
Object
Object
None
Formula
Formula for the cell.
Object
Object
None
ArrayFormula
Specifies formula should be an array formula (a.k.a CSE [ctrl-shift-enter] formula).
SwitchParameter
SwitchParameter
False
ResetFont
Clear Bold, Italic, StrikeThrough and Underline and set color to Black.
SwitchParameter
SwitchParameter
False
Bold
Make text bold; use -Bold:$false to remove bold.
SwitchParameter
SwitchParameter
False
Italic
Make text italic; use -Italic:$false to remove italic.
SwitchParameter
SwitchParameter
False
Underline
Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining.
SwitchParameter
SwitchParameter
False
UnderLineType
Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single".
ExcelUnderLineType
ExcelUnderLineType
Single
StrikeThru
Strike through text; use -Strikethru:$false to remove Strike through
SwitchParameter
SwitchParameter
False
FontShift
Subscript or Superscript (or none).
ExcelVerticalAlignmentFont
ExcelVerticalAlignmentFont
None
FontName
Font to use - Excel defaults to Calibri.
String
String
None
FontSize
Point size for the text.
Single
Single
0
BackgroundColor
Change background color.
Object
Object
None
BackgroundPattern
Background pattern - Solid by default.
ExcelFillStyle
ExcelFillStyle
Solid
PatternColor
Secondary color for background pattern.
Object
Object
None
WrapText
Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping.
SwitchParameter
SwitchParameter
False
HorizontalAlignment
Position cell contents to Left, Right, Center etc. default is 'General'.
ExcelHorizontalAlignment
ExcelHorizontalAlignment
None
VerticalAlignment
Position cell contents to Top, Bottom or Center.
ExcelVerticalAlignment
ExcelVerticalAlignment
None
TextRotation
Degrees to rotate text; up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise.
Int32
Int32
0
AutoSize
Autofit cells to width (columns or ranges only).
SwitchParameter
SwitchParameter
False
Width
Set cells to a fixed width (columns or ranges only), ignored if Autosize is specified.
Single
Single
0
Height
Set cells to a fixed height (rows or ranges only).
Single
Single
0
Hidden
Hide a row or column (not a range); use -Hidden:$false to unhide.
SwitchParameter
SwitchParameter
False
Locked
Locks cells. Cells are locked by default use -locked:$false on the whole sheet and then lock specific ones, and enable protection on the sheet.
SwitchParameter
SwitchParameter
False
Merge
Merges cells - it is recommended that you explicitly set -HorizontalAlignment
SwitchParameter
SwitchParameter
False
-------------------------- EXAMPLE 1 --------------------------
PS\> $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 numbers as a integers with comma-separated groups, aligns it right, and auto-fits the column to the contents.
-------------------------- EXAMPLE 2 --------------------------
PS\> 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.
-------------------------- EXAMPLE 3 --------------------------
PS\> 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.
Set-ExcelRow
Set
ExcelRow
Fills values into a [new] row in an Excel spreadsheet, and sets row formats.
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.
Set-ExcelRow
ExcelPackage
An Excel package object - for example from Export-Excel -PassThru - if specified requires a sheet name to be passed a parameter.
ExcelPackage
ExcelPackage
None
Worksheetname
The name of the sheet to update in the package.
Object
Object
Sheet1
Row
Row to fill right - first row is 1. 0 will be interpreted as first unused row.
Object
Object
0
StartColumn
Position in the row to start from.
Int32
Int32
0
Value
Value, Formula or ScriptBlock to fill in. A ScriptBlock can use $worksheet, $row, $Column [number], $ColumnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn.
Object
Object
None
Heading
Optional row-heading.
Object
Object
None
HeadingBold
Set the heading in bold type.
SwitchParameter
False
HeadingSize
Change the font-size of the heading.
Int32
Int32
0
NumberFormat
Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc.
Object
Object
None
BorderAround
Style of border to draw around the row.
None
Hair
Dotted
DashDot
Thin
DashDotDot
Dashed
MediumDashDotDot
MediumDashed
MediumDashDot
Thick
Medium
Double
ExcelBorderStyle
ExcelBorderStyle
None
BorderColor
Color of the border.
Object
Object
[System.Drawing.Color]::Black
BorderBottom
Style for the bottom border.
None
Hair
Dotted
DashDot
Thin
DashDotDot
Dashed
MediumDashDotDot
MediumDashed
MediumDashDot
Thick
Medium
Double
ExcelBorderStyle
ExcelBorderStyle
None
BorderTop
Style for the top border.
None
Hair
Dotted
DashDot
Thin
DashDotDot
Dashed
MediumDashDotDot
MediumDashed
MediumDashDot
Thick
Medium
Double
ExcelBorderStyle
ExcelBorderStyle
None
BorderLeft
Style for the left border.
None
Hair
Dotted
DashDot
Thin
DashDotDot
Dashed
MediumDashDotDot
MediumDashed
MediumDashDot
Thick
Medium
Double
ExcelBorderStyle
ExcelBorderStyle
None
BorderRight
Style for the right border.
None
Hair
Dotted
DashDot
Thin
DashDotDot
Dashed
MediumDashDotDot
MediumDashed
MediumDashDot
Thick
Medium
Double
ExcelBorderStyle
ExcelBorderStyle
None
FontColor
Color for the text - if not specified the font will be left as it it is.
Object
Object
None
Bold
Make text bold; use -Bold:$false to remove bold.
SwitchParameter
False
Italic
Make text italic; use -Italic:$false to remove italic.
SwitchParameter
False
Underline
Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining.
SwitchParameter
False
UnderLineType
Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single".
None
Single
Double
SingleAccounting
DoubleAccounting
ExcelUnderLineType
ExcelUnderLineType
Single
StrikeThru
Strike through text; use -StrikeThru:$false to remove strike through.
SwitchParameter
False
FontShift
Subscript or Superscript (or none).
None
Baseline
Subscript
Superscript
ExcelVerticalAlignmentFont
ExcelVerticalAlignmentFont
None
FontName
Font to use - Excel defaults to Calibri.
String
String
None
FontSize
Point size for the text.
Single
Single
0
BackgroundColor
Change background color.
Object
Object
None
BackgroundPattern
Background pattern - solid by default.
None
Solid
DarkGray
MediumGray
LightGray
Gray125
Gray0625
DarkVertical
DarkHorizontal
DarkDown
DarkUp
DarkGrid
DarkTrellis
LightVertical
LightHorizontal
LightDown
LightUp
LightGrid
LightTrellis
ExcelFillStyle
ExcelFillStyle
Solid
PatternColor
Secondary color for background pattern.
Object
Object
None
WrapText
Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping.
SwitchParameter
False
HorizontalAlignment
Position cell contents to Left, Right, Center etc. default is 'General'.
General
Left
Center
CenterContinuous
Right
Fill
Distributed
Justify
ExcelHorizontalAlignment
ExcelHorizontalAlignment
None
VerticalAlignment
Position cell contents to Top, Bottom or Center.
Top
Center
Bottom
Distributed
Justify
ExcelVerticalAlignment
ExcelVerticalAlignment
None
TextRotation
Degrees to rotate text. Up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise.
Int32
Int32
0
Height
Set cells to a fixed height.
Single
Single
0
Hide
Hide the row.
SwitchParameter
False
ReturnRange
If sepecified, returns the range of cells which were affected.
SwitchParameter
False
PassThru
If Specified, return a row object to allow further work to be done.
SwitchParameter
False
Set-ExcelRow
Worksheet
A worksheet object instead of passing a name and package.
ExcelWorksheet
ExcelWorksheet
None
Row
Row to fill right - first row is 1. 0 will be interpreted as first unused row.
Object
Object
0
StartColumn
Position in the row to start from.
Int32
Int32
0
Value
Value, Formula or ScriptBlock to fill in. A ScriptBlock can use $worksheet, $row, $Column [number], $ColumnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn.
Object
Object
None
Heading
Optional row-heading.
Object
Object
None
HeadingBold
Set the heading in bold type.
SwitchParameter
False
HeadingSize
Change the font-size of the heading.
Int32
Int32
0
NumberFormat
Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc.
Object
Object
None
BorderAround
Style of border to draw around the row.
None
Hair
Dotted
DashDot
Thin
DashDotDot
Dashed
MediumDashDotDot
MediumDashed
MediumDashDot
Thick
Medium
Double
ExcelBorderStyle
ExcelBorderStyle
None
BorderColor
Color of the border.
Object
Object
[System.Drawing.Color]::Black
BorderBottom
Style for the bottom border.
None
Hair
Dotted
DashDot
Thin
DashDotDot
Dashed
MediumDashDotDot
MediumDashed
MediumDashDot
Thick
Medium
Double
ExcelBorderStyle
ExcelBorderStyle
None
BorderTop
Style for the top border.
None
Hair
Dotted
DashDot
Thin
DashDotDot
Dashed
MediumDashDotDot
MediumDashed
MediumDashDot
Thick
Medium
Double
ExcelBorderStyle
ExcelBorderStyle
None
BorderLeft
Style for the left border.
None
Hair
Dotted
DashDot
Thin
DashDotDot
Dashed
MediumDashDotDot
MediumDashed
MediumDashDot
Thick
Medium
Double
ExcelBorderStyle
ExcelBorderStyle
None
BorderRight
Style for the right border.
None
Hair
Dotted
DashDot
Thin
DashDotDot
Dashed
MediumDashDotDot
MediumDashed
MediumDashDot
Thick
Medium
Double
ExcelBorderStyle
ExcelBorderStyle
None
FontColor
Color for the text - if not specified the font will be left as it it is.
Object
Object
None
Bold
Make text bold; use -Bold:$false to remove bold.
SwitchParameter
False
Italic
Make text italic; use -Italic:$false to remove italic.
SwitchParameter
False
Underline
Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining.
SwitchParameter
False
UnderLineType
Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single".
None
Single
Double
SingleAccounting
DoubleAccounting
ExcelUnderLineType
ExcelUnderLineType
Single
StrikeThru
Strike through text; use -StrikeThru:$false to remove strike through.
SwitchParameter
False
FontShift
Subscript or Superscript (or none).
None
Baseline
Subscript
Superscript
ExcelVerticalAlignmentFont
ExcelVerticalAlignmentFont
None
FontName
Font to use - Excel defaults to Calibri.
String
String
None
FontSize
Point size for the text.
Single
Single
0
BackgroundColor
Change background color.
Object
Object
None
BackgroundPattern
Background pattern - solid by default.
None
Solid
DarkGray
MediumGray
LightGray
Gray125
Gray0625
DarkVertical
DarkHorizontal
DarkDown
DarkUp
DarkGrid
DarkTrellis
LightVertical
LightHorizontal
LightDown
LightUp
LightGrid
LightTrellis
ExcelFillStyle
ExcelFillStyle
Solid
PatternColor
Secondary color for background pattern.
Object
Object
None
WrapText
Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping.
SwitchParameter
False
HorizontalAlignment
Position cell contents to Left, Right, Center etc. default is 'General'.
General
Left
Center
CenterContinuous
Right
Fill
Distributed
Justify
ExcelHorizontalAlignment
ExcelHorizontalAlignment
None
VerticalAlignment
Position cell contents to Top, Bottom or Center.
Top
Center
Bottom
Distributed
Justify
ExcelVerticalAlignment
ExcelVerticalAlignment
None
TextRotation
Degrees to rotate text. Up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise.
Int32
Int32
0
Height
Set cells to a fixed height.
Single
Single
0
Hide
Hide the row.
SwitchParameter
False
ReturnRange
If sepecified, returns the range of cells which were affected.
SwitchParameter
False
PassThru
If Specified, return a row object to allow further work to be done.
SwitchParameter
False
ExcelPackage
An Excel package object - for example from Export-Excel -PassThru - if specified requires a sheet name to be passed a parameter.
ExcelPackage
ExcelPackage
None
Worksheetname
The name of the sheet to update in the package.
Object
Object
Sheet1
Worksheet
A worksheet object instead of passing a name and package.
ExcelWorksheet
ExcelWorksheet
None
Row
Row to fill right - first row is 1. 0 will be interpreted as first unused row.
Object
Object
0
StartColumn
Position in the row to start from.
Int32
Int32
0
Value
Value, Formula or ScriptBlock to fill in. A ScriptBlock can use $worksheet, $row, $Column [number], $ColumnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn.
Object
Object
None
Heading
Optional row-heading.
Object
Object
None
HeadingBold
Set the heading in bold type.
SwitchParameter
SwitchParameter
False
HeadingSize
Change the font-size of the heading.
Int32
Int32
0
NumberFormat
Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc.
Object
Object
None
BorderAround
Style of border to draw around the row.
ExcelBorderStyle
ExcelBorderStyle
None
BorderColor
Color of the border.
Object
Object
[System.Drawing.Color]::Black
BorderBottom
Style for the bottom border.
ExcelBorderStyle
ExcelBorderStyle
None
BorderTop
Style for the top border.
ExcelBorderStyle
ExcelBorderStyle
None
BorderLeft
Style for the left border.
ExcelBorderStyle
ExcelBorderStyle
None
BorderRight
Style for the right border.
ExcelBorderStyle
ExcelBorderStyle
None
FontColor
Color for the text - if not specified the font will be left as it it is.
Object
Object
None
Bold
Make text bold; use -Bold:$false to remove bold.
SwitchParameter
SwitchParameter
False
Italic
Make text italic; use -Italic:$false to remove italic.
SwitchParameter
SwitchParameter
False
Underline
Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining.
SwitchParameter
SwitchParameter
False
UnderLineType
Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single".
ExcelUnderLineType
ExcelUnderLineType
Single
StrikeThru
Strike through text; use -StrikeThru:$false to remove strike through.
SwitchParameter
SwitchParameter
False
FontShift
Subscript or Superscript (or none).
ExcelVerticalAlignmentFont
ExcelVerticalAlignmentFont
None
FontName
Font to use - Excel defaults to Calibri.
String
String
None
FontSize
Point size for the text.
Single
Single
0
BackgroundColor
Change background color.
Object
Object
None
BackgroundPattern
Background pattern - solid by default.
ExcelFillStyle
ExcelFillStyle
Solid
PatternColor
Secondary color for background pattern.
Object
Object
None
WrapText
Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping.
SwitchParameter
SwitchParameter
False
HorizontalAlignment
Position cell contents to Left, Right, Center etc. default is 'General'.
ExcelHorizontalAlignment
ExcelHorizontalAlignment
None
VerticalAlignment
Position cell contents to Top, Bottom or Center.
ExcelVerticalAlignment
ExcelVerticalAlignment
None
TextRotation
Degrees to rotate text. Up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise.
Int32
Int32
0
Height
Set cells to a fixed height.
Single
Single
0
Hide
Hide the row.
SwitchParameter
SwitchParameter
False
ReturnRange
If sepecified, returns the range of cells which were affected.
SwitchParameter
SwitchParameter
False
PassThru
If Specified, return a row object to allow further work to be done.
SwitchParameter
SwitchParameter
False
OfficeOpenXml.ExcelRow
System.String
-------------------------- EXAMPLE 1 --------------------------
PS\> 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 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 the backtick in the script block (`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.
-------------------------- EXAMPLE 2 --------------------------
PS\> 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.
Update-FirstObjectProperties
Update
FirstObjectProperties
Updates the first object to contain all the properties of the object with the most properties in the array.
Updates the first object to contain all the properties found anywhere in the array.
This is usefull when not all objects have the same quantity of properties and CmdLets like Out-GridView or Export-Excel are not able to show all the properties because the first object doesn't have them all.
Update-FirstObjectProperties
CHANGELOG 2017/06/08 Function born
-------------------------- EXAMPLE 1 --------------------------
PS\> $Array = @()
PS\> $Obj1 = [PSCustomObject]@{
Member1 = 'First'
Member2 = 'Second'
}
PS\> $Obj2 = [PSCustomObject]@{
Member1 = 'First'
Member2 = 'Second'
Member3 = 'Third'
}
PS\> $Obj3 = [PSCustomObject]@{
Member1 = 'First'
Member2 = 'Second'
Member3 = 'Third'
Member4 = 'Fourth'
}
PS\> $Array = $Obj1, $Obj2, $Obj3
PS\> $Array | Out-GridView -Title 'Not showing Member3 and Member4'
PS\> $Array | Update-FirstObjectProperties | Out-GridView -Title 'All properties are visible'
Updates the first object of the array by adding Member3 and Member4 and shows before and after in gridviews
-------------------------- EXAMPLE 2 --------------------------
PS\>$ExcelParams = @{
Path = $env:TEMP + '\Excel.xlsx'
Show = $true
Verbose = $true
}
PS\> Remove-Item -Path $ExcelParams.Path -Force -EA Ignore
PS\> $Array = @()
PS\> $Obj1 = [PSCustomObjectable@{
Member1 = 'First'
Member2 = 'Second'
}
PS\> $Obj2 = [PSCustomObject]@{
Member1 = 'First'
Member2 = 'Second'
Member3 = 'Third'
}
PS\> $Obj3 = [PSCustomObject]@{
Member1 = 'First'
Member2 = 'Second'
Member3 = 'Third'
Member4 = 'Fourth'
}
PS\> $Array = $Obj1, $Obj2, $Obj3
PS\> $Array | Out-GridView -Title 'Not showing Member3 and Member4'
PS\> $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.
https://github.com/dfinke/ImportExcel
https://github.com/dfinke/ImportExcel