importexcel

Convert-ExcelRangeToImage Aliases

  • Convert-XlRangeToImage

Syntax

Convert-ExcelRangeToImage [-Path] <Object> [[-WorkSheetname] <Object>] [-Range] <Object> [[-Destination] <Object>] [-Show] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Path none Path to the Excel file true False None
-WorkSheetname none Worksheet name - if none is specified "Sheet1" will be assumed false False Sheet1
-Range none Range of cells within the sheet, e.g "A1:Z99" true False None
-Destination none A bmp, png or jpg file where the result will be saved false False "$pwd\temp.png"
-Show none If specified opens the image in the default viewer. false False False

ConvertFrom-ExcelSheet Aliases

  • Export-ExcelSheet

Syntax

ConvertFrom-ExcelSheet [-Path] <String> [[-OutputPath] <String>] [[-SheetName] <String>] [[-Encoding] <Encoding>] [[-Extension] {.txt | .log | .csv}] [[-Delimiter] {; |  | }] [[-Property] <Object>] [[-ExcludeProperty] <Object>] [[-AsText] <String[]>] [[-AsDate] <String[]>] [-Append] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Append none 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. false False False
-AsText none AsText allows selected columns to be returned as the text displayed in their cells, instead of their value. (* is supported as a wildcard.) false False None
-AsDate none 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.) false False None
-Delimiter none Selects , or ; as the delimeter for the exported data - if not specified , is used by default. false False None
-Encoding none Sets the text encoding for the output data file; UTF8 bu default false False None
-ExcludeProperty none 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. false False None
-Extension none Sets the file extension for the exported data, defaults to CSV false False None
-OutputPath none 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. false False None
-Path none The path to the .XLSX file which will be exported. true False None
-Property none 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 false False None
-SheetName none The name of a sheet to export, or a regular expression which is used to identify sheets false False None

Inputs

The input type is the type of the objects that you can pipe to the cmdlet.

  • None

Outputs

The output type is the type of the objects that the cmdlet emits.

  • System.Object

Examples

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.

Top of page

Links

New-ExcelChartDefinition Aliases

  • New-ExcelChart

Syntax

New-ExcelChartDefinition [[-Title] <Object>] [[-RowOffSetPixels] <Object>] [[-Column] <Object>] [[-ColumnOffSetPixels] <Object>] [[-LegendPosition] {Top | Left | Right | Bottom | TopRight}] [[-LegendSize] <Object>] [[-SeriesHeader] <Object>] [[-TitleSize] <Int32>] [[-XAxisTitleText] <String>] [[-XAxisTitleSize] <Object>] [[-XAxisNumberformat] <String>] [[-Header] <Object>] [[-XMajorUnit] <Object>] [[-XMinorUnit] <Object>] [[-XMaxValue] <Object>] [[-XMinValue] <Object>] [[-XAxisPosition] {Left | Bottom | Right | Top}] [[-YAxisTitleText] <String>] [[-YAxisTitleSize] <Object>] [[-YAxisNumberformat] <String>] [[-YMajorUnit] <Object>] [[-YMinorUnit] <Object>] [[-ChartType] {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}] [[-YMaxValue] <Object>] [[-YMinValue] <Object>] [[-YAxisPosition] {Left | Bottom | Right | Top}] [[-ChartTrendLine] {Exponential | Linear | Logarithmic | MovingAvgerage | Polynomial | Power}] [[-XRange] <Object>] [[-YRange] <Object>] [[-Width] <Object>] [[-Height] <Object>] [[-Row] <Object>] [-LegendBold] [-NoLegend] [-ShowCategory] [-ShowPercent] [-TitleBold] [-XAxisTitleBold] [-YAxisTitleBold] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Title none The title for the chart. false False Chart Title
-Header none No longer used. This may be removed in future versions. false False None
-ChartType none One of the built-in chart types, such as Pie, ClusteredColumn, Line etc. Defaults to "ColumnStacked". false False ColumnStacked
-ChartTrendLine none Superimposes one of Excel's trenline types on the chart. false False None
-XRange none The range of cells containing values for the X-Axis - usually labels. false False None
-YRange none The range(s) of cells holding values for the Y-Axis - usually "data". false False None
-Width none Width of the chart in pixels. Defaults to 500. false False 500
-Height none Height of the chart in pixels. Defaults to 350. false False 350
-Row none 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. false False 0
-RowOffSetPixels none Offset to position the chart by a fraction of a row. false False 10
-Column none 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. false False 6
-ColumnOffSetPixels none Offset to position the chart by a fraction of a column. false False 5
-LegendPosition none Location of the key, either "Left", "Right", "Top", "Bottom" or "TopRight". false False None
-LegendSize none Font size for the key. false False None
-LegendBold none Sets the key in bold type. false False False
-NoLegend none 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. false False False
-ShowCategory none Attaches a category label in charts which support this. false False False
-ShowPercent none Attaches a percentage label in charts which support this. false False False
-SeriesHeader none Specifies explicit name(s) for the data series, which will appear in the legend/key false False None
-TitleBold none Sets the title in bold face. false False False
-TitleSize none Sets the point size for the title. false False 0
-XAxisTitleText none Specifies a title for the X-axis. false False None
-XAxisTitleBold none Sets the X-axis title in bold face. false False False
-XAxisTitleSize none Sets the font size for the axis title. false False None
-XAxisNumberformat none A number formatting string, like "#,##0.00", for numbers along the X-axis. false False None
-XMajorUnit none Spacing for the major gridlines / tick marks along the X-axis. false False None
-XMinorUnit none Spacing for the minor gridlines / tick marks along the X-axis. false False None
-XMaxValue none Maximum value for the scale along the X-axis. false False None
-XMinValue none Minimum value for the scale along the X-axis. false False None
-XAxisPosition none Position for the X-axis ("Top" or" Bottom"). false False None
-YAxisTitleText none Specifies a title for the Y-axis. false False None
-YAxisTitleBold none Sets the Y-axis title in bold face. false False False
-YAxisTitleSize none Sets the font size for the Y-axis title. false False None
-YAxisNumberformat none A number formatting string, like "#,##0.00", for numbers on the Y-axis false False None
-YMajorUnit none Spacing for the major gridlines / tick marks on the Y-axis. false False None
-YMinorUnit none Spacing for the minor gridlines / tick marks on the Y-axis. false False None
-YMaxValue none Maximum value on the Y-axis. false False None
-YMinValue none Minimum value on the Y-axis. false False None
-YAxisPosition none Position for the Y-axis ("Left" or "Right"). false False None

Examples

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 .

Top of page

Set-ExcelColumn Aliases

  • Set-Column

Syntax

Set-ExcelColumn -ExcelPackage <ExcelPackage> [-Worksheetname <String>] [-Column <Object>] [-StartRow <Int32>] [-Value <Object>] [-Heading <Object>] [-NumberFormat <Object>] [-BorderAround {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-FontColor <Object>] [-Bold] [-Italic] [-Underline] [-UnderLineType {None | Single | Double | SingleAccounting | DoubleAccounting}] [-StrikeThru] [-FontShift {None | Baseline | Subscript | Superscript}] [-FontName <String>] [-FontSize <Single>] [-BackgroundColor <Object>] [-BackgroundPattern {None | Solid | DarkGray | MediumGray | LightGray | Gray125 | Gray0625 | DarkVertical | DarkHorizontal | DarkDown | DarkUp | DarkGrid | DarkTrellis | LightVertical | LightHorizontal | LightDown | LightUp | LightGrid | LightTrellis}] [-PatternColor <Object>] [-WrapText] [-HorizontalAlignment {General | Left | Center | CenterContinuous | Right | Fill | Distributed | Justify}] [-VerticalAlignment {Top | Center | Bottom | Distributed | Justify}] [-TextRotation <Int32>] [-AutoSize] [-Width <Single>] [-AutoNameRange] [-Hide] [-Specified] [-PassThru] [<CommonParameters>]

Set-ExcelColumn -Worksheet <ExcelWorksheet> [-Column <Object>] [-StartRow <Int32>] [-Value <Object>] [-Heading <Object>] [-NumberFormat <Object>] [-BorderAround {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-FontColor <Object>] [-Bold] [-Italic] [-Underline] [-UnderLineType {None | Single | Double | SingleAccounting | DoubleAccounting}] [-StrikeThru] [-FontShift {None | Baseline | Subscript | Superscript}] [-FontName <String>] [-FontSize <Single>] [-BackgroundColor <Object>] [-BackgroundPattern {None | Solid | DarkGray | MediumGray | LightGray | Gray125 | Gray0625 | DarkVertical | DarkHorizontal | DarkDown | DarkUp | DarkGrid | DarkTrellis | LightVertical | LightHorizontal | LightDown | LightUp | LightGrid | LightTrellis}] [-PatternColor <Object>] [-WrapText] [-HorizontalAlignment {General | Left | Center | CenterContinuous | Right | Fill | Distributed | Justify}] [-VerticalAlignment {Top | Center | Bottom | Distributed | Justify}] [-TextRotation <Int32>] [-AutoSize] [-Width <Single>] [-AutoNameRange] [-Hide] [-Specified] [-PassThru] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-ExcelPackage none If specifying the worksheet by name, the ExcelPackage object which contains the worksheet also needs to be passed. true False None
-Worksheetname none The sheet to update can be given as a name or an Excel Worksheet object - this sets it by name. false False Sheet1
-Worksheet none This passes the worksheet object instead of passing a sheet name and an Excelpackage object. true False None
-Column none Column to fill down - the first column is 1. 0 will be interpreted as first empty column. false True (ByValue) 0
-StartRow none First row to fill data in. false False 0
-Value none A value, formula or scriptblock to fill in. A script block can use $worksheet, $row, $column [number], $columnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn. false False None
-Heading none Optional column heading. false False None
-NumberFormat NFormat 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. false False None
-BorderAround none Style of border to draw around the row. false False None
-FontColor none Colour for the text - if none specified it will be left as it it is. false False None
-Bold none Make text bold; use -Bold:$false to remove bold. false False False
-Italic none Make text italic; use -Italic:$false to remove italic. false False False
-Underline none Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. false False False
-UnderLineType none Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". false False Single
-StrikeThru none Strike through text; use -StrikeThru:$false to remove strike through. false False False
-FontShift none Subscript or Superscript (or None). false False None
-FontName none Font to use - Excel defaults to Calibri. false False None
-FontSize none Point size for the text. false False 0
-BackgroundColor none Change background color. false False None
-BackgroundPattern none Background pattern - "Solid" by default. false False Solid
-PatternColor PatternColour Secondary color for background pattern. false False None
-WrapText none Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. false False False
-HorizontalAlignment none Position cell contents to Left, Right, Center etc. Default is "General". false False None
-VerticalAlignment none Position cell contents to Top, Bottom or Center. false False None
-TextRotation none Degrees to rotate text; up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise. false False 0
-AutoSize AutoFit Attempt to auto-fit cells to the width their contents. false False False
-Width none Set cells to a fixed width, ignored if -AutoSize is specified. false False 0
-AutoNameRange none Set the inserted data to be a named range. false False False
-Hide Hidden Hide the column. false False False
-Specified none If specified, returns the range of cells which were affected. false False False
-PassThru none If specified, return an object representing the Column, to allow further work to be done on it. false False False

Outputs

The output type is the type of the objects that the cmdlet emits.

  • OfficeOpenXml.ExcelColumn System.String

Examples

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.

Top of page

Set-ExcelRange Aliases

  • Set-Format

Syntax

Set-ExcelRange [[-Range] <Object>] [-WorkSheet <ExcelWorksheet>] [-NumberFormat <Object>] [-BorderAround {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderColor <Object>] [-BorderBottom {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderTop {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderLeft {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderRight {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-FontColor <Object>] [-Value <Object>] [-Formula <Object>] [-ArrayFormula] [-ResetFont] [-Bold] [-Italic] [-Underline] [-UnderLineType {None | Single | Double | SingleAccounting | DoubleAccounting}] [-StrikeThru] [-FontShift {None | Baseline | Subscript | Superscript}] [-FontName <String>] [-FontSize <Single>] [-BackgroundColor <Object>] [-BackgroundPattern {None | Solid | DarkGray | MediumGray | LightGray | Gray125 | Gray0625 | DarkVertical | DarkHorizontal | DarkDown | DarkUp | DarkGrid | DarkTrellis | LightVertical | LightHorizontal | LightDown | LightUp | LightGrid | LightTrellis}] [-PatternColor <Object>] [-WrapText] [-HorizontalAlignment {General | Left | Center | CenterContinuous | Right | Fill | Distributed | Justify}] [-VerticalAlignment {Top | Center | Bottom | Distributed | Justify}] [-TextRotation <Int32>] [-AutoSize] [-Width <Single>] [-Height <Single>] [-Hidden] [-Locked] [-Merge] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Range Address One or more row(s), Column(s) and/or block(s) of cells to format. false True (ByValue) None
-WorkSheet none The worksheet where the format is to be applied. false False None
-NumberFormat NFormat 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. false False None
-BorderAround none Style of border to draw around the range. false False None
-BorderColor none Color of the border. false False [System.Drawing.Color]::Black
-BorderBottom none Style for the bottom border. false False None
-BorderTop none Style for the top border. false False None
-BorderLeft none Style for the left border. false False None
-BorderRight none Style for the right border. false False None
-FontColor ForegroundColor Colour for the text - if none is specified it will be left as it is. false False None
-Value none Value for the cell. false False None
-Formula none Formula for the cell. false False None
-ArrayFormula none Specifies formula should be an array formula (a.k.a CSE [ctrl-shift-enter] formula). false False False
-ResetFont none Clear Bold, Italic, StrikeThrough and Underline and set color to Black. false False False
-Bold none Make text bold; use -Bold:$false to remove bold. false False False
-Italic none Make text italic; use -Italic:$false to remove italic. false False False
-Underline none Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. false False False
-UnderLineType none Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". false False Single
-StrikeThru none Strike through text; use -Strikethru:$false to remove Strike through false False False
-FontShift none Subscript or Superscript (or none). false False None
-FontName none Font to use - Excel defaults to Calibri. false False None
-FontSize none Point size for the text. false False 0
-BackgroundColor none Change background color. false False None
-BackgroundPattern none Background pattern - Solid by default. false False Solid
-PatternColor PatternColour Secondary color for background pattern. false False None
-WrapText none Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. false False False
-HorizontalAlignment none Position cell contents to Left, Right, Center etc. default is 'General'. false False None
-VerticalAlignment none Position cell contents to Top, Bottom or Center. false False None
-TextRotation none Degrees to rotate text; up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise. false False 0
-AutoSize AutoFit Autofit cells to width (columns or ranges only). false False False
-Width none Set cells to a fixed width (columns or ranges only), ignored if Autosize is specified. false False 0
-Height none Set cells to a fixed height (rows or ranges only). false False 0
-Hidden Hide Hide a row or column (not a range); use -Hidden:$false to unhide. false False False
-Locked none 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. false False False
-Merge none Merges cells - it is recommended that you explicitly set -HorizontalAlignment false False False

Examples

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.

Top of page

Set-ExcelRow Aliases

  • Set-Row

Syntax

Set-ExcelRow -ExcelPackage <ExcelPackage> [-Worksheetname <Object>] [-Row <Object>] [-StartColumn <Int32>] [-Value <Object>] [-Heading <Object>] [-HeadingBold] [-HeadingSize <Int32>] [-NumberFormat <Object>] [-BorderAround {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderColor <Object>] [-BorderBottom {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderTop {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderLeft {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderRight {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-FontColor <Object>] [-Bold] [-Italic] [-Underline] [-UnderLineType {None | Single | Double | SingleAccounting | DoubleAccounting}] [-StrikeThru] [-FontShift {None | Baseline | Subscript | Superscript}] [-FontName <String>] [-FontSize <Single>] [-BackgroundColor <Object>] [-BackgroundPattern {None | Solid | DarkGray | MediumGray | LightGray | Gray125 | Gray0625 | DarkVertical | DarkHorizontal | DarkDown | DarkUp | DarkGrid | DarkTrellis | LightVertical | LightHorizontal | LightDown | LightUp | LightGrid | LightTrellis}] [-PatternColor <Object>] [-WrapText] [-HorizontalAlignment {General | Left | Center | CenterContinuous | Right | Fill | Distributed | Justify}] [-VerticalAlignment {Top | Center | Bottom | Distributed | Justify}] [-TextRotation <Int32>] [-Height <Single>] [-Hide] [-ReturnRange] [-PassThru] [<CommonParameters>]

Set-ExcelRow -Worksheet <ExcelWorksheet> [-Row <Object>] [-StartColumn <Int32>] [-Value <Object>] [-Heading <Object>] [-HeadingBold] [-HeadingSize <Int32>] [-NumberFormat <Object>] [-BorderAround {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderColor <Object>] [-BorderBottom {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderTop {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderLeft {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderRight {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-FontColor <Object>] [-Bold] [-Italic] [-Underline] [-UnderLineType {None | Single | Double | SingleAccounting | DoubleAccounting}] [-StrikeThru] [-FontShift {None | Baseline | Subscript | Superscript}] [-FontName <String>] [-FontSize <Single>] [-BackgroundColor <Object>] [-BackgroundPattern {None | Solid | DarkGray | MediumGray | LightGray | Gray125 | Gray0625 | DarkVertical | DarkHorizontal | DarkDown | DarkUp | DarkGrid | DarkTrellis | LightVertical | LightHorizontal | LightDown | LightUp | LightGrid | LightTrellis}] [-PatternColor <Object>] [-WrapText] [-HorizontalAlignment {General | Left | Center | CenterContinuous | Right | Fill | Distributed | Justify}] [-VerticalAlignment {Top | Center | Bottom | Distributed | Justify}] [-TextRotation <Int32>] [-Height <Single>] [-Hide] [-ReturnRange] [-PassThru] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-ExcelPackage none An Excel package object - for example from Export-Excel -PassThru - if specified requires a sheet name to be passed a parameter. true False None
-Worksheetname none The name of the sheet to update in the package. false False Sheet1
-Worksheet none A worksheet object instead of passing a name and package. true False None
-Row none Row to fill right - first row is 1. 0 will be interpreted as first unused row. false True (ByValue) 0
-StartColumn none Position in the row to start from. false False 0
-Value none Value, Formula or ScriptBlock to fill in. A ScriptBlock can use $worksheet, $row, $Column [number], $ColumnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn. false False None
-Heading none Optional row-heading. false False None
-HeadingBold none Set the heading in bold type. false False False
-HeadingSize none Change the font-size of the heading. false False 0
-NumberFormat NFormat Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc. false False None
-BorderAround none Style of border to draw around the row. false False None
-BorderColor none Color of the border. false False [System.Drawing.Color]::Black
-BorderBottom none Style for the bottom border. false False None
-BorderTop none Style for the top border. false False None
-BorderLeft none Style for the left border. false False None
-BorderRight none Style for the right border. false False None
-FontColor none Color for the text - if not specified the font will be left as it it is. false False None
-Bold none Make text bold; use -Bold:$false to remove bold. false False False
-Italic none Make text italic; use -Italic:$false to remove italic. false False False
-Underline none Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. false False False
-UnderLineType none Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". false False Single
-StrikeThru none Strike through text; use -StrikeThru:$false to remove strike through. false False False
-FontShift none Subscript or Superscript (or none). false False None
-FontName none Font to use - Excel defaults to Calibri. false False None
-FontSize none Point size for the text. false False 0
-BackgroundColor none Change background color. false False None
-BackgroundPattern none Background pattern - solid by default. false False Solid
-PatternColor PatternColour Secondary color for background pattern. false False None
-WrapText none Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. false False False
-HorizontalAlignment none Position cell contents to Left, Right, Center etc. default is 'General'. false False None
-VerticalAlignment none Position cell contents to Top, Bottom or Center. false False None
-TextRotation none Degrees to rotate text. Up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise. false False 0
-Height none Set cells to a fixed height. false False 0
-Hide Hidden Hide the row. false False False
-ReturnRange none If sepecified, returns the range of cells which were affected. false False False
-PassThru none If Specified, return a row object to allow further work to be done. false False False

Outputs

The output type is the type of the objects that the cmdlet emits.

  • OfficeOpenXml.ExcelRow System.String

Examples

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.

Top of page

ConvertFrom-ExcelData Aliases

  • Use-ExcelData

Parameters

Name Alias Description Required? Pipeline Input Default Value
-DataOnly None false false
-Header None false false
-HeaderRow None false false
-NoHeader None false false
-Path FullName true true (ByValue, ByPropertyName)
-ScriptBlock None false false
-WorksheetName Sheet false false

Syntax

Add-ConditionalFormatting [-Address] <Object> [-RuleType] {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} [[-ConditionValue] <Object>] [[-ConditionValue2] <Object>] [-WorkSheet <ExcelWorksheet>] [-ForegroundColor <Object>] [-Reverse] [-BackgroundColor <Object>] [-BackgroundPattern {None | Solid | DarkGray | MediumGray | LightGray | Gray125 | Gray0625 | DarkVertical | DarkHorizontal | DarkDown | DarkUp | DarkGrid | DarkTrellis | LightVertical | LightHorizontal | LightDown | LightUp | LightGrid | LightTrellis}] [-PatternColor <Object>] [-NumberFormat <Object>] [-Bold] [-Italic] [-Underline] [-StrikeThru] [-StopIfTrue] [-Priority <Int32>] [-PassThru] [<CommonParameters>]

Add-ConditionalFormatting [-Address] <Object> [-WorkSheet <ExcelWorksheet>] -DataBarColor <Object> [-Priority <Int32>] [-PassThru] [<CommonParameters>]

Add-ConditionalFormatting [-Address] <Object> [-WorkSheet <ExcelWorksheet>] -ThreeIconsSet {Arrows | ArrowsGray | Flags | Signs | Symbols | Symbols2 | TrafficLights1 | TrafficLights2} [-Reverse] [-Priority <Int32>] [-PassThru] [<CommonParameters>]

Add-ConditionalFormatting [-Address] <Object> [-WorkSheet <ExcelWorksheet>] -FourIconsSet {Arrows | ArrowsGray | Rating | RedToBlack | TrafficLights} [-Reverse] [-Priority <Int32>] [-PassThru] [<CommonParameters>]

Add-ConditionalFormatting [-Address] <Object> [-WorkSheet <ExcelWorksheet>] -FiveIconsSet {Arrows | ArrowsGray | Quarters | Rating} [-Reverse] [-Priority <Int32>] [-PassThru] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Address Range A block of cells to format - you can use a named range with -Address $ws.names[1] or $ws.cells["RangeName"] true False None
-WorkSheet none The worksheet where the format is to be applied false False None
-RuleType none A standard named-rule - Top / Bottom / Less than / Greater than / Contains etc. true False None
-ForegroundColor ForegroundColour, FontColor Text color for matching objects false False None
-DataBarColor DataBarColour Color for databar type charts true False None
-ThreeIconsSet none One of the three-icon set types (e.g. Traffic Lights) true False None
-FourIconsSet none A four-icon set name true False None
-FiveIconsSet none A five-icon set name true False None
-Reverse none Use the Icon-Set in reverse order, or reverse the orders of Two- & Three-Color Scales false False False
-ConditionValue none A value for the condition (for example 2000 if the test is 'lessthan 2000'; Formulas should begin with "=" ) false False None
-ConditionValue2 none A second value for the conditions like "Between X and Y" false False None
-BackgroundColor none Background color for matching items false False None
-BackgroundPattern none Background pattern for matching items false False None
-PatternColor none Secondary color when a background pattern requires it false False None
-NumberFormat none Sets the numeric format for matching items false False None
-Bold none Put matching items in bold face false False False
-Italic none Put matching items in italic false False False
-Underline none Underline matching items false False False
-StrikeThru none Strikethrough text of matching items false False False
-StopIfTrue none Prevent the processing of subsequent rules false False False
-Priority none Set the sequence for rule processing false False 0
-PassThru none If specified pass the rule back to the caller to allow additional customization. false False False

Examples

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.

Top of page

Syntax

Add-ExcelChart -Worksheet <ExcelWorksheet> [-Title <String>] [-ChartType {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}] [-ChartTrendLine {Exponential | Linear | Logarithmic | MovingAvgerage | Polynomial | Power}] [-XRange <Object>] [-YRange <Object>] [-Width <Int32>] [-Height <Int32>] [-Row <Int32>] [-RowOffSetPixels <Int32>] [-Column <Int32>] [-ColumnOffSetPixels <Int32>] [-LegendPosition {Top | Left | Right | Bottom | TopRight}] [-LegendSize <Object>] [-LegendBold] [-NoLegend] [-ShowCategory] [-ShowPercent] [-SeriesHeader <String[]>] [-TitleBold] [-TitleSize <Int32>] [-XAxisTitleText <String>] [-XAxisTitleBold] [-XAxisTitleSize <Object>] [-XAxisNumberformat <String>] [-XMajorUnit <Object>] [-XMinorUnit <Object>] [-XMaxValue <Object>] [-XMinValue <Object>] [-XAxisPosition {Left | Bottom | Right | Top}] [-YAxisTitleText <String>] [-YAxisTitleBold] [-YAxisTitleSize <Object>] [-YAxisNumberformat <String>] [-YMajorUnit <Object>] [-YMinorUnit <Object>] [-YMaxValue <Object>] [-YMinValue <Object>] [-YAxisPosition {Left | Bottom | Right | Top}] [-PassThru] [<CommonParameters>]

Add-ExcelChart -PivotTable <ExcelPivotTable> [-Title <String>] [-ChartType {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}] [-ChartTrendLine {Exponential | Linear | Logarithmic | MovingAvgerage | Polynomial | Power}] [-XRange <Object>] [-YRange <Object>] [-Width <Int32>] [-Height <Int32>] [-Row <Int32>] [-RowOffSetPixels <Int32>] [-Column <Int32>] [-ColumnOffSetPixels <Int32>] [-LegendPosition {Top | Left | Right | Bottom | TopRight}] [-LegendSize <Object>] [-LegendBold] [-NoLegend] [-ShowCategory] [-ShowPercent] [-SeriesHeader <String[]>] [-TitleBold] [-TitleSize <Int32>] [-XAxisTitleText <String>] [-XAxisTitleBold] [-XAxisTitleSize <Object>] [-XAxisNumberformat <String>] [-XMajorUnit <Object>] [-XMinorUnit <Object>] [-XMaxValue <Object>] [-XMinValue <Object>] [-XAxisPosition {Left | Bottom | Right | Top}] [-YAxisTitleText <String>] [-YAxisTitleBold] [-YAxisTitleSize <Object>] [-YAxisNumberformat <String>] [-YMajorUnit <Object>] [-YMinorUnit <Object>] [-YMaxValue <Object>] [-YMinValue <Object>] [-YAxisPosition {Left | Bottom | Right | Top}] [-PassThru] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Worksheet none An existing Sheet where the chart will be created. true False None
-PivotTable none Instead of specify X and Y ranges, get data from a PivotTable by passing a PivotTable Object. true False None
-Title none The title for the chart. false False None
-ChartType none One of the built-in chart types, such as Pie, ClusteredColumn, Line etc. Defaults to "ColumnStacked". false False ColumnStacked
-ChartTrendLine none {{ Fill ChartTrendLine Description }} false False None
-XRange none The range of cells containing values for the X-Axis - usually labels. false False None
-YRange none The range(s) of cells holding values for the Y-Axis - usually "data". false False None
-Width none Width of the chart in Pixels; defaults to 500. false False 500
-Height none Height of the chart in Pixels; defaults to 350. false False 350
-Row none Row position of the top left corner of the chart. ) places at the top of the sheet, 1 below row 1 and so on. false False 0
-RowOffSetPixels none Offset to position the chart by a fraction of a row. false False 10
-Column none 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. false False 6
-ColumnOffSetPixels none Offset to position the chart by a fraction of a column. false False 5
-LegendPosition none Location of the key, either left, right, top, bottom or TopRight. false False None
-LegendSize none Font size for the key. false False None
-LegendBold none Sets the key in bold type. false False False
-NoLegend none 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. false False False
-ShowCategory none Attaches a category label, in charts which support this. false False False
-ShowPercent none Attaches a percentage label, in charts which support this. false False False
-SeriesHeader none 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 . false False None
-TitleBold none Sets the title in bold face. false False False
-TitleSize none Sets the point size for the title. false False 0
-XAxisTitleText none Specifies a title for the X-axis. false False None
-XAxisTitleBold none Sets the X-axis title in bold face. false False False
-XAxisTitleSize none Sets the font size for the axis title. false False None
-XAxisNumberformat none A number formatting string, like "#,##0.00", for numbers along the X-axis. false False None
-XMajorUnit none Spacing for the major gridlines / tick marks along the X-axis. false False None
-XMinorUnit none Spacing for the minor gridlines / tick marks along the X-axis. false False None
-XMaxValue none Maximum value for the scale along the X-axis. false False None
-XMinValue none Minimum value for the scale along the X-axis. false False None
-XAxisPosition none Position for the X-axis (Top or Bottom). false False None
-YAxisTitleText none Specifies a title for the Y-axis. false False None
-YAxisTitleBold none Sets the Y-axis title in bold face. false False False
-YAxisTitleSize none Sets the font size for the Y-axis title false False None
-YAxisNumberformat none A number formatting string, like "#,##0.00", for numbers on the Y-axis. false False None
-YMajorUnit none Spacing for the major gridlines / tick marks on the Y-axis. false False None
-YMinorUnit none Spacing for the minor gridlines / tick marks on the Y-axis. false False None
-YMaxValue none Maximum value on the Y-axis. false False None
-YMinValue none Minimum value on the Y-axis. false False None
-YAxisPosition none Position for the Y-axis (Left or Right). false False None
-PassThru none 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. false False False

Outputs

The output type is the type of the objects that the cmdlet emits.

  • OfficeOpenXml.Drawing.Chart.ExcelChart

Examples

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)".

Top of page

Syntax

Add-ExcelDataValidationRule [[-Range] <Object>] [-WorkSheet <ExcelWorksheet>] [-ValidationType <Object>] [-Operator {between | notBetween | equal | notEqual | lessThan | lessThanOrEqual | greaterThan | greaterThanOrEqual}] [-Value <Object>] [-Value2 <Object>] [-Formula <Object>] [-Formula2 <Object>] [-ValueSet <Object>] [-ShowErrorMessage] [-ErrorStyle {undefined | stop | warning | information}] [-ErrorTitle <String>] [-ErrorBody <String>] [-ShowPromptMessage] [-PromptBody <String>] [-PromptTitle <String>] [-NoBlank <String>] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Range Address The range of cells to be validate, for example, "B2:C100" false True (ByValue) None
-WorkSheet none The worksheet where the cells should be validated false False None
-ValidationType none 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 false False None
-Operator none The operator to apply to Decimal, Integer, TextLength, DateTime and time fields, for example "equal" or "between" false False Equal
-Value none For Decimal, Integer, TextLength, DateTime the [first] data value false False None
-Value2 none When using the between operator, the second data value false False None
-Formula none 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 false False None
-Formula2 none When using the between operator, the second data value as a formula false False None
-ValueSet none When using the list validation type, a set of values (rather than refering to Sheet!B$2:B$100 ) false False None
-ShowErrorMessage none Corresponds to the the 'Show Error alert ...' check box on error alert page in the Excel dialog false False False
-ErrorStyle none Stop, Warning, or Infomation, corresponding to to the style setting in the Excel dialog false False None
-ErrorTitle none The title for the message box corresponding to to the title setting in the Excel dialog false False None
-ErrorBody none The error message corresponding to to the Error message setting in the Excel dialog false False None
-ShowPromptMessage none Corresponds to the the 'Show Input message ...' check box on input message page in the Excel dialog false False False
-PromptBody none The prompt message corresponding to to the Input message setting in the Excel dialog false False None
-PromptTitle none The title for the message box corresponding to to the title setting in the Excel dialog false False None
-NoBlank none By default the 'Ignore blank' option will be selected, unless NoBlank is sepcified. false False None

Examples

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.

Top of page

Syntax

Add-ExcelName [-Range] <ExcelRange> [[-RangeName] <String>] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Range none The range of cells to assign as a name. true False None
-RangeName none 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. false False None

Examples

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.

Top of page

Syntax

Add-ExcelTable [-Range] <ExcelRange> [[-TableName] <String>] [[-TableStyle] {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}] [[-TotalSettings] <Hashtable>] [-ShowHeader] [-ShowFilter] [-ShowTotal] [-ShowFirstColumn] [-ShowLastColumn] [-ShowRowStripes] [-ShowColumnStripes] [-PassThru] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Range none The range of cells to assign to a table. true False None
-TableName none The name for the Table - this should be unqiue in the Workbook - auto generated names will be used if this is left empty. false False None
-TableStyle none The Style for the table, by default "Medium6" is used false False Medium6
-ShowHeader none By default the header row is shown - it can be turned off with -ShowHeader:$false. false False False
-ShowFilter none By default the filter is enabled - it can be turned off with -ShowFilter:$false. false False False
-ShowTotal none 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 false False False
-TotalSettings none A HashTable in the form ColumnName = "Average"|"Count"|"CountNums"|"Max"|"Min"|"None"|"StdDev"|"Sum"|"Var" - if specified, -ShowTotal is not needed. false False None
-ShowFirstColumn none Highlights the first column in bold. false False False
-ShowLastColumn none Highlights the last column in bold. false False False
-ShowRowStripes none By default the table formats show striped rows, the can be turned off with -ShowRowStripes:$false false False False
-ShowColumnStripes none Turns on column stripes. false False False
-PassThru none If -PassThru is specified, the table object will be returned to allow additional changes to be made. false False False

Outputs

The output type is the type of the objects that the cmdlet emits.

  • OfficeOpenXml.Table.ExcelTable

Examples

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.

Top of page

Syntax

Add-PivotTable -PivotTableName <String> [-Address <ExcelAddressBase>] [-ExcelPackage <Object>] [-SourceWorkSheet <Object>] [-SourceRange <Object>] [-PivotRows <Object>] [-PivotData <Object>] [-PivotColumns <Object>] [-PivotFilter <Object>] [-PivotDataToColumn] [-PivotTotals <String>] [-NoTotalsInPivot] [-GroupDateRow <String>] [-GroupDatePart {Years | Quarters | Months | Days | Hours | Minutes | Seconds}] [-GroupNumericRow <String>] [-GroupNumericMin <Double>] [-GroupNumericMax <Double>] [-GroupNumericInterval <Double>] [-PivotNumberFormat <String>] [-PivotTableStyle {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}] -PivotChartDefinition <Object> [-Activate] [-PassThru] [<CommonParameters>]

Add-PivotTable -PivotTableName <String> [-Address <ExcelAddressBase>] [-ExcelPackage <Object>] [-SourceWorkSheet <Object>] [-SourceRange <Object>] [-PivotRows <Object>] [-PivotData <Object>] [-PivotColumns <Object>] [-PivotFilter <Object>] [-PivotDataToColumn] [-PivotTotals <String>] [-NoTotalsInPivot] [-GroupDateRow <String>] [-GroupDatePart {Years | Quarters | Months | Days | Hours | Minutes | Seconds}] [-GroupNumericRow <String>] [-GroupNumericMin <Double>] [-GroupNumericMax <Double>] [-GroupNumericInterval <Double>] [-PivotNumberFormat <String>] [-PivotTableStyle {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}] [-IncludePivotChart] [-ChartTitle <String>] [-ChartHeight <Int32>] [-ChartWidth <Int32>] [-ChartRow <Int32>] [-ChartColumn <Int32>] [-ChartRowOffSetPixels <Int32>] [-ChartColumnOffSetPixels <Int32>] [-ChartType {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}] [-NoLegend] [-ShowCategory] [-ShowPercent] [-Activate] [-PassThru] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-PivotTableName none Name for the new PivotTable - this will be the name of a sheet in the Workbook. true False None
-Address none 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.) false False None
-ExcelPackage none An Excel-package object for the workbook. false False None
-SourceWorkSheet none Worksheet where the data is found. false False None
-SourceRange none 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. false False None
-PivotRows none Fields to set as rows in the PivotTable. false False None
-PivotData none A hash table in form "FieldName"="Function", where function is one of Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP. false False None
-PivotColumns none Fields to set as columns in the PivotTable. false False None
-PivotFilter none Fields to use to filter in the PivotTable. false False None
-PivotDataToColumn none If there are multiple data items in a PivotTable, by default they are shown on separate rows; this switch makes them separate columns. false False False
-PivotTotals none Define whether totals should be added to rows, columns neither, or both (the default is both). false False Both
-NoTotalsInPivot none Included for compatibility - equivalent to -PivotTotals "None". false False False
-GroupDateRow none The name of a row field which should be grouped by parts of the date/time (ignored if GroupDateRow is not specified) false False None
-GroupDatePart none The Part(s) of the date to use in the grouping (ignored if GroupDateRow is not specified) false False None
-GroupNumericRow none The name of a row field which should be grouped by Number (e.g. 0-99, 100-199, 200-299 ) false False None
-GroupNumericMin none The starting point for grouping false False 0
-GroupNumericMax none The endpoint for grouping false False 1.79769313486232E+308
-GroupNumericInterval none The interval for grouping false False 100
-PivotNumberFormat none Number format to apply to the data cells in the PivotTable. false False None
-PivotTableStyle none Apply a table style to the PivotTable. false False None
-PivotChartDefinition none Use a chart definition instead of specifying chart settings one by one. true True (ByPropertyName) None
-IncludePivotChart none If specified, a chart will be included. false False False
-ChartTitle none Optional title for the pivot chart, by default the title omitted. false False None
-ChartHeight none Height of the chart in Pixels (400 by default). false False 400
-ChartWidth none Width of the chart in Pixels (600 by default). false False 600
-ChartRow none 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). false False 0
-ChartColumn none 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). false False 4
-ChartRowOffSetPixels none Vertical offset of the chart from the cell corner. false False 0
-ChartColumnOffSetPixels none Horizontal offset of the chart from the cell corner. false False 0
-ChartType none Type of chart; defaults to "Pie". false False Pie
-NoLegend none If specified hides the chart legend. false False False
-ShowCategory none 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. false False False
-ShowPercent none If specified attaches percentages to slices in a pie chart. false False False
-Activate none If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified. false False False
-PassThru none Return the PivotTable so it can be customized. false False False

Outputs

The output type is the type of the objects that the cmdlet emits.

  • OfficeOpenXml.Table.PivotTable.ExcelPivotTable

Examples

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.

Top of page

Syntax

Add-WorkSheet [-ExcelPackage] <ExcelPackage> [-WorksheetName <String>] [-ClearSheet] [-MoveToStart] [-MoveToEnd] [-MoveBefore <Object>] [-MoveAfter <Object>] [-Activate] [-CopySource <ExcelWorksheet>] [-NoClobber] [<CommonParameters>]

Add-WorkSheet -ExcelWorkbook <ExcelWorkbook> [-WorksheetName <String>] [-ClearSheet] [-MoveToStart] [-MoveToEnd] [-MoveBefore <Object>] [-MoveAfter <Object>] [-Activate] [-CopySource <ExcelWorksheet>] [-NoClobber] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-ExcelPackage none An object representing an Excel Package. true True (ByValue) None
-ExcelWorkbook none An Excel Workbook to which the Worksheet will be added - a Package contains one Workbook, so you can use whichever fits at the time. true False None
-WorksheetName none The name of the worksheet, 'Sheet1' by default. false False None
-ClearSheet none If the worksheet already exists, by default it will returned, unless -ClearSheet is specified in which case it will be deleted and re-created. false False False
-MoveToStart none 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.
false False False
-MoveToEnd none 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.)
false False False
-MoveBefore none 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.
false False None
-MoveAfter none 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.
false False None
-Activate none If there is already content in the workbook the new sheet will not be active UNLESS Activate is specified. false False False
-CopySource none 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. false False None
-NoClobber none Ignored but retained for backwards compatibility. false False False

Outputs

The output type is the type of the objects that the cmdlet emits.

  • OfficeOpenXml.ExcelWorksheet

Examples

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.

Top of page

Parameters

Name Alias Description Required? Pipeline Input Default Value
-ChartType None false false
-NoLegend None false false
-ShowCategory None false false
-ShowPercent None false false
-targetData None false true (ByValue)
-title None false false

Syntax

Close-ExcelPackage [-ExcelPackage] <ExcelPackage> [[-SaveAs] <Object>] [[-Password] <String>] [-Show] [-NoSave] [-Calculate] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-ExcelPackage none Package to close. true True (ByValue) None
-Show none Open the file in Excel. false False False
-NoSave none Abandon the file without saving. false False False
-SaveAs none Save file with a new name (ignored if -NoSave Specified). false False None
-Password none Password to protect the file. false False None
-Calculate none Attempt to recalculation the workbook before saving false False False

Examples

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.

Top of page

Parameters

Name Alias Description Required? Pipeline Input Default Value
-ChartType None false false
-NoLegend None false false
-ShowCategory None false false
-ShowPercent None false false
-targetData None false true (ByValue)
-title None false false

Syntax

Compare-WorkSheet [-Referencefile] <Object> [-Differencefile] <Object> [-WorkSheetName <Object>] [-Property <Object>] [-ExcludeProperty <Object>] -Headername <String[]> [-Startrow <Int32>] [-AllDataBackgroundColor <Object>] [-BackgroundColor <Object>] [-TabColor <Object>] [-Key <Object>] [-FontColor <Object>] [-Show] [-GridView] [-PassThru] [-IncludeEqual] [-ExcludeDifferent] [<CommonParameters>]

Compare-WorkSheet [-Referencefile] <Object> [-Differencefile] <Object> [-WorkSheetName <Object>] [-Property <Object>] [-ExcludeProperty <Object>] -NoHeader [-Startrow <Int32>] [-AllDataBackgroundColor <Object>] [-BackgroundColor <Object>] [-TabColor <Object>] [-Key <Object>] [-FontColor <Object>] [-Show] [-GridView] [-PassThru] [-IncludeEqual] [-ExcludeDifferent] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Referencefile none First file to compare. true False None
-Differencefile none Second file to compare. true False None
-WorkSheetName none Name(s) of worksheets to compare. false False Sheet1
-Property none Properties to include in the comparison - supports wildcards, default is "*". false False *
-ExcludeProperty none Properties to exclude from the comparison - supports wildcards. false False None
-Headername none Specifies custom property names to use, instead of the values defined in the starting row of the sheet. true False None
-NoHeader none Automatically generate property names (P1, P2, P3 ...) instead of the using the values the starting row of the sheet. true False False
-Startrow none The row from where we start to import data: all rows above the start row are disregarded. By default, this is the first row. false False 1
-AllDataBackgroundColor none If specified, highlights all the cells - so you can make Equal cells one color, and Different cells another. false False None
-BackgroundColor none If specified, highlights the rows with differences. false False None
-TabColor none If specified identifies the tabs which contain difference rows (ignored if -BackgroundColor is omitted). false False None
-Key none Name of a column which is unique and will be used to add a row to the DIFF object, defaults to "Name". false False Name
-FontColor none If specified, highlights the DIFF columns in rows which have the same key. false False None
-Show none If specified, opens the Excel workbooks instead of outputting the diff to the console (unless -PassThru is also specified). false False False
-GridView none 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. false False False
-PassThru none If specified a full set of DIFF data is returned without filtering to the specified properties. false False False
-IncludeEqual none If specified the result will include equal rows as well. By default only different rows are returned. false False False
-ExcludeDifferent none If specified, the result includes only the rows where both are equal. false False False

Examples

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.

Top of page

Convert-ExcelRangeToImage Aliases

  • Convert-XlRangeToImage

Syntax

Convert-ExcelRangeToImage [-Path] <Object> [[-WorkSheetname] <Object>] [-Range] <Object> [[-Destination] <Object>] [-Show] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Path none Path to the Excel file true False None
-WorkSheetname none Worksheet name - if none is specified "Sheet1" will be assumed false False Sheet1
-Range none Range of cells within the sheet, e.g "A1:Z99" true False None
-Destination none A bmp, png or jpg file where the result will be saved false False "$pwd\temp.png"
-Show none If specified opens the image in the default viewer. false False False

ConvertFrom-ExcelData Aliases

  • Use-ExcelData

Parameters

Name Alias Description Required? Pipeline Input Default Value
-DataOnly None false false
-Header None false false
-HeaderRow None false false
-NoHeader None false false
-Path FullName true true (ByValue, ByPropertyName)
-ScriptBlock None false false
-WorksheetName Sheet false false

ConvertFrom-ExcelSheet Aliases

  • Export-ExcelSheet

Syntax

ConvertFrom-ExcelSheet [-Path] <String> [[-OutputPath] <String>] [[-SheetName] <String>] [[-Encoding] <Encoding>] [[-Extension] {.txt | .log | .csv}] [[-Delimiter] {; |  | }] [[-Property] <Object>] [[-ExcludeProperty] <Object>] [[-AsText] <String[]>] [[-AsDate] <String[]>] [-Append] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Append none 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. false False False
-AsText none AsText allows selected columns to be returned as the text displayed in their cells, instead of their value. (* is supported as a wildcard.) false False None
-AsDate none 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.) false False None
-Delimiter none Selects , or ; as the delimeter for the exported data - if not specified , is used by default. false False None
-Encoding none Sets the text encoding for the output data file; UTF8 bu default false False None
-ExcludeProperty none 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. false False None
-Extension none Sets the file extension for the exported data, defaults to CSV false False None
-OutputPath none 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. false False None
-Path none The path to the .XLSX file which will be exported. true False None
-Property none 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 false False None
-SheetName none The name of a sheet to export, or a regular expression which is used to identify sheets false False None

Inputs

The input type is the type of the objects that you can pipe to the cmdlet.

  • None

Outputs

The output type is the type of the objects that the cmdlet emits.

  • System.Object

Examples

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.

Top of page

Links

Syntax

ConvertFrom-ExcelToSQLInsert [-TableName] <Object> [-Path] <Object> [[-WorkSheetname] <Object>] [[-StartRow] <Int32>] [[-Header] <String[]>] [-NoHeader] [-DataOnly] [-ConvertEmptyStringsToNull] [-UseMSSQLSyntax] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-TableName none Name of the target database table. true False None
-Path FullName Path to an existing .XLSX file This parameter is passed to Import-Excel as is. true True (ByPropertyName, ByValue) None
-WorkSheetname Sheet 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. false False 1
-StartRow HeaderRow, TopRow 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. false False 0
-Header none 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. false False None
-NoHeader none 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. false False False
-DataOnly none Import only rows and columns that contain data, empty rows and empty columns are not imported. false False False
-ConvertEmptyStringsToNull none 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. false False False
-UseMSSQLSyntax none {{ Fill UseMSSQLSyntax Description }} false False False

Examples

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);

Top of page

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Force None false false
-Path None true true (ByValue)

Syntax

Copy-ExcelWorkSheet [-SourceObject] <Object> [[-SourceWorkSheet] <Object>] [-DestinationWorkbook] <Object> [[-DestinationWorksheet] <Object>] [-Show] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-SourceObject SourceWorkbook An ExcelWorkbook or ExcelPackage object or the path to an XLSx file where the data is found. true True (ByValue) None
-SourceWorkSheet none Name or number (starting from 1) of the worksheet in the source workbook (defaults to 1). false False 1
-DestinationWorkbook none An ExcelWorkbook or ExcelPackage object or the path to an XLSx file where the data should be copied. true False None
-DestinationWorksheet none 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. false False None
-Show none if the destination is an excel package or a path, launch excel and open the file on completion. false False False

Examples

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

Top of page

Parameters

Name Alias Description Required? Pipeline Input Default Value
-ChartType None false false
-NoLegend None false false
-ShowCategory None false false
-ShowPercent None false false
-targetData None false false
-title None false false

Syntax

Expand-NumberFormat [[-NumberFormat] <Object>] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-NumberFormat none The format string to Expand false False None

Outputs

The output type is the type of the objects that the cmdlet emits.

  • System.String

Examples

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.

Top of page

Syntax

Export-Excel [[-Path] <String>] [-InputObject <Object>] [-Calculate] [-Show] [-WorksheetName <String>] [-Password <String>] [-ClearSheet] [-Append] [-Title <String>] [-TitleFillPattern {None | Solid | DarkGray | MediumGray | LightGray | Gray125 | Gray0625 | DarkVertical | DarkHorizontal | DarkDown | DarkUp | DarkGrid | DarkTrellis | LightVertical | LightHorizontal | LightDown | LightUp | LightGrid | LightTrellis}] [-TitleBold] [-TitleSize <Int32>] [-TitleBackgroundColor <Object>] [-IncludePivotTable] [-PivotTableName <String>] [-PivotRows <String[]>] [-PivotColumns <String[]>] [-PivotData <Object>] [-PivotFilter <String[]>] [-PivotDataToColumn] [-PivotTableDefinition <Hashtable>] [-IncludePivotChart] [-ChartType {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}] [-NoLegend] [-ShowCategory] [-ShowPercent] [-AutoSize] [-MaxAutoSizeRows <Object>] [-NoClobber] [-FreezeTopRow] [-FreezeFirstColumn] [-FreezeTopRowFirstColumn] [-FreezePane <Int32[]>] [-AutoFilter] [-BoldTopRow] [-NoHeader] [-RangeName <String>] [-TableName <Object>] [-TableStyle {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}] [-Barchart] [-PieChart] [-LineChart] [-ColumnChart] [-ExcelChartDefinition <Object[]>] [-HideSheet <String[]>] [-UnHideSheet <String[]>] [-MoveToStart] [-MoveToEnd] [-MoveBefore <Object>] [-MoveAfter <Object>] [-KillExcel] [-AutoNameRange] [-StartRow <Int32>] [-StartColumn <Int32>] [-PassThru] [-Numberformat <String>] [-ExcludeProperty <String[]>] [-NoAliasOrScriptPropeties] [-DisplayPropertySet] [-NoNumberConversion <String[]>] [-ConditionalFormat <Object[]>] [-ConditionalText <Object[]>] [-Style <Object[]>] [-CellStyleSB <ScriptBlock>] [-Activate] [-Now] [-ReturnRange] [-PivotTotals <String>] [-NoTotalsInPivot] [-ReZip] [<CommonParameters>]

Export-Excel -ExcelPackage <ExcelPackage> [-InputObject <Object>] [-Calculate] [-Show] [-WorksheetName <String>] [-Password <String>] [-ClearSheet] [-Append] [-Title <String>] [-TitleFillPattern {None | Solid | DarkGray | MediumGray | LightGray | Gray125 | Gray0625 | DarkVertical | DarkHorizontal | DarkDown | DarkUp | DarkGrid | DarkTrellis | LightVertical | LightHorizontal | LightDown | LightUp | LightGrid | LightTrellis}] [-TitleBold] [-TitleSize <Int32>] [-TitleBackgroundColor <Object>] [-IncludePivotTable] [-PivotTableName <String>] [-PivotRows <String[]>] [-PivotColumns <String[]>] [-PivotData <Object>] [-PivotFilter <String[]>] [-PivotDataToColumn] [-PivotTableDefinition <Hashtable>] [-IncludePivotChart] [-ChartType {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}] [-NoLegend] [-ShowCategory] [-ShowPercent] [-AutoSize] [-MaxAutoSizeRows <Object>] [-NoClobber] [-FreezeTopRow] [-FreezeFirstColumn] [-FreezeTopRowFirstColumn] [-FreezePane <Int32[]>] [-AutoFilter] [-BoldTopRow] [-NoHeader] [-RangeName <String>] [-TableName <Object>] [-TableStyle {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}] [-Barchart] [-PieChart] [-LineChart] [-ColumnChart] [-ExcelChartDefinition <Object[]>] [-HideSheet <String[]>] [-UnHideSheet <String[]>] [-MoveToStart] [-MoveToEnd] [-MoveBefore <Object>] [-MoveAfter <Object>] [-KillExcel] [-AutoNameRange] [-StartRow <Int32>] [-StartColumn <Int32>] [-PassThru] [-Numberformat <String>] [-ExcludeProperty <String[]>] [-NoAliasOrScriptPropeties] [-DisplayPropertySet] [-NoNumberConversion <String[]>] [-ConditionalFormat <Object[]>] [-ConditionalText <Object[]>] [-Style <Object[]>] [-CellStyleSB <ScriptBlock>] [-Activate] [-ReturnRange] [-PivotTotals <String>] [-NoTotalsInPivot] [-ReZip] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Path none Path to a new or existing .XLSX file. false False None
-ExcelPackage none 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. true False None
-InputObject TargetData Date is usually piped into Export-Excel, but it also accepts data through the InputObject parameter false True (ByValue) None
-Calculate none If specified, a recalculation of the worksheet will be requested before saving. false False False
-Show none Opens the Excel file immediately after creation; convenient for viewing the results instantly without having to search for the file first. false False False
-WorksheetName none The name of a sheet within the workbook - "Sheet1" by default. false False Sheet1
-Password PW Sets password protection on the workbook. false False None
-ClearSheet none 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).
false False False
-Append none If specified data will be added to the end of an existing sheet, using the same column headings. false False False
-Title none Text of a title to be placed in the top left cell. false False None
-TitleFillPattern none Sets the fill pattern for the title cell. false False Solid
-TitleBold none Sets the title in boldface type. false False False
-TitleSize none Sets the point size for the title. false False 22
-TitleBackgroundColor none Sets the cell background color for the title cell. false False None
-IncludePivotTable none Adds a PivotTable using the data in the worksheet. false False False
-PivotTableName none If a PivotTable is created from command line parameters, specifies the name of the new sheet holding the pivot. Defaults to "WorksheetName-PivotTable". false False None
-PivotRows none Name(s) of column(s) from the spreadsheet which will provide the Row name(s) in a PivotTable created from command line parameters. false False None
-PivotColumns none Name(s) of columns from the spreadsheet which will provide the Column name(s) in a PivotTable created from command line parameters. false False None
-PivotData none 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.
false False None
-PivotFilter none Name(s) columns from the spreadsheet which will provide the Filter name(s) in a PivotTable created from command line parameters. false False None
-PivotDataToColumn none 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. false False False
-PivotTableDefinition none 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.
false False None
-IncludePivotChart none Include a chart with the PivotTable - implies -IncludePivotTable. false False False
-ChartType none The type for PivotChart (one of Excel's defined chart types). false False Pie
-NoLegend none Exclude the legend from the PivotChart. false False False
-ShowCategory none Add category labels to the PivotChart. false False False
-ShowPercent none Add percentage labels to the PivotChart. false False False
-AutoSize none Sizes the width of the Excel column to the maximum width needed to display all the containing data in that cell. false False False
-MaxAutoSizeRows none 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 false False 1000
-NoClobber none Not used. Left in to avoid problems with older scripts, it may be removed in future versions. false False False
-FreezeTopRow none Freezes headers etc. in the top row. false False False
-FreezeFirstColumn none Freezes titles etc. in the left column. false False False
-FreezeTopRowFirstColumn none Freezes top row and left column (equivalent to Freeze pane 2,2 ). false False False
-FreezePane none Freezes panes at specified coordinates (in the form RowNumber, ColumnNumber). false False None
-AutoFilter none Enables the Excel filter on the complete header row, so users can easily sort, filter and/or search the data in the selected column. false False False
-BoldTopRow none Makes the top row boldface. false False False
-NoHeader none Specifies that field names should not be put at the top of columns. false False False
-RangeName none Makes the data in the worksheet a named range. false False None
-TableName Table 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. false False None
-TableStyle none Selects the style for the named table - if the Tablename parameter is specified without giving a style, 'Medium6' is used as a default. false False Medium6
-Barchart none Creates a "quick" bar chart using the first text column as labels and the first numeric column as values. false False False
-PieChart none Creates a "quick" pie chart using the first text column as labels and the first numeric column as values. false False False
-LineChart none Creates a "quick" line chart using the first text column as labels and the first numeric column as values. false False False
-ColumnChart none Creates a "quick" column chart using the first text column as labels and the first numeric column as values. false False False
-ExcelChartDefinition none 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. false False None
-HideSheet none 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. false False None
-UnHideSheet none Name(s) of Sheet(s) to reveal in the workbook, supports wildcards. false False None
-MoveToStart none 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.
false False False
-MoveToEnd none 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.) false False False
-MoveBefore none 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.
false False None
-MoveAfter none 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.
false False None
-KillExcel none Closes Excel without stopping to ask if work should be saved - prevents errors writing to the file because Excel has it open. false False False
-AutoNameRange none Makes each column a named range. false False False
-StartRow none 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. false False 1
-StartColumn none Column to start adding data - 1 by default. false False 1
-PassThru PT 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. false False False
-Numberformat none 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
false False General
-ExcludeProperty none Specifies properties which may exist in the target data but should not be placed on the worksheet. false False None
-NoAliasOrScriptPropeties none 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 false False False
-DisplayPropertySet none 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. false False False
-NoNumberConversion none 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
false False None
-ConditionalFormat none One or more conditional formatting rules defined with New-ConditionalFormattingIconSet. false False None
-ConditionalText none Applies a Conditional formatting rule defined with New-ConditionalText. When specific conditions are met the format is applied. false False None
-Style none 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. false False None
-CellStyleSB none 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. false False None
-Activate none 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. false False False
-Now none The -Now switch is a shortcut that automatically creates a temporary file, enables "AutoSize", "TableName" and "Show", and opens the file immediately. false False False
-ReturnRange none If specified, Export-Excel returns the range of added cells in the format "A1:Z100". false False False
-PivotTotals none 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. false False Both
-NoTotalsInPivot none In a PivotTable created from command line parameters, prevents the addition of totals to rows and columns. false False False
-ReZip none If specified, Export-Excel will expand the contents of the .XLSX file (which is multiple files in a zip archive) and rebuild it. false False False

Outputs

The output type is the type of the objects that the cmdlet emits.

  • OfficeOpenXml.ExcelPackage

Examples

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.

Top of page

Links

Parameters

Name Alias Description Required? Pipeline Input Default Value
-ColumnNumber None false true (ByValue)

Syntax

Get-ExcelFileSummary [-Path] <Object> [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Path FullName true true (ByPropertyName)

Syntax

Get-ExcelSheetInfo [-Path] <Object> [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Path FullName Specifies the path to the Excel file. (This parameter is required.) true True (ByPropertyName, ByValue) None

Note

CHANGELOG 2016/01/07 Added Created by Johan Akerstrom (https://github.com/CosmosKey)

Examples

EXAMPLE 1
Get-ExcelSheetInfo .\Test.xlsx

Top of page

Links

Syntax

Get-ExcelWorkbookInfo [-Path] <String> [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Path FullName Specifies the path to the Excel file. This parameter is required. true True (ByPropertyName, ByValue) None

Note

CHANGELOG 2016/01/07 Added Created by Johan Akerstrom (https://github.com/CosmosKey)

Examples

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

Top of page

Links

Parameters

Name Alias Description Required? Pipeline Input Default Value
-FirstDataRow None false false
-Header None false false
-TableIndex None false false
-Url None true false
-UseDefaultCredentials None false false

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Start None false false
-Step None false false
-Stop None false false

Parameters

Name Alias Description Required? Pipeline Input Default Value
-TargetData None false false

Syntax

Import-Excel [-Path] <String> [[-WorksheetName] <String>] -NoHeader [-StartRow <Int32>] [-EndRow <Int32>] [-StartColumn <Int32>] [-EndColumn <Int32>] [-DataOnly] [-AsText <String[]>] [-AsDate <String[]>] [-Password <String>] [<CommonParameters>]

Import-Excel [-Path] <String> [[-WorksheetName] <String>] -HeaderName <String[]> [-StartRow <Int32>] [-EndRow <Int32>] [-StartColumn <Int32>] [-EndColumn <Int32>] [-DataOnly] [-AsText <String[]>] [-AsDate <String[]>] [-Password <String>] [<CommonParameters>]

Import-Excel [-Path] <String> [[-WorksheetName] <String>] [-StartRow <Int32>] [-EndRow <Int32>] [-StartColumn <Int32>] [-EndColumn <Int32>] [-DataOnly] [-AsText <String[]>] [-AsDate <String[]>] [-Password <String>] [<CommonParameters>]

Import-Excel [[-WorksheetName] <String>] -ExcelPackage <ExcelPackage> -NoHeader [-StartRow <Int32>] [-EndRow <Int32>] [-StartColumn <Int32>] [-EndColumn <Int32>] [-DataOnly] [-AsText <String[]>] [-AsDate <String[]>] [-Password <String>] [<CommonParameters>]

Import-Excel [[-WorksheetName] <String>] -ExcelPackage <ExcelPackage> -HeaderName <String[]> [-StartRow <Int32>] [-EndRow <Int32>] [-StartColumn <Int32>] [-EndColumn <Int32>] [-DataOnly] [-AsText <String[]>] [-AsDate <String[]>] [-Password <String>] [<CommonParameters>]

Import-Excel [[-WorksheetName] <String>] -ExcelPackage <ExcelPackage> [-StartRow <Int32>] [-EndRow <Int32>] [-StartColumn <Int32>] [-EndColumn <Int32>] [-DataOnly] [-AsText <String[]>] [-AsDate <String[]>] [-Password <String>] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Path FullName Specifies the path to the Excel file. true True (ByPropertyName, ByValue) None
-ExcelPackage none 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.
true False None
-WorksheetName Sheet 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. false False None
-HeaderName none 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.
true False None
-NoHeader none 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.
true False False
-StartRow HeaderRow, TopRow 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.
false False 1
-EndRow StopRow, BottomRow By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row. false False 0
-StartColumn LeftColumn The number of the first column to read data from (1 by default). false False 1
-EndColumn RightColumn By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number. false False 0
-DataOnly none Import only rows and columns that contain data, empty rows and empty columns are not imported. false False False
-AsText none 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.) false False None
-AsDate none 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.) false False None
-Password none Accepts a string that will be used to open a password protected Excel file. false False None

Examples

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.

Top of page

Links

Parameters

Name Alias Description Required? Pipeline Input Default Value
-FirstDataRow None false false
-Header None false false
-Index None false false
-Url None false false
-UseDefaultCredentials None false false

Parameters

Name Alias Description Required? Pipeline Input Default Value
-TrackingNumber None false false
-UseDefaultCredentials None false false

Parameters

Name Alias Description Required? Pipeline Input Default Value
-TrackingNumber None false false
-UseDefaultCredentials None false false

Syntax

Invoke-ExcelQuery [-Path] <String> [-Query] <String> [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Path The path to the file to open. true false
-Query var name consistent with Import-Excel
var name consistent with Invoke-Sqlcmd
true false

Examples

EXAMPLE 1
Invoke-ExcelQuery .\test.xlsx 'select ROUND(F1) as [A1] from [sheet3$A1:A1]'
EXAMPLE 2
$Path = (Get-ChildItem 'test.xlsx').FullName
$Query = "select ROUND(F1) as [A] from [sheet1$A1:A1]"
Read-XlsxUsingOleDb -Path $Path -Query $Query
EXAMPLE 3
$ReadDataArgs = @{
    Path = .\test.xlsx
    Query = Get-Content query.sql -Raw
}
$Results = Invoke-ExcelQuery @ReadDataArgs

Top of page

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Data None false false
-Dimension None false false
-Measure None false false

Syntax

Join-Worksheet [[-Path] <String>] [-WorkSheetName <Object>] [-Clearsheet] [-NoHeader] [-FromLabel <String>] [-LabelBlocks] [-AutoSize] [-FreezeTopRow] [-FreezeFirstColumn] [-FreezeTopRowFirstColumn] [-FreezePane <Int32[]>] [-AutoFilter] [-BoldTopRow] [-HideSource] [-Title <String>] [-TitleFillPattern {None | Solid | DarkGray | MediumGray | LightGray | Gray125 | Gray0625 | DarkVertical | DarkHorizontal | DarkDown | DarkUp | DarkGrid | DarkTrellis | LightVertical | LightHorizontal | LightDown | LightUp | LightGrid | LightTrellis}] [-TitleBackgroundColor <Object>] [-TitleBold] [-TitleSize <Int32>] [-PivotTableDefinition <Hashtable>] [-ExcelChartDefinition <Object[]>] [-ConditionalFormat <Object[]>] [-ConditionalText <Object[]>] [-AutoNameRange] [-RangeName <String>] [-ReturnRange] [-Show] [-PassThru] [<CommonParameters>]

Join-Worksheet [[-Path] <String>] [-WorkSheetName <Object>] [-Clearsheet] [-NoHeader] [-FromLabel <String>] [-LabelBlocks] [-AutoSize] [-FreezeTopRow] [-FreezeFirstColumn] [-FreezeTopRowFirstColumn] [-FreezePane <Int32[]>] [-BoldTopRow] [-HideSource] [-Title <String>] [-TitleFillPattern {None | Solid | DarkGray | MediumGray | LightGray | Gray125 | Gray0625 | DarkVertical | DarkHorizontal | DarkDown | DarkUp | DarkGrid | DarkTrellis | LightVertical | LightHorizontal | LightDown | LightUp | LightGrid | LightTrellis}] [-TitleBackgroundColor <Object>] [-TitleBold] [-TitleSize <Int32>] [-PivotTableDefinition <Hashtable>] [-ExcelChartDefinition <Object[]>] [-ConditionalFormat <Object[]>] [-ConditionalText <Object[]>] [-AutoNameRange] [-RangeName <String>] -TableName <String> [-TableStyle {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}] [-ReturnRange] [-Show] [-PassThru] [<CommonParameters>]

Join-Worksheet -ExcelPackage <ExcelPackage> [-WorkSheetName <Object>] [-Clearsheet] [-NoHeader] [-FromLabel <String>] [-LabelBlocks] [-AutoSize] [-FreezeTopRow] [-FreezeFirstColumn] [-FreezeTopRowFirstColumn] [-FreezePane <Int32[]>] [-BoldTopRow] [-HideSource] [-Title <String>] [-TitleFillPattern {None | Solid | DarkGray | MediumGray | LightGray | Gray125 | Gray0625 | DarkVertical | DarkHorizontal | DarkDown | DarkUp | DarkGrid | DarkTrellis | LightVertical | LightHorizontal | LightDown | LightUp | LightGrid | LightTrellis}] [-TitleBackgroundColor <Object>] [-TitleBold] [-TitleSize <Int32>] [-PivotTableDefinition <Hashtable>] [-ExcelChartDefinition <Object[]>] [-ConditionalFormat <Object[]>] [-ConditionalText <Object[]>] [-AutoNameRange] [-RangeName <String>] -TableName <String> [-TableStyle {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}] [-ReturnRange] [-Show] [-PassThru] [<CommonParameters>]

Join-Worksheet -ExcelPackage <ExcelPackage> [-WorkSheetName <Object>] [-Clearsheet] [-NoHeader] [-FromLabel <String>] [-LabelBlocks] [-AutoSize] [-FreezeTopRow] [-FreezeFirstColumn] [-FreezeTopRowFirstColumn] [-FreezePane <Int32[]>] [-AutoFilter] [-BoldTopRow] [-HideSource] [-Title <String>] [-TitleFillPattern {None | Solid | DarkGray | MediumGray | LightGray | Gray125 | Gray0625 | DarkVertical | DarkHorizontal | DarkDown | DarkUp | DarkGrid | DarkTrellis | LightVertical | LightHorizontal | LightDown | LightUp | LightGrid | LightTrellis}] [-TitleBackgroundColor <Object>] [-TitleBold] [-TitleSize <Int32>] [-PivotTableDefinition <Hashtable>] [-ExcelChartDefinition <Object[]>] [-ConditionalFormat <Object[]>] [-ConditionalText <Object[]>] [-AutoNameRange] [-RangeName <String>] [-ReturnRange] [-Show] [-PassThru] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Path none Path to a new or existing .XLSX file. false False None
-ExcelPackage none An object representing an Excel Package - either from Open-ExcelPackage or specifying -PassThru to Export-Excel. true False None
-WorkSheetName none The name of a sheet within the workbook where the other sheets will be joined together - "Combined" by default. false False Combined
-Clearsheet none If specified ,any pre-existing target for the joined data will be deleted and re-created; otherwise data will be appended on this sheet. false False False
-NoHeader none Join-Worksheet assumes each sheet has identical headers and the headers should be copied to the target sheet, unless -NoHeader is specified. false False False
-FromLabel none 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. false False From
-LabelBlocks none If specified, the copied blocks of data will have the name of the sheet they were copied from inserted above them as a title. false False False
-AutoSize none Sets the width of the Excel columns to display all the data in their cells. false False False
-FreezeTopRow none Freezes headers etc. in the top row. false False False
-FreezeFirstColumn none Freezes titles etc. in the left column. false False False
-FreezeTopRowFirstColumn none Freezes top row and left column (equivalent to Freeze pane 2,2 ). false False False
-FreezePane none Freezes panes at specified coordinates (in the formRowNumber , ColumnNumber). false False None
-AutoFilter none Enables the Excel filter on the headers of the combined sheet. false False False
-BoldTopRow none Makes the top row boldface. false False False
-HideSource none If specified, hides the sheets that the data is copied from. false False False
-Title none Text of a title to be placed in Cell A1. false False None
-TitleFillPattern none Sets the fill pattern for the title cell. false False Solid
-TitleBackgroundColor none Sets the cell background color for the title cell. false False None
-TitleBold none Sets the title in boldface type. false False False
-TitleSize none Sets the point size for the title. false False 22
-PivotTableDefinition none Hashtable(s) with Sheet PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values to specify a definition for one or morePivotTable(s). false False None
-ExcelChartDefinition none A hashtable containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-pivot] charts. false False None
-ConditionalFormat none One or more conditional formatting rules defined with New-ConditionalFormattingIconSet. false False None
-ConditionalText none Applies a Conditional formatting rule defined with New-ConditionalText. false False None
-AutoNameRange none Makes each column a named range. false False False
-RangeName none Makes the data in the worksheet a named range. false False None
-TableName none Makes the data in the worksheet a table with a name and applies a style to it. Name must not contain spaces. true False None
-TableStyle none Selects the style for the named table - defaults to "Medium6". false False Medium6
-ReturnRange none If specified, returns the range of cells in the combined sheet, in the format "A1:Z100". false False False
-Show none Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first. false False False
-PassThru none If specified, an object representing the unsaved Excel package will be returned, it then needs to be saved. false False False

Examples

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.

Top of page

Links

Parameters

Name Alias Description Required? Pipeline Input Default Value
-ChartType None false false
-NoLegend None false false
-ShowCategory None false false
-ShowPercent None false false
-targetData None false true (ByValue)
-title None false false

Syntax

Merge-MultipleSheets [-Path] <Object> [[-KeyFontColor] <Object>] [[-ChangeBackgroundColor] <Object>] [[-DeleteBackgroundColor] <Object>] [[-AddBackgroundColor] <Object>] [[-Startrow] <Int32>] [[-Headername] <String[]>] [[-WorksheetName] <Object>] [[-OutputFile] <Object>] [[-OutputSheetName] <Object>] [[-Property] <Object>] [[-ExcludeProperty] <Object>] [[-Key] <Object>] [-NoHeader] [-HideRowNumbers] [-Passthru] [-Show] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Path none Paths to the files to be merged. Files are also accepted true True (ByValue) None
-Startrow none The row from where we start to import data, all rows above the Start row are disregarded. By default this is the first row. false False 1
-Headername none Specifies custom property names to use, instead of the values defined in the column headers of the Start row. false False None
-NoHeader none If specified, property names will be automatically generated (P1, P2, P3, ..) instead of using the values from the start row. false False False
-WorksheetName none Name(s) of Worksheets to compare. false False Sheet1
-OutputFile OutFile File to write output to. false False .\temp.xlsx
-OutputSheetName OutSheet Name of Worksheet to output - if none specified will use the reference Worksheet name. false False Sheet1
-Property none Properties to include in the comparison - supports wildcards, default is "*". false False *
-ExcludeProperty none Properties to exclude from the the comparison - supports wildcards. false False None
-Key none Name of a column which is unique used to pair up rows from the reference and difference sides, default is "Name". false False Name
-KeyFontColor none Sets the font color for the Key field; this means you can filter by color to get only changed rows. false False [System.Drawing.Color]::Red
-ChangeBackgroundColor none Sets the background color for changed rows. false False [System.Drawing.Color]::Orange
-DeleteBackgroundColor none Sets the background color for rows in the reference but deleted from the difference sheet. false False [System.Drawing.Color]::LightPink
-AddBackgroundColor none Sets the background color for rows not in the reference but added to the difference sheet. false False [System.Drawing.Color]::Orange
-HideRowNumbers none If specified, hides the columns in the spreadsheet that contain the row numbers. false False False
-Passthru none If specified, outputs the data to the pipeline (you can add -whatif so it the command only outputs to the pipeline). false False False
-Show none If specified, opens the output workbook. false False False

Examples

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.

Top of page

Links

Syntax

Merge-Worksheet [-Referencefile] <Object> [-Differencefile] <Object> [[-WorksheetName] <Object>] [[-OutputFile] <Object>] [[-OutputSheetName] <Object>] [-Startrow <Int32>] -NoHeader [-Property <Object>] [-ExcludeProperty <Object>] [-Key <Object>] [-KeyFontColor <Object>] [-ChangeBackgroundColor <Object>] [-DeleteBackgroundColor <Object>] [-AddBackgroundColor <Object>] [-HideEqual] [-Passthru] [-Show] [-WhatIf] [-Confirm] [<CommonParameters>]

Merge-Worksheet [-Referencefile] <Object> [-Differencefile] <Object> [[-WorksheetName] <Object>] [[-OutputFile] <Object>] [[-OutputSheetName] <Object>] [-Startrow <Int32>] -Headername <String[]> [-Property <Object>] [-ExcludeProperty <Object>] [-Key <Object>] [-KeyFontColor <Object>] [-ChangeBackgroundColor <Object>] [-DeleteBackgroundColor <Object>] [-AddBackgroundColor <Object>] [-HideEqual] [-Passthru] [-Show] [-WhatIf] [-Confirm] [<CommonParameters>]

Merge-Worksheet [-Referencefile] <Object> [-Differencefile] <Object> [[-WorksheetName] <Object>] [[-OutputFile] <Object>] [[-OutputSheetName] <Object>] [-Startrow <Int32>] [-Property <Object>] [-ExcludeProperty <Object>] [-Key <Object>] [-KeyFontColor <Object>] [-ChangeBackgroundColor <Object>] [-DeleteBackgroundColor <Object>] [-AddBackgroundColor <Object>] [-HideEqual] [-Passthru] [-Show] [-WhatIf] [-Confirm] [<CommonParameters>]

Merge-Worksheet [-Differencefile] <Object> [[-WorksheetName] <Object>] [[-DiffPrefix] <Object>] [[-OutputFile] <Object>] [[-OutputSheetName] <Object>] [-Startrow <Int32>] -NoHeader -ReferenceObject <Object> [-Property <Object>] [-ExcludeProperty <Object>] [-Key <Object>] [-KeyFontColor <Object>] [-ChangeBackgroundColor <Object>] [-DeleteBackgroundColor <Object>] [-AddBackgroundColor <Object>] [-HideEqual] [-Passthru] [-Show] [-WhatIf] [-Confirm] [<CommonParameters>]

Merge-Worksheet [-Differencefile] <Object> [[-WorksheetName] <Object>] [[-DiffPrefix] <Object>] [[-OutputFile] <Object>] [[-OutputSheetName] <Object>] [-Startrow <Int32>] -Headername <String[]> -ReferenceObject <Object> [-Property <Object>] [-ExcludeProperty <Object>] [-Key <Object>] [-KeyFontColor <Object>] [-ChangeBackgroundColor <Object>] [-DeleteBackgroundColor <Object>] [-AddBackgroundColor <Object>] [-HideEqual] [-Passthru] [-Show] [-WhatIf] [-Confirm] [<CommonParameters>]

Merge-Worksheet [-Differencefile] <Object> [[-WorksheetName] <Object>] [[-DiffPrefix] <Object>] [[-OutputFile] <Object>] [[-OutputSheetName] <Object>] [-Startrow <Int32>] -ReferenceObject <Object> [-Property <Object>] [-ExcludeProperty <Object>] [-Key <Object>] [-KeyFontColor <Object>] [-ChangeBackgroundColor <Object>] [-DeleteBackgroundColor <Object>] [-AddBackgroundColor <Object>] [-HideEqual] [-Passthru] [-Show] [-WhatIf] [-Confirm] [<CommonParameters>]

Merge-Worksheet [-DifferenceObject] <Object> [[-DiffPrefix] <Object>] [[-OutputFile] <Object>] [[-OutputSheetName] <Object>] -ReferenceObject <Object> [-Property <Object>] [-ExcludeProperty <Object>] [-Key <Object>] [-KeyFontColor <Object>] [-ChangeBackgroundColor <Object>] [-DeleteBackgroundColor <Object>] [-AddBackgroundColor <Object>] [-HideEqual] [-Passthru] [-Show] [-WhatIf] [-Confirm] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Referencefile none 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
true False None
-Differencefile none 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
true False None
-WorksheetName none Name(s) of Worksheets to compare. Applies to all parameter sets EXCEPT D which is two objects (no sheets) false False Sheet1
-Startrow none 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 ) false False 1
-Headername none 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
true False None
-NoHeader none 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
true False False
-ReferenceObject RefObject Reference object to compare if a Worksheet is NOT being used. Reference object can combine with a difference sheet or difference object true False None
-DifferenceObject DiffObject Difference object to compare if a Worksheet is NOT being used for either half. Can't have a reference sheet and difference object. true False None
-DiffPrefix none If there isn't a filename to use to label data from the "Difference" side, DiffPrefix is used, it defaults to "=>" false False =>
-OutputFile OutFile File to hold merged data. false False None
-OutputSheetName OutSheet Name of Worksheet to output - if none specified will use the reference Worksheet name. false False Sheet1
-Property none Properties to include in the DIFF - supports wildcards, default is "*". false False *
-ExcludeProperty none Properties to exclude from the the search - supports wildcards. false False None
-Key none Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name". false False Name
-KeyFontColor none Sets the font color for the "key" field; this means you can filter by color to get only changed rows. false False [System.Drawing.Color]::DarkRed
-ChangeBackgroundColor none Sets the background color for changed rows. false False [System.Drawing.Color]::Orange
-DeleteBackgroundColor none Sets the background color for rows in the reference but deleted from the difference sheet. false False [System.Drawing.Color]::LightPink
-AddBackgroundColor none Sets the background color for rows not in the reference but added to the difference sheet. false False [System.Drawing.Color]::PaleGreen
-HideEqual none if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows. false False False
-Passthru none If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline). false False False
-Show none If specified, opens the output workbook. false False False
-WhatIf wi Shows what would happen if the cmdlet runs. The cmdlet is not run. false False False
-Confirm cf Prompts you for confirmation before running the cmdlet. false False False

Examples

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).

Top of page

Links

Syntax

New-ConditionalFormattingIconSet [-Range] <Object> [[-ConditionalFormat] <Object>] [-Reverse] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Range none The range of cells that the conditional format applies to. true False None
-ConditionalFormat none The type of rule: one of "ThreeIconSet","FourIconSet" or "FiveIconSet" false False None
-Reverse none Use the icons in the reverse order. false False False

Examples

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.

Top of page

Links

Syntax

New-ConditionalText [[-Text] <Object>] [[-ConditionalTextColor] <Object>] [[-BackgroundColor] <Object>] [[-Range] <String>] [[-PatternType] {None | Solid | DarkGray | MediumGray | LightGray | Gray125 | Gray0625 | DarkVertical | DarkHorizontal | DarkDown | DarkUp | DarkGrid | DarkTrellis | LightVertical | LightHorizontal | LightDown | LightUp | LightGrid | LightTrellis}] [[-ConditionalType] <Object>] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Text ConditionValue The text (or other value) to use in the rule. Note that Equals, GreaterThan/LessThan rules require text to wrapped in double quotes. false False None
-ConditionalTextColor ForeGroundColor The font color for the cell - by default: "DarkRed". false False [System.Drawing.Color]::DarkRed
-BackgroundColor none The fill color for the cell - by default: "LightPink". false False [System.Drawing.Color]::LightPink
-Range none 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. false False None
-PatternType none The background pattern for the cell - by default: "Solid" false False Solid
-ConditionalType RuleType One of the supported rules; by default "ContainsText" is selected. false False ContainsText

Examples

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.

Top of page

Links

New-ExcelChartDefinition Aliases

  • New-ExcelChart

Syntax

New-ExcelChartDefinition [[-Title] <Object>] [[-RowOffSetPixels] <Object>] [[-Column] <Object>] [[-ColumnOffSetPixels] <Object>] [[-LegendPosition] {Top | Left | Right | Bottom | TopRight}] [[-LegendSize] <Object>] [[-SeriesHeader] <Object>] [[-TitleSize] <Int32>] [[-XAxisTitleText] <String>] [[-XAxisTitleSize] <Object>] [[-XAxisNumberformat] <String>] [[-Header] <Object>] [[-XMajorUnit] <Object>] [[-XMinorUnit] <Object>] [[-XMaxValue] <Object>] [[-XMinValue] <Object>] [[-XAxisPosition] {Left | Bottom | Right | Top}] [[-YAxisTitleText] <String>] [[-YAxisTitleSize] <Object>] [[-YAxisNumberformat] <String>] [[-YMajorUnit] <Object>] [[-YMinorUnit] <Object>] [[-ChartType] {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}] [[-YMaxValue] <Object>] [[-YMinValue] <Object>] [[-YAxisPosition] {Left | Bottom | Right | Top}] [[-ChartTrendLine] {Exponential | Linear | Logarithmic | MovingAvgerage | Polynomial | Power}] [[-XRange] <Object>] [[-YRange] <Object>] [[-Width] <Object>] [[-Height] <Object>] [[-Row] <Object>] [-LegendBold] [-NoLegend] [-ShowCategory] [-ShowPercent] [-TitleBold] [-XAxisTitleBold] [-YAxisTitleBold] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Title none The title for the chart. false False Chart Title
-Header none No longer used. This may be removed in future versions. false False None
-ChartType none One of the built-in chart types, such as Pie, ClusteredColumn, Line etc. Defaults to "ColumnStacked". false False ColumnStacked
-ChartTrendLine none Superimposes one of Excel's trenline types on the chart. false False None
-XRange none The range of cells containing values for the X-Axis - usually labels. false False None
-YRange none The range(s) of cells holding values for the Y-Axis - usually "data". false False None
-Width none Width of the chart in pixels. Defaults to 500. false False 500
-Height none Height of the chart in pixels. Defaults to 350. false False 350
-Row none 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. false False 0
-RowOffSetPixels none Offset to position the chart by a fraction of a row. false False 10
-Column none 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. false False 6
-ColumnOffSetPixels none Offset to position the chart by a fraction of a column. false False 5
-LegendPosition none Location of the key, either "Left", "Right", "Top", "Bottom" or "TopRight". false False None
-LegendSize none Font size for the key. false False None
-LegendBold none Sets the key in bold type. false False False
-NoLegend none 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. false False False
-ShowCategory none Attaches a category label in charts which support this. false False False
-ShowPercent none Attaches a percentage label in charts which support this. false False False
-SeriesHeader none Specifies explicit name(s) for the data series, which will appear in the legend/key false False None
-TitleBold none Sets the title in bold face. false False False
-TitleSize none Sets the point size for the title. false False 0
-XAxisTitleText none Specifies a title for the X-axis. false False None
-XAxisTitleBold none Sets the X-axis title in bold face. false False False
-XAxisTitleSize none Sets the font size for the axis title. false False None
-XAxisNumberformat none A number formatting string, like "#,##0.00", for numbers along the X-axis. false False None
-XMajorUnit none Spacing for the major gridlines / tick marks along the X-axis. false False None
-XMinorUnit none Spacing for the minor gridlines / tick marks along the X-axis. false False None
-XMaxValue none Maximum value for the scale along the X-axis. false False None
-XMinValue none Minimum value for the scale along the X-axis. false False None
-XAxisPosition none Position for the X-axis ("Top" or" Bottom"). false False None
-YAxisTitleText none Specifies a title for the Y-axis. false False None
-YAxisTitleBold none Sets the Y-axis title in bold face. false False False
-YAxisTitleSize none Sets the font size for the Y-axis title. false False None
-YAxisNumberformat none A number formatting string, like "#,##0.00", for numbers on the Y-axis false False None
-YMajorUnit none Spacing for the major gridlines / tick marks on the Y-axis. false False None
-YMinorUnit none Spacing for the minor gridlines / tick marks on the Y-axis. false False None
-YMaxValue none Maximum value on the Y-axis. false False None
-YMinValue none Minimum value on the Y-axis. false False None
-YAxisPosition none Position for the Y-axis ("Left" or "Right"). false False None

Examples

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 .

Top of page

Parameters

Name Alias Description Required? Pipeline Input Default Value
-ArrayFormula None false false
-AutoSize AutoFit false false
-BackgroundColor None false false
-BackgroundPattern None false false
-Bold None false false
-BorderAround None false false
-BorderBottom None false false
-BorderColor None false false
-BorderLeft None false false
-BorderRight None false false
-BorderTop None false false
-FontColor ForegroundColor false false
-FontName None false false
-FontShift None false false
-FontSize None false false
-Formula None false false
-Height None false false
-Hidden Hide false false
-HorizontalAlignment None false false
-Italic None false false
-Locked None false false
-Merge None false false
-NumberFormat NFormat false false
-PatternColor PatternColour false false
-Range Address false false
-ResetFont None false false
-StrikeThru None false false
-TextRotation None false false
-UnderLineType None false false
-Underline None false false
-Value None false false
-VerticalAlignment None false false
-Width None false false
-WrapText None false false

Syntax

New-PivotTableDefinition -PivotTableName <Object> [-SourceWorkSheet <Object>] [-SourceRange <Object>] [-PivotRows <Object>] [-PivotData <Hashtable>] [-PivotColumns <Object>] [-PivotFilter <Object>] [-PivotDataToColumn] [-PivotTotals <String>] [-NoTotalsInPivot] [-GroupDateRow <String>] [-GroupDatePart {Years | Quarters | Months | Days | Hours | Minutes | Seconds}] [-GroupNumericRow <String>] [-GroupNumericMin <Double>] [-GroupNumericMax <Double>] [-GroupNumericInterval <Double>] [-PivotNumberFormat <String>] [-PivotTableStyle {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}] -PivotChartDefinition <Object> [-Activate] [<CommonParameters>]

New-PivotTableDefinition -PivotTableName <Object> [-SourceWorkSheet <Object>] [-SourceRange <Object>] [-PivotRows <Object>] [-PivotData <Hashtable>] [-PivotColumns <Object>] [-PivotFilter <Object>] [-PivotDataToColumn] [-PivotTotals <String>] [-NoTotalsInPivot] [-GroupDateRow <String>] [-GroupDatePart {Years | Quarters | Months | Days | Hours | Minutes | Seconds}] [-GroupNumericRow <String>] [-GroupNumericMin <Double>] [-GroupNumericMax <Double>] [-GroupNumericInterval <Double>] [-PivotNumberFormat <String>] [-PivotTableStyle {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}] [-IncludePivotChart] [-ChartTitle <String>] [-ChartHeight <Int32>] [-ChartWidth <Int32>] [-ChartRow <Int32>] [-ChartColumn <Int32>] [-ChartRowOffSetPixels <Int32>] [-ChartColumnOffSetPixels <Int32>] [-ChartType {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}] [-NoLegend] [-ShowCategory] [-ShowPercent] [-Activate] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-PivotTableName PivtoTableName 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
true False None
-SourceWorkSheet none Worksheet where the data is found false False None
-SourceRange none 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. false False None
-PivotRows none Fields to set as rows in the PivotTable false False None
-PivotData none A hash-table in form "FieldName"="Function", where function is one of Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP false False None
-PivotColumns none Fields to set as columns in the PivotTable false False None
-PivotFilter none Fields to use to filter in the PivotTable false False None
-PivotDataToColumn none 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. false False False
-PivotTotals none 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. false False Both
-NoTotalsInPivot none Included for compatibility - equivalent to -PivotTotals "None" false False False
-GroupDateRow none The name of a row field which should be grouped by parts of the date/time (ignored if GroupDateRow is not specified) false False None
-GroupDatePart none The Part(s) of the date to use in the grouping (ignored if GroupDateRow is not specified) false False None
-GroupNumericRow none The name of a row field which should be grouped by Number (e.g 0-99, 100-199, 200-299 ) false False None
-GroupNumericMin none The starting point for grouping false False 0
-GroupNumericMax none The endpoint for grouping false False 1.79769313486232E+308
-GroupNumericInterval none The interval for grouping false False 100
-PivotNumberFormat none Number format to apply to the data cells in the PivotTable false False None
-PivotTableStyle none Apply a table style to the PivotTable false False None
-PivotChartDefinition none Use a chart definition instead of specifying chart settings one by one true True (ByPropertyName) None
-IncludePivotChart none If specified a chart Will be included. false False False
-ChartTitle none Optional title for the pivot chart, by default the title omitted. false False None
-ChartHeight none Height of the chart in Pixels (400 by default) false False 400
-ChartWidth none Width of the chart in Pixels (600 by default) false False 600
-ChartRow none 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). false False 0
-ChartColumn none 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) false False 4
-ChartRowOffSetPixels none Vertical offset of the chart from the cell corner. false False 0
-ChartColumnOffSetPixels none Horizontal offset of the chart from the cell corner. false False 0
-ChartType none Type of chart false False Pie
-NoLegend none If specified hides the chart legend false False False
-ShowCategory none 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. false False False
-ShowPercent none If specified attaches percentages to slices in a pie chart. false False False
-Activate none If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified false False False

Examples

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.

Top of page

Parameters

Name Alias Description Required? Pipeline Input Default Value

Parameters

Name Alias Description Required? Pipeline Input Default Value

Syntax

Open-ExcelPackage [-Path] <Object> [[-Password] <String>] [-KillExcel] [-Create] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Path none The path to the file to open. true False None
-KillExcel none 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. false False False
-Password none The password for a protected worksheet, as a [normal] string (not a secure string). false False None
-Create none By default Open-ExcelPackage will only open an existing file; -Create instructs it to create a new file if required. false False False

Outputs

The output type is the type of the objects that the cmdlet emits.

  • OfficeOpenXml.ExcelPackage

Examples

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.

Top of page

Parameters

Name Alias Description Required? Pipeline Input Default Value
-ChartType None false false
-NoLegend None false false
-ShowCategory None false false
-ShowPercent None false false
-targetData None false true (ByValue)
-title None false false

Parameters

Name Alias Description Required? Pipeline Input Default Value
-ChartType None false false
-pivotData None false false
-pivotRows None false false
-targetData None false false

Syntax

Read-Clipboard [[-Delimiter] <Object>] [[-Header] <Object>] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Delimiter false false
-Header false false

Examples

EXAMPLE 1
Read-Clipboard # Detects if the clipboard contains CSV, JSON, or Tab delimited data.
EXAMPLE 2
Read-Clipboard -Delimiter '|' # Converts data using a pipe delimiter
EXAMPLE 3
Read-Clipboard -Header 'P1', 'P2', 'P3' # Specify the header columns to be used

Top of page

Syntax

Read-OleDbData [-ConnectionString] <String> [-SqlStatement] <String> [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-ConnectionString true false
-SqlStatement true false

Examples

EXAMPLE 1
Read-OleDbData `
    -ConnectionString "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=file.xlsx;Extended Properties='Excel 12.0 Xml;HDR=NO;IMEX=1;'" `
    -SqlStatement "select ROUND(F1) as [A] from [sheet1$A1:A1]"
EXAMPLE 2
$ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=file.xlsx;Extended Properties='Excel 12.0 Xml;HDR=NO;IMEX=1;'"
$SqlStatement = "select ROUND(F1) as [A] from [sheet1$A1:A1]"
Read-OleDbData -ConnectionString $ConnectionString -SqlStatement $SqlStatement
EXAMPLE 3
$ReadDataArgs = @{
    SqlStatement = Get-Content query.sql -Raw
    ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=file.xlsx;Extended Properties='Excel 12.0 Xml;HDR=NO;IMEX=1;'"
}
$Results = Read-OleDbData @ReadDataArgs

Top of page

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Delimiter None false false
-Header None false false
-data None true false

Syntax

Remove-WorkSheet [[-FullName] <Object>] [[-WorksheetName] <String[]>] [-Show] [-WhatIf] [-Confirm] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-FullName Path The fully qualified path to the XLSX file(s) false True (ByPropertyName) None
-WorksheetName none The worksheet to be removed (sheet1 by default) false False Sheet1
-Show none If specified the file will be opened in excel after the sheet is removed. false False False
-WhatIf wi Shows what would happen if the cmdlet runs. The cmdlet is not run. false False False
-Confirm cf Prompts you for confirmation before running the cmdlet. false False False

Examples

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

Top of page

Syntax

Select-Worksheet [-ExcelPackage] <ExcelPackage> [-WorksheetName <String>] [<CommonParameters>]

Select-Worksheet -ExcelWorkbook <ExcelWorkbook> [-WorksheetName <String>] [<CommonParameters>]

Select-Worksheet -ExcelWorksheet <ExcelWorksheet> [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-ExcelPackage none An object representing an ExcelPackage. true True (ByValue) None
-ExcelWorkbook none 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. true False None
-WorksheetName none The name of the worksheet "Sheet1" by default. false False None
-ExcelWorksheet none An object representing an Excel worksheet. true False None

Examples

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.

Top of page

Syntax

Send-SQLDataToExcel -Connection <Object> -SQL <String> [-QueryTimeout <Int32>] [-Force] [<CommonParameters>]

Send-SQLDataToExcel -Connection <Object> -MsSQLserver [-DataBase <String>] -SQL <String> [-QueryTimeout <Int32>] [-Force] [<CommonParameters>]

Send-SQLDataToExcel -Session <Object> -SQL <String> [-QueryTimeout <Int32>] [-Force] [<CommonParameters>]

Send-SQLDataToExcel [-QueryTimeout <Int32>] -DataTable <DataTable> [-Force] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Connection none 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.
true False None
-Session none An active ODBC Connection or SQL connection object representing a session with a database which will be queried to get the data . true False None
-MsSQLserver none Specifies the connection string is for SQL server, not ODBC. true False False
-DataBase none Switches to a specific database on a SQL server. false False None
-SQL none The SQL query to run against the session which was passed in -Session or set up from -Connection. true False None
-QueryTimeout none Override the default query time of 30 seconds. false False 0
-DataTable none 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. true False None
-Force none If specified Export-Excel will be called with parameters specified, even if there is no data to send false False False

Examples

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

Top of page

Links

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Color None false false
-LastColumn None false false
-Pattern None false false
-Row None false false
-Worksheet None false false

Set-ExcelColumn Aliases

  • Set-Column

Syntax

Set-ExcelColumn -ExcelPackage <ExcelPackage> [-Worksheetname <String>] [-Column <Object>] [-StartRow <Int32>] [-Value <Object>] [-Heading <Object>] [-NumberFormat <Object>] [-BorderAround {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-FontColor <Object>] [-Bold] [-Italic] [-Underline] [-UnderLineType {None | Single | Double | SingleAccounting | DoubleAccounting}] [-StrikeThru] [-FontShift {None | Baseline | Subscript | Superscript}] [-FontName <String>] [-FontSize <Single>] [-BackgroundColor <Object>] [-BackgroundPattern {None | Solid | DarkGray | MediumGray | LightGray | Gray125 | Gray0625 | DarkVertical | DarkHorizontal | DarkDown | DarkUp | DarkGrid | DarkTrellis | LightVertical | LightHorizontal | LightDown | LightUp | LightGrid | LightTrellis}] [-PatternColor <Object>] [-WrapText] [-HorizontalAlignment {General | Left | Center | CenterContinuous | Right | Fill | Distributed | Justify}] [-VerticalAlignment {Top | Center | Bottom | Distributed | Justify}] [-TextRotation <Int32>] [-AutoSize] [-Width <Single>] [-AutoNameRange] [-Hide] [-Specified] [-PassThru] [<CommonParameters>]

Set-ExcelColumn -Worksheet <ExcelWorksheet> [-Column <Object>] [-StartRow <Int32>] [-Value <Object>] [-Heading <Object>] [-NumberFormat <Object>] [-BorderAround {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-FontColor <Object>] [-Bold] [-Italic] [-Underline] [-UnderLineType {None | Single | Double | SingleAccounting | DoubleAccounting}] [-StrikeThru] [-FontShift {None | Baseline | Subscript | Superscript}] [-FontName <String>] [-FontSize <Single>] [-BackgroundColor <Object>] [-BackgroundPattern {None | Solid | DarkGray | MediumGray | LightGray | Gray125 | Gray0625 | DarkVertical | DarkHorizontal | DarkDown | DarkUp | DarkGrid | DarkTrellis | LightVertical | LightHorizontal | LightDown | LightUp | LightGrid | LightTrellis}] [-PatternColor <Object>] [-WrapText] [-HorizontalAlignment {General | Left | Center | CenterContinuous | Right | Fill | Distributed | Justify}] [-VerticalAlignment {Top | Center | Bottom | Distributed | Justify}] [-TextRotation <Int32>] [-AutoSize] [-Width <Single>] [-AutoNameRange] [-Hide] [-Specified] [-PassThru] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-ExcelPackage none If specifying the worksheet by name, the ExcelPackage object which contains the worksheet also needs to be passed. true False None
-Worksheetname none The sheet to update can be given as a name or an Excel Worksheet object - this sets it by name. false False Sheet1
-Worksheet none This passes the worksheet object instead of passing a sheet name and an Excelpackage object. true False None
-Column none Column to fill down - the first column is 1. 0 will be interpreted as first empty column. false True (ByValue) 0
-StartRow none First row to fill data in. false False 0
-Value none A value, formula or scriptblock to fill in. A script block can use $worksheet, $row, $column [number], $columnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn. false False None
-Heading none Optional column heading. false False None
-NumberFormat NFormat 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. false False None
-BorderAround none Style of border to draw around the row. false False None
-FontColor none Colour for the text - if none specified it will be left as it it is. false False None
-Bold none Make text bold; use -Bold:$false to remove bold. false False False
-Italic none Make text italic; use -Italic:$false to remove italic. false False False
-Underline none Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. false False False
-UnderLineType none Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". false False Single
-StrikeThru none Strike through text; use -StrikeThru:$false to remove strike through. false False False
-FontShift none Subscript or Superscript (or None). false False None
-FontName none Font to use - Excel defaults to Calibri. false False None
-FontSize none Point size for the text. false False 0
-BackgroundColor none Change background color. false False None
-BackgroundPattern none Background pattern - "Solid" by default. false False Solid
-PatternColor PatternColour Secondary color for background pattern. false False None
-WrapText none Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. false False False
-HorizontalAlignment none Position cell contents to Left, Right, Center etc. Default is "General". false False None
-VerticalAlignment none Position cell contents to Top, Bottom or Center. false False None
-TextRotation none Degrees to rotate text; up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise. false False 0
-AutoSize AutoFit Attempt to auto-fit cells to the width their contents. false False False
-Width none Set cells to a fixed width, ignored if -AutoSize is specified. false False 0
-AutoNameRange none Set the inserted data to be a named range. false False False
-Hide Hidden Hide the column. false False False
-Specified none If specified, returns the range of cells which were affected. false False False
-PassThru none If specified, return an object representing the Column, to allow further work to be done on it. false False False

Outputs

The output type is the type of the objects that the cmdlet emits.

  • OfficeOpenXml.ExcelColumn System.String

Examples

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.

Top of page

Set-ExcelRange Aliases

  • Set-Format

Syntax

Set-ExcelRange [[-Range] <Object>] [-WorkSheet <ExcelWorksheet>] [-NumberFormat <Object>] [-BorderAround {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderColor <Object>] [-BorderBottom {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderTop {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderLeft {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderRight {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-FontColor <Object>] [-Value <Object>] [-Formula <Object>] [-ArrayFormula] [-ResetFont] [-Bold] [-Italic] [-Underline] [-UnderLineType {None | Single | Double | SingleAccounting | DoubleAccounting}] [-StrikeThru] [-FontShift {None | Baseline | Subscript | Superscript}] [-FontName <String>] [-FontSize <Single>] [-BackgroundColor <Object>] [-BackgroundPattern {None | Solid | DarkGray | MediumGray | LightGray | Gray125 | Gray0625 | DarkVertical | DarkHorizontal | DarkDown | DarkUp | DarkGrid | DarkTrellis | LightVertical | LightHorizontal | LightDown | LightUp | LightGrid | LightTrellis}] [-PatternColor <Object>] [-WrapText] [-HorizontalAlignment {General | Left | Center | CenterContinuous | Right | Fill | Distributed | Justify}] [-VerticalAlignment {Top | Center | Bottom | Distributed | Justify}] [-TextRotation <Int32>] [-AutoSize] [-Width <Single>] [-Height <Single>] [-Hidden] [-Locked] [-Merge] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-Range Address One or more row(s), Column(s) and/or block(s) of cells to format. false True (ByValue) None
-WorkSheet none The worksheet where the format is to be applied. false False None
-NumberFormat NFormat 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. false False None
-BorderAround none Style of border to draw around the range. false False None
-BorderColor none Color of the border. false False [System.Drawing.Color]::Black
-BorderBottom none Style for the bottom border. false False None
-BorderTop none Style for the top border. false False None
-BorderLeft none Style for the left border. false False None
-BorderRight none Style for the right border. false False None
-FontColor ForegroundColor Colour for the text - if none is specified it will be left as it is. false False None
-Value none Value for the cell. false False None
-Formula none Formula for the cell. false False None
-ArrayFormula none Specifies formula should be an array formula (a.k.a CSE [ctrl-shift-enter] formula). false False False
-ResetFont none Clear Bold, Italic, StrikeThrough and Underline and set color to Black. false False False
-Bold none Make text bold; use -Bold:$false to remove bold. false False False
-Italic none Make text italic; use -Italic:$false to remove italic. false False False
-Underline none Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. false False False
-UnderLineType none Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". false False Single
-StrikeThru none Strike through text; use -Strikethru:$false to remove Strike through false False False
-FontShift none Subscript or Superscript (or none). false False None
-FontName none Font to use - Excel defaults to Calibri. false False None
-FontSize none Point size for the text. false False 0
-BackgroundColor none Change background color. false False None
-BackgroundPattern none Background pattern - Solid by default. false False Solid
-PatternColor PatternColour Secondary color for background pattern. false False None
-WrapText none Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. false False False
-HorizontalAlignment none Position cell contents to Left, Right, Center etc. default is 'General'. false False None
-VerticalAlignment none Position cell contents to Top, Bottom or Center. false False None
-TextRotation none Degrees to rotate text; up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise. false False 0
-AutoSize AutoFit Autofit cells to width (columns or ranges only). false False False
-Width none Set cells to a fixed width (columns or ranges only), ignored if Autosize is specified. false False 0
-Height none Set cells to a fixed height (rows or ranges only). false False 0
-Hidden Hide Hide a row or column (not a range); use -Hidden:$false to unhide. false False False
-Locked none 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. false False False
-Merge none Merges cells - it is recommended that you explicitly set -HorizontalAlignment false False False

Examples

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.

Top of page

Set-ExcelRow Aliases

  • Set-Row

Syntax

Set-ExcelRow -ExcelPackage <ExcelPackage> [-Worksheetname <Object>] [-Row <Object>] [-StartColumn <Int32>] [-Value <Object>] [-Heading <Object>] [-HeadingBold] [-HeadingSize <Int32>] [-NumberFormat <Object>] [-BorderAround {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderColor <Object>] [-BorderBottom {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderTop {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderLeft {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderRight {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-FontColor <Object>] [-Bold] [-Italic] [-Underline] [-UnderLineType {None | Single | Double | SingleAccounting | DoubleAccounting}] [-StrikeThru] [-FontShift {None | Baseline | Subscript | Superscript}] [-FontName <String>] [-FontSize <Single>] [-BackgroundColor <Object>] [-BackgroundPattern {None | Solid | DarkGray | MediumGray | LightGray | Gray125 | Gray0625 | DarkVertical | DarkHorizontal | DarkDown | DarkUp | DarkGrid | DarkTrellis | LightVertical | LightHorizontal | LightDown | LightUp | LightGrid | LightTrellis}] [-PatternColor <Object>] [-WrapText] [-HorizontalAlignment {General | Left | Center | CenterContinuous | Right | Fill | Distributed | Justify}] [-VerticalAlignment {Top | Center | Bottom | Distributed | Justify}] [-TextRotation <Int32>] [-Height <Single>] [-Hide] [-ReturnRange] [-PassThru] [<CommonParameters>]

Set-ExcelRow -Worksheet <ExcelWorksheet> [-Row <Object>] [-StartColumn <Int32>] [-Value <Object>] [-Heading <Object>] [-HeadingBold] [-HeadingSize <Int32>] [-NumberFormat <Object>] [-BorderAround {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderColor <Object>] [-BorderBottom {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderTop {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderLeft {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-BorderRight {None | Hair | Dotted | DashDot | Thin | DashDotDot | Dashed | MediumDashDotDot | MediumDashed | MediumDashDot | Thick | Medium | Double}] [-FontColor <Object>] [-Bold] [-Italic] [-Underline] [-UnderLineType {None | Single | Double | SingleAccounting | DoubleAccounting}] [-StrikeThru] [-FontShift {None | Baseline | Subscript | Superscript}] [-FontName <String>] [-FontSize <Single>] [-BackgroundColor <Object>] [-BackgroundPattern {None | Solid | DarkGray | MediumGray | LightGray | Gray125 | Gray0625 | DarkVertical | DarkHorizontal | DarkDown | DarkUp | DarkGrid | DarkTrellis | LightVertical | LightHorizontal | LightDown | LightUp | LightGrid | LightTrellis}] [-PatternColor <Object>] [-WrapText] [-HorizontalAlignment {General | Left | Center | CenterContinuous | Right | Fill | Distributed | Justify}] [-VerticalAlignment {Top | Center | Bottom | Distributed | Justify}] [-TextRotation <Int32>] [-Height <Single>] [-Hide] [-ReturnRange] [-PassThru] [<CommonParameters>]

Parameters

Name Alias Description Required? Pipeline Input Default Value
-ExcelPackage none An Excel package object - for example from Export-Excel -PassThru - if specified requires a sheet name to be passed a parameter. true False None
-Worksheetname none The name of the sheet to update in the package. false False Sheet1
-Worksheet none A worksheet object instead of passing a name and package. true False None
-Row none Row to fill right - first row is 1. 0 will be interpreted as first unused row. false True (ByValue) 0
-StartColumn none Position in the row to start from. false False 0
-Value none Value, Formula or ScriptBlock to fill in. A ScriptBlock can use $worksheet, $row, $Column [number], $ColumnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn. false False None
-Heading none Optional row-heading. false False None
-HeadingBold none Set the heading in bold type. false False False
-HeadingSize none Change the font-size of the heading. false False 0
-NumberFormat NFormat Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc. false False None
-BorderAround none Style of border to draw around the row. false False None
-BorderColor none Color of the border. false False [System.Drawing.Color]::Black
-BorderBottom none Style for the bottom border. false False None
-BorderTop none Style for the top border. false False None
-BorderLeft none Style for the left border. false False None
-BorderRight none Style for the right border. false False None
-FontColor none Color for the text - if not specified the font will be left as it it is. false False None
-Bold none Make text bold; use -Bold:$false to remove bold. false False False
-Italic none Make text italic; use -Italic:$false to remove italic. false False False
-Underline none Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. false False False
-UnderLineType none Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". false False Single
-StrikeThru none Strike through text; use -StrikeThru:$false to remove strike through. false False False
-FontShift none Subscript or Superscript (or none). false False None
-FontName none Font to use - Excel defaults to Calibri. false False None
-FontSize none Point size for the text. false False 0
-BackgroundColor none Change background color. false False None
-BackgroundPattern none Background pattern - solid by default. false False Solid
-PatternColor PatternColour Secondary color for background pattern. false False None
-WrapText none Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. false False False
-HorizontalAlignment none Position cell contents to Left, Right, Center etc. default is 'General'. false False None
-VerticalAlignment none Position cell contents to Top, Bottom or Center. false False None
-TextRotation none Degrees to rotate text. Up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise. false False 0
-Height none Set cells to a fixed height. false False 0
-Hide Hidden Hide the row. false False False
-ReturnRange none If sepecified, returns the range of cells which were affected. false False False
-PassThru none If Specified, return a row object to allow further work to be done. false False False

Outputs

The output type is the type of the objects that the cmdlet emits.

  • OfficeOpenXml.ExcelRow System.String

Examples

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.

Top of page

Parameters

Name Alias Description Required? Pipeline Input Default Value
-AllowAll None false false
-AllowAutoFilter None false false
-AllowDeleteColumns None false false
-AllowDeleteRows None false false
-AllowFormatCells None false false
-AllowFormatColumns None false false
-AllowFormatRows None false false
-AllowInsertColumns None false false
-AllowInsertHyperlinks None false false
-AllowInsertRows None false false
-AllowPivotTables None false false
-AllowSort None false false
-BlockEditObject None false false
-BlockEditScenarios None false false
-BlockSelectLockedCells None false false
-BlockSelectUnlockedCells None false false
-IsProtected None false false
-LockAddress None false false
-UnLockAddress None false false
-Worksheet None true false

Parameters

Name Alias Description Required? Pipeline Input Default Value
-p None false false

Parameters

Name Alias Description Required? Pipeline Input Default Value
-p None false false

Parameters

Name Alias Description Required? Pipeline Input Default Value
-p None false false

Parameters

Name Alias Description Required? Pipeline Input Default Value
-p None false false

Parameters

Name Alias Description Required? Pipeline Input Default Value
-p None false false

Syntax

Update-FirstObjectProperties [<CommonParameters>]

Note

CHANGELOG 2017/06/08 Function born

Examples

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.

Top of page

Links