Blitz on spelling mistakes in help. Still not 100% proof-read.

This commit is contained in:
jhoneill
2018-09-28 12:07:22 +01:00
parent c1d778ef85
commit a2dd42fc80
9 changed files with 296 additions and 289 deletions

View File

@@ -1,7 +1,7 @@
Function Add-ConditionalFormatting {
<#
.Synopsis
Adds contitional formatting to worksheet.
Adds conditional formatting to worksheet.
.Description
Conditional formatting allows excel to
* Mark cells with Icons depending on their value
@@ -20,7 +20,7 @@
$excel.Save() ; $excel.Dispose()
Here Export-Excel is called with the -passThru parameter so the Excel Package object is stored in $Excel
The desired worksheet is selected and the then columns B and i are conditially formatted (excluding the top row) to show red text if
The desired worksheet is selected and the then columns" B" and "I" are conditionally formatted (excluding the top row) to show red text if
the columns contain "2003" or "Disabled respectively. A fixed date format is then applied to columns D..G, and the top row is formatted.
Finally the workbook is saved and the Excel object closed.
.Example
@@ -31,7 +31,7 @@
Again Export-Excel has been called with -passthru leaving a package object in $Excel
This time B1:B100 has been conditionally formatted with 3 icons, using the flags icon set.
Add-ConditionalFormatting does not provide access to every option in the formatting rule, so passthru has been used and the
rule is to apply the flags in reverse order, and boundaries for the number which will set the split are set to 100 and 1000
rule is modified to apply the flags in reverse order, and boundaries for the number which will set the split are set to 100 and 1000
.Example
Add-ConditionalFormatting -WorkSheet $sheet -Range "D2:D1048576" -DataBarColor Red
@@ -39,8 +39,8 @@
.Example
Add-ConditionalFormatting -Address $worksheet.cells["FinishPosition"] -RuleType Equal -ConditionValue 1 -ForeGroundColor Purple -Bold -Priority 1 -StopIfTrue
In this example a named range is used to select the cells where the formula should apply. If a cell in the "FinishPosition" range is 1, then the text is turned to puple, boldface.
This rule is move to first in the priority list, and where cells have a value of 1, no other rules will be processed.
In this example a named range is used to select the cells where the formula should apply. If a cell in the "FinishPosition" range is 1, then the text is turned to Bold & Purple.
This rule is moved to first in the priority list, and where cells have a value of 1, no other rules will be processed.
#>
Param (
#A block of cells to format - you can use a named range with -Address $ws.names[1] or $ws.cells["RangeName"]
@@ -49,14 +49,14 @@
$Address ,
#The worksheet where the format is to be applied
[OfficeOpenXml.ExcelWorksheet]$WorkSheet ,
#One of the standard named rules - Top / Bottom / Less than / Greater than / Contains etc.
#A standard named-rule - Top / Bottom / Less than / Greater than / Contains etc.
[Parameter(Mandatory = $true, ParameterSetName = "NamedRule", Position = 1)]
[OfficeOpenXml.ConditionalFormatting.eExcelConditionalFormattingRuleType]$RuleType ,
#Text colour for matching objects
[Parameter(ParameterSetName = "NamedRule")]
[Alias("ForeGroundColour")]
[System.Drawing.Color]$ForeGroundColor,
#colour for databar type charts
#Colour for databar type charts
[Parameter(Mandatory = $true, ParameterSetName = "DataBar")]
[Alias("DataBarColour")]
[System.Drawing.Color]$DataBarColor,
@@ -75,7 +75,7 @@
[Parameter(ParameterSetName = "FourIconSet")]
[Parameter(ParameterSetName = "FiveIconSet")]
[switch]$Reverse,
#A value for the condition (e.g. 2000 if the test is 'lessthan 2000' ; Formulas should begin with "=" )
#A value for the condition (for example 2000 if the test is 'lessthan 2000'; Formulas should begin with "=" )
[Parameter(ParameterSetName = "NamedRule")]
$ConditionValue,
#A second value for the conditions like "between x and Y"
@@ -108,7 +108,7 @@
#Prevent the processing of subsequent rules
[Parameter(ParameterSetName = "NamedRule")]
[switch]$StopIfTrue,
#Set the sequence for rule processong
#Set the sequence for rule processing
[int]$Priority,
#If specified pass the rule back to the caller to allow additional customization.
[switch]$Passthru

View File

@@ -39,7 +39,7 @@
.PARAMETER IncludePivotTable
Adds a Pivot table using the data in the worksheet.
.PARAMETER PivotTableName
If a Pivot table is created from command line parameters, specifies the name of the new sheet holding the pivot. If Omitted this will be "WorksheetName-PivotTable"
If a Pivot table is created from command line parameters, specifies the name of the new sheet holding the pivot. Defaults to "WorksheetName-PivotTable"
.PARAMETER PivotRows
Name(s) columns from the spreadsheet which will provide the Row name(s) in a pivot table created from command line parameters.
.PARAMETER PivotColumns
@@ -47,7 +47,7 @@
.PARAMETER PivotFilter
Name(s) columns from the spreadsheet which will provide the Filter name(s) in a pivot table created from command line parameters.
.PARAMETER PivotData
In a pivot table created from command line parameters, the fields to use in the table body are given as a Hash table in the form ColumnName = Average|Count|CountNums|Max|Min|Product|None|StdDev|StdDevP|Sum|Var|VarP .
In a pivot table created from command line parameters, the fields to use in the table body are given as a Hash table in the form ColumnName = Average|Count|CountNums|Max|Min|Product|None|StdDev|StdDevP|Sum|Var|VarP.
.PARAMETER PivotDataToColumn
If there are multiple datasets in a PivotTable, by default they are shown as separate rows under the given row heading; this switch makes them separate columns.
.PARAMETER NoTotalsInPivot
@@ -55,7 +55,7 @@
.PARAMETER PivotTotals
By default, Pivot tables have totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected.
.PARAMETER PivotTableDefinition
Instead of describing a single pivot table with multiple commandline parameters; you can use a HashTable in the form PivotTableName = Definition;
Instead of describing a single pivot table with multiple commandline parameters; you can use a hashTable in the form PivotTableName = Definition;
Definition is itself a hashtable with Sheet, PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values.
.PARAMETER IncludePivotChart
Include a chart with the Pivot table - implies -IncludePivotTable.
@@ -124,7 +124,7 @@
.PARAMETER FreezeTopRowFirstColumn
Freezes top row and left column (equivalent to Freeze pane 2,2 ).
.PARAMETER FreezePane
Freezes panes at specified coordinates (in the form RowNumber , ColumnNumber).
Freezes panes at specified coordinates (in the form RowNumber, ColumnNumber).
.PARAMETER AutoFilter
Enables the 'Filter' in Excel on the complete header row, so users can easily sort, filter and/or search the data in the selected column from within Excel.
.PARAMETER AutoSize
@@ -173,8 +173,8 @@
.PARAMETER ReturnRange
If specified, Export-Excel returns the range of added cells in the format "A1:Z100"
.PARAMETER PassThru
If specified, Export-Excel returns an object representing the Excel package without saving the package first. To save it you need to call the save or Saveas method or send it back to Export-Excel.
If specified, Export-Excel returns an object representing the Excel package without saving the package first.
To save, you need to call Close-ExcelPackage or send the object back to Export-Excel, or use its .Save() or SaveAs() method.
.EXAMPLE
Get-Process | Export-Excel .\Test.xlsx -show
Export all the processes to the Excel file 'Test.xlsx' and open the file immediately.
@@ -342,7 +342,7 @@
Export-Excel -Path .\test.xlsx -PivotTableDefinition $pt -Show
This example defines two pivot tables. Then it puts Service data on Sheet1 with one call to Export-Excel and Process Data on sheet2 with a second call to Export-Excel.
The thrid and final call adds the two pivot tables and opens the spreadsheet in Excel.
The third and final call adds the two pivot tables and opens the spreadsheet in Excel.
.EXAMPLE
@@ -356,7 +356,7 @@
$excel.Dispose()
Start-Process .\test.xlsx
This example uses -passthrough - put service information into sheet1 of the workbook and saves the ExcelPackageObject in $Excel.
This example uses -passthrough. It puts service information into sheet1 of the workbook and saves the ExcelPackageObject in $Excel.
It then uses the package object to apply formatting, and then saves the workbook and disposes of the object before loading the document in Excel.
.EXAMPLE
@@ -1080,10 +1080,10 @@ function Add-WorkSheet {
#An object representing an Excel Package.
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "Package", Position = 0)]
[OfficeOpenXml.ExcelPackage]$ExcelPackage,
#An Excel workbook to which the Worksheet will be added - a package contains one workbook so you can use whichever fits at the time.
#An Excel Workbook to which the Worksheet will be added - a Package contains one Workbook, so you can use whichever fits at the time.
[Parameter(Mandatory = $true, ParameterSetName = "WorkBook")]
[OfficeOpenXml.ExcelWorkbook]$ExcelWorkbook,
#The name of the worksheet 'Sheet1' by default.
#The name of the worksheet, 'Sheet1' by default.
[string]$WorksheetName ,
#If the worksheet already exists, by default it will returned, unless -ClearSheet is specified in which case it will be deleted and re-created.
[switch]$ClearSheet,
@@ -1093,13 +1093,13 @@ function Add-WorkSheet {
#If specified, the worksheet will be moved to the end of the workbook.
#(This is the default position for newly created sheets, but this can be used to move existing sheets.)
[Switch]$MoveToEnd,
#If specified, the worksheet will be moved before the nominated one (which can be a position starting from 1, or a name).
#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.
$MoveBefore ,
# If specified, the worksheet will be moved after the nominated one (which can be a position starting from 1, or a name or *).
# 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.
$MoveAfter ,
#If there is already content in the workbook the new sheet will not be active UNLESS Activate is specified
#If there is already content in the workbook the new sheet will not be active UNLESS Activate is specified.
[switch]$Activate,
#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.
[OfficeOpenXml.ExcelWorksheet]$CopySource,
@@ -1171,34 +1171,34 @@ function Add-WorkSheet {
function Select-Worksheet {
<#
.SYNOPSIS
Sets the selected tab in an Excel workbook to be the chosen sheet, and unselects all the others.
Sets the selected tab in an Excel workbook to be the chosen sheet and unselects all the others.
.DESCRIPTION
Sometimes when a sheet is added we want it to be the active sheet, sometimes we want the active sheet to be left as it was.
Select-Worksheet exists to change the which sheet is the selected tab when Excel opens the file.
.EXAMPLE
Select-Worksheet -ExcelWorkbook $ExcelWorkbook -WorksheetName "NewSheet"
$ExcelWorkbook holds the a workbook object containing a sheet named "NewSheet";
$ExcelWorkbook holds a workbook object containing a sheet named "NewSheet";
This sheet will become the [only] active sheet in the workbook
.EXAMPLE
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
This sheet will become the [only] active sheet in the workbook.
.EXAMPLE
Select-Worksheet -ExcelWorksheet $ws
$ws holds an Excel worksheet which will become the [only] active sheet in the workbook
$ws holds an Excel worksheet which will become the [only] active sheet in the workbook.
#>
param (
#An object representing an Excel Package.
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Package', Position = 0)]
[OfficeOpenXml.ExcelPackage]$ExcelPackage,
#An Excel workbook to which the Worksheet will be added - a package contains one workbook so you can use workbook or package as it suits
#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.
[Parameter(Mandatory = $true, ParameterSetName = 'WorkBook')]
[OfficeOpenXml.ExcelWorkbook]$ExcelWorkbook,
[Parameter(ParameterSetName='Package')]
[Parameter(ParameterSetName='Workbook')]
#The name of the worksheet 'Sheet1' by default.
[string]$WorksheetName,
#An object representing an Excel worksheet
#An object representing an Excel worksheet.
[Parameter(ParameterSetName='Sheet',Mandatory=$true)]
[OfficeOpenXml.ExcelWorksheet]$ExcelWorksheet
)
@@ -1218,7 +1218,7 @@ function Select-Worksheet {
Function Add-ExcelName {
<#
.SYNOPSIS
Adds a named range to an existing Excel worksheet
Adds a named-range to an existing Excel worksheet.
.DESCRIPTION
It is often helpful to be able to refer to sets of cells with a name rather than using their co-ordinates; Add-ExcelName sets up these names.
.EXAMPLE
@@ -1231,7 +1231,7 @@ Function Add-ExcelName {
#The range of cells to assign as a name.
[Parameter(Mandatory=$true)]
[OfficeOpenXml.ExcelRange]$Range,
#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
#The name to assign to the range. If the name exists it will be updated to the new range. If no name is specified, the first cell in the range will be used as the name.
[String]$RangeName
)
try {
@@ -1271,36 +1271,36 @@ function Add-ExcelTable {
.EXAMPLE
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, a totals row added and first column set in bold.
the filter is turned off, and a "Totals" row added, and first column is set in bold.
#>
[CmdletBinding()]
[OutputType([OfficeOpenXml.Table.ExcelTable])]
param (
#The range of cells to assign to a table
#The range of cells to assign to a table.
[Parameter(Mandatory=$true)]
[OfficeOpenXml.ExcelRange]$Range,
#The name for the table
#The name for the Table - this should be unqiue in the Workbook.
[Parameter(Mandatory=$true)]
[String]$TableName,
#The Style for the table, by default Medium 6
#The Style for the table, by default "Medium6" is used
[OfficeOpenXml.Table.TableStyles]$TableStyle = 'Medium6',
#By default the header row is shown - it can be turned off with -ShowHeader:$false
#By default the header row is shown - it can be turned off with -ShowHeader:$false.
[Switch]$ShowHeader ,
#By default the filter is enabled - it can be turned off with -ShowFilter:$false
#By default the filter is enabled - it can be turned off with -ShowFilter:$false.
[Switch]$ShowFilter,
#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
[Switch]$ShowTotal,
#Hashtable in the form ColumnName = "Average"|"Count"|"CountNums"|"Max"|"Min"|"None"|"StdDev"|"Sum"|"Var" - if specified ShowTotal is not needed.
#A HashTable in the form ColumnName = "Average"|"Count"|"CountNums"|"Max"|"Min"|"None"|"StdDev"|"Sum"|"Var" - if specified, -ShowTotal is not needed.
[hashtable]$TotalSettings,
#Highlights the first column in bold
#Highlights the first column in bold.
[Switch]$ShowFirstColumn,
#Highlights the last column in bold
#Highlights the last column in bold.
[Switch]$ShowLastColumn,
#By default the table formats show striped rows, the can be turned off with -ShowRowStripes:$false
[Switch]$ShowRowStripes,
#Turns on column stripes.
[Switch]$ShowColumnStripes,
#If -PassThru is specified the table object will be returned to allow additional
#If -PassThru is specified, the table object will be returned to allow additional changes to be made.
[Switch]$PassThru
)
try {

View File

@@ -1,31 +1,31 @@
function New-ConditionalText {
<#
.SYNOPSIS
Creates an object which describes a conditional formatting rule for single valued rules
Creates an object which describes a conditional formatting rule for single valued rules.
.DESCRIPTION
Some Conditional formatting rules don't apply styles to a cell (IconSets and Databars)
Some take two parameters (Between)
Some take none (ThisWeek , containsErrors, AboveAverage etc.)
The others take a single paramter (top, BottomPercent, GreaterThan, Contains etc)
This command creates an object to describe the last two categories, which can be passed to Export-Excel
Some Conditional formatting rules don't apply styles to a cell (IconSets and Databars).
Some take two parameters (Between).
Some take none (ThisWeek , containsErrors, AboveAverage etc).
The others take a single parameter (Top, BottomPercent, GreaterThan, Contains etc).
This command creates an object to describe the last two categories, which can then be passed to Export-Excel.
.PARAMETER Range
The range of cells that the conditional format applies to; if none is specified the range will be apply to all the data in the sheet
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.
.PARAMETER ConditionalType
One the supported rules by default - "ContainsText" is selected
One of the supported rules; by default "ContainsText" is selected.
.PARAMETER Text
The text (or other value) to use in the rule. Not that Equals, GreaterThan/LessThan rules require text to wrapped in double quotes
The text (or other value) to use in the rule. Not that Equals, GreaterThan/LessThan rules require text to wrapped in double quotes.
.PARAMETER ConditionalTextColor
The font color for the cell - by default: Dark red
The font color for the cell - by default: Dark red.
.PARAMETER BackgroundColor
The fill color for the cell - by default: light pink
The fill color for the cell - by default: Light pink.
.PARAMETER PatternType
The Background pattern for the cell - by deault: Solid
The Background pattern for the cell - by default: Solid
.EXAMPLE
$ct = New-ConditionalText -Text 'Ferrari'
Export-Excel -ExcelPackage $excel -ConditionalTest $ct -show
The first line creates a definition object which will highlight the word "Ferrari" in any cell.
and the secind uses Export-Excel with an open package to apply the format and save and open the file.
and the second uses Export-Excel with an open package to apply the format and save and open the file.
.EXAMPLE
$ct = New-ConditionalText -Text "Ferrari"
$ct2 = New-ConditionalText -Range $worksheet.Names["FinishPosition"].Address -ConditionalType LessThanOrEqual -Text 3 -ConditionalTextColor Red -BackgroundColor White

View File

@@ -1,10 +1,12 @@
function New-ExcelChartDefinition {
function New-ExcelChartDefinition {
<#
.SYNOPSIS
Creates a Definition of a chart which can be added using Export Excel
Creates a Definition of a chart which can be added using Export-Excel, or Add-PivotTable
.DESCRIPTION
All the parameters which are passed to Add-ExcelChart can be added to an object and
passed to Export-Excel with the -ExcelChartDefinition parameter. This command sets up those objects.
passed to Export-Excel with the -ExcelChartDefinition parameter,
or to Add-PivotTable with the -PivotChartDefinition parameter.
This command sets up those definitions.
.PARAMETER Title
The title for the chart.
.PARAMETER TitleBold
@@ -12,7 +14,7 @@ function New-ExcelChartDefinition {
.PARAMETER TitleSize
Sets the point size for the title.
.PARAMETER ChartType
One of the built in chart types, such as Pie, ClusteredColumn, Line etc. Defaults to "ColumnStacked".
One of the built-in chart types, such as Pie, ClusteredColumn, Line etc. Defaults to "ColumnStacked".
.PARAMETER XRange
The range of cells containing values for the X-Axis - usually labels.
.PARAMETER YRange
@@ -24,63 +26,63 @@ function New-ExcelChartDefinition {
.PARAMETER Row
Row position of the top left corner of the chart. 0 places at the top of the sheet, 1 below row 1 and so on.
.PARAMETER RowOffSetPixels
Offset to postion the chart by a fraction of of a row .
Offset to position the chart by a fraction of of a row.
.PARAMETER Column
Column Postion 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.
Column position of the top left corner of the chart. 0 places at the edge of the sheet 1 to the right of column A and so on.
.PARAMETER ColumnOffSetPixels
Offset to postion the chart by a fraction of of a column.
Offset to position the chart by a fraction of of a column.
.PARAMETER NoLegend
If specified, turns of display of the key. If you only have one data series it may be preferable to use the title to say what the chart is.
.PARAMETER SeriesHeader
Specify explicit name(s) for the data series, which will appear in the legend/key
Specify explicit name(s) for the data series, which will appear in the legend/key.
.PARAMETER LegendPostion
Location of the key, either left, right, top, bottom or TopRight.
.PARAMETER LegendSize
Font size for the key
Font size for the key.
.PARAMETER LegendBold
Sets the key in bold type.
.PARAMETER ShowCategory
Attaches a category label in charts which support this.
Attaches a category label in charts which support this.
.PARAMETER ShowPercent
Attaches a pecentage label in charts which support this.
Attaches a percentage label in charts which support this.
.PARAMETER XAxisTitleText
Specifies a title for the X axis.
Specifies a title for the X-axis.
.PARAMETER XAxisTitleBold
Sets the X axis title in bold face.
Sets the X-axis title in bold face.
.PARAMETER XAxisTitleSize
Sets the font size for the axis title
Sets the font size for the axis title.
.PARAMETER XAxisNumberformat
A number formatting string, like "#,##0.00" for numbers along the X axis
A number formatting string, like "#,##0.00", for numbers along the X-axis.
.PARAMETER XMajorUnit
Spacing for the major gridlines / tick marks along the X axis
Spacing for the major gridlines / tick marks along the X-axis.
.PARAMETER XMinorUnit
Spacing for the major gridlines / tick marks along the X axis
Spacing for the minor gridlines / tick marks along the X-axis.
.PARAMETER XMaxValue
Maximum value for the scale along the Xaxis
Maximum value for the scale along the X-axis.
.PARAMETER XMinValue
Minimum value for the scale along the Xaxis
Minimum value for the scale along the X-axis.
.PARAMETER xAxisPosition
Postion for the X axis (top or bottom)
Postion for the X-axis (Top or Bottom).
.PARAMETER YAxisTitleText
Specifies a title for the Y axis.
Specifies a title for the Y-axis.
.PARAMETER YAxisTitleBold
Sets the Y axis title in bold face.
Sets the Y-axis title in bold face.
.PARAMETER YAxisTitleSize
Sets the font size for the Y axis title
Sets the font size for the Y-axis title.
.PARAMETER YAxisNumberformat
A number formatting string, like "#,##0.00" for numbers on the Y axis
A number formatting string, like "#,##0.00", for numbers on the Y-axis
.PARAMETER YMajorUnit
Spacing for the major gridlines / tick marks on the Y axis
Spacing for the major gridlines / tick marks on the Y-axis.
.PARAMETER YMinorUnit
Spacing for the major gridlines / tick marks on the Y axis
Spacing for the minor gridlines / tick marks on the Y-axis.
.PARAMETER YMaxValue
Maximum value on the Yaxis
Maximum value on the Y-axis.
.PARAMETER YMinValue
Minimum value on the Yaxis
Minimum value on the Y-axis.
.PARAMETER YAxisPosition
Postion for the Y axis (left or right)
Postion for the Y-axis (Left or Right).
.PARAMETER Header
No longer used. This may be removed in future versions
No longer used. This may be removed in future versions.
.Example
>
PS> $cDef = New-ExcelChartDefinition -ChartType line -XRange "X" -YRange "Sinx" -Title "Graph of Sine X" -TitleBold -TitleSize 14 `
@@ -180,13 +182,13 @@ function New-ExcelChartDefinition {
function Add-ExcelChart {
<#
.SYNOPSIS
Creates a chart in an existing Excel worksheet
Creates a chart in an existing Excel worksheet.
.DESCRIPTION
Creates a chart. It is possible to configure the type of chart, the range of X values (labels) and Y values.
the title, the legend, the ranges for both axes, the format and postion of the axes.
the title, the legend, the ranges for both axes, the format and position of the axes.
Normally the command does not return anything, but if -passthru is specified the chart is returned so that it can be customized.
.PARAMETER Worksheet
An exisiting Sheet where the chart will be created.
An existing Sheet where the chart will be created.
.PARAMETER Title
The title for the chart.
.PARAMETER TitleBold
@@ -194,7 +196,7 @@ function Add-ExcelChart {
.PARAMETER TitleSize
Sets the point size for the title.
.PARAMETER ChartType
One of the built in chart types, such as Pie, ClusteredColumn, Line etc. Defaults to "ColumnStacked".
One of the built-in chart types, such as Pie, ClusteredColumn, Line etc. Defaults to "ColumnStacked".
.PARAMETER XRange
The range of cells containing values for the X-Axis - usually labels.
.PARAMETER YRange
@@ -208,63 +210,63 @@ function Add-ExcelChart {
.PARAMETER Row
Row position of the top left corner of the chart. 0 places at the top of the sheet, 1 below row 1 and so on.
.PARAMETER RowOffSetPixels
Offset to postion the chart by a fraction of of a row .
Offset to position the chart by a fraction of a row.
.PARAMETER Column
Column Postion 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.
Column position of the top left corner of the chart. 0 places at the edge of the sheet 1 to the right of column A and so on.
.PARAMETER ColumnOffSetPixels
Offset to postion the chart by a fraction of of a column.
Offset to position the chart by a fraction of a column.
.PARAMETER NoLegend
If specified, turns of display of the key. If you only have one data series it may be preferable to use the title to say what the chart is.
.PARAMETER SeriesHeader
Specify explicit name(s) for the data series, which will appear in the legend/key
.PARAMETER SeriesHeade
Specify explicit name(s) for the data series, which will appear in the legend/key.
.PARAMETER LegendPostion
Location of the key, either left, right, top, bottom or TopRight.
Location of the key, either Left, Right, Top, Bottom or TopRight.
.PARAMETER LegendSize
Font size for the key
Font size for the key.
.PARAMETER LegendBold
Sets the key in bold type.
.PARAMETER ShowCategory
Attaches a category label in charts which support this.
.PARAMETER ShowCategory
Attaches a category label in charts which support this.
.PARAMETER ShowPercent
Attaches a pecentage label in charts which support this.
Attaches a percentage label in charts which support this.
.PARAMETER XAxisTitleText
Specifies a title for the X axis.
Specifies a title for the X-axis.
.PARAMETER XAxisTitleBold
Sets the X axis title in bold face.
Sets the X-axis title in bold face.
.PARAMETER XAxisTitleSize
Sets the font size for the axis title
Sets the font size for the axis title.
.PARAMETER XAxisNumberformat
A number formatting string, like "#,##0.00" for numbers along the X axis
A number formatting string, like "#,##0.00", for numbers along the X-axis.
.PARAMETER XMajorUnit
Spacing for the major gridlines / tick marks along the X axis
Spacing for the major gridlines / tick marks along the X-axis.
.PARAMETER XMinorUnit
Spacing for the major gridlines / tick marks along the X axis
Spacing for the minor gridlines / tick marks along the X-axis.
.PARAMETER XMaxValue
Maximum value for the scale along the Xaxis
Maximum value for the scale along the X-axis.
.PARAMETER XMinValue
Minimum value for the scale along the Xaxis
Minimum value for the scale along the X-axis.
.PARAMETER xAxisPosition
Postion for the X axis (top or bottom)
Position for the X-axis (Top or Bottom).
.PARAMETER YAxisTitleText
Specifies a title for the Y axis.
Specifies a title for the Y-axis.
.PARAMETER YAxisTitleBold
Sets the Y axis title in bold face.
Sets the Y-axis title in bold face.
.PARAMETER YAxisTitleSize
Sets the font size for the Y axis title
Sets the font size for the Y-axis title
.PARAMETER YAxisNumberformat
A number formatting string, like "#,##0.00" for numbers on the Y axis
A number formatting string, like "#,##0.00", for numbers on the Y-axis.
.PARAMETER YMajorUnit
Spacing for the major gridlines / tick marks on the Y axis
Spacing for the major gridlines / tick marks on the Y-axis.
.PARAMETER YMinorUnit
Spacing for the major gridlines / tick marks on the Y axis
Spacing for the minor gridlines / tick marks on the Y-axis.
.PARAMETER YMaxValue
Maximum value on the Yaxis
Maximum value on the Y-axis.
.PARAMETER YMinValue
Minimum value on the Yaxis
Minimum value on the Y-axis.
.PARAMETER YAxisPosition
Postion for the Y axis (left or right)
Position for the Y-axis (Left or Right).
.PARAMETER PassThru
Add-Excel chart doesn't normally return anything, but if -PassThru is specified it returns the newly created chart to allow it to be fine tuned
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.
.EXAMPLE
>
PS> $Excel = ConvertFrom-Csv @"
@@ -280,8 +282,8 @@ function Add-ExcelChart {
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 explitly specified. Note the at 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 table.
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
>
@@ -310,13 +312,17 @@ function Add-ExcelChart {
-SeriesHeader "Sin(x)" -LegendSize 8 -legendBold -LegendPostion 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 ranges for the two columns - "X" and "SinX" respectively
The Add-Excel chart colum adds a chart to that work sheet, specifying a line chart with the X values comming from named range "X" and the the Y values comming the range named "SinX".
The chart has a title, and is positioned to the right of column 2 and sized 8000 pixels wide
Thed X axis s labeled "Degrees", in bold 12 point type and runs from 0 to 361 with labels every 30, and minor tick marks every 10. Degres are shown badded to 3 didits.
The Y axis is labeled "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 show 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)"
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)".
#>
[cmdletbinding(DefaultParameterSetName='Worksheet')]
[OutputType([OfficeOpenXml.Drawing.Chart.ExcelChart])]
@@ -404,7 +410,7 @@ function Add-ExcelChart {
if ($XAxisTitleBold) {$chart.XAxis.Title.Font.Bold = $true}
if ($XAxisTitleSize) {$chart.XAxis.Title.Font.Size = $XAxisTitleSize}
}
if ($XAxisPosition) {Write-Warning "X Axis position is not being set propertly at the moment, parameter ignored" }
if ($XAxisPosition) {Write-Warning "X-axis position is not being set propertly at the moment, parameter ignored" }
#$chart.ChartXml.chartSpace.chart.plotArea.catAx.axPos.val = $XAxisPosition.ToString().substring(0,1)}
if ($XMajorUnit) {$chart.XAxis.MajorUnit = $XMajorUnit}
if ($XMinorUnit) {$chart.XAxis.MinorUnit = $XMinorUnit}
@@ -417,7 +423,7 @@ function Add-ExcelChart {
if ($YAxisTitleBold) {$chart.YAxis.Title.Font.Bold = $true}
if ($YAxisTitleSize) {$chart.YAxis.Title.Font.Size = $YAxisTitleSize}
}
if ($YAxisPosition) {Write-Warning "Y Axis position is not being set propertly at the moment, parameter ignored" }
if ($YAxisPosition) {Write-Warning "Y-axis position is not being set propertly at the moment, parameter ignored" }
#$chart.ChartXml.chartSpace.chart.plotArea.valAx.axPos.val= $YAxisPosition.ToString().substring(0,1)}
if ($YMajorUnit) {$chart.YAxis.MajorUnit = $YMajorUnit}
if ($YMinorUnit) {$chart.YAxis.MinorUnit = $YMinorUnit}

View File

@@ -73,9 +73,10 @@ Function Close-ExcelPackage {
.Synopsis
Closes an Excel Package, saving, saving under a new name or abandoning changes and opening the file in Excel as required.
.Description
When working with an Excel packaage object the workbook is held in memory and not saved until the Save() method of the package is called.
Close package saves and disposes of the package object. It can be called with -NoSave to abandon the file without saving, with a new "SaveAs" filename
with a password to protect the file. And with Show to open it in Excel. -Calculate will try to update the workbook, although not everything can be recalculated
When working with an ExcelPackage object, the Workbook is held in memory and not saved until the .Save() method of the package is called.
Close-ExcelPackage saves and disposes of the Package object. It can be called with -NoSave to abandon the file without saving, with a new "SaveAs" filename,
and/or with a password to protect the file. And -Show will open the file in Excel;
-Calculate will try to update the workbook, although not everything can be recalculated
.Example
Close-ExcelPackage -show $excel
$excel holds a package object, this saves the workbook and loads it into Excel.

View File

@@ -1,9 +1,9 @@
function Add-PivotTable {
<#
.Synopsis
Adds a Pivot table (and optional pivot chart) to a workbook
Adds a PivotTable (and optional PivotChart) to a workbook.
.Description
If the pivot table already exists, the source data will be updated.
If the PivotTable already exists, the source data will be updated.
.Example
>
PS> $excel = Get-Service | Export-Excel -Path test.xlsx -WorksheetName Services -PassThru -AutoSize -DisplayPropertySet -TableName ServiceTable -Title "Services on $Env:COMPUTERNAME"
@@ -34,66 +34,66 @@
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 sheeet in the workbook,
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 (product) and the the data is explicitly formatted as a currency.
Not that in thee the chart definition the number format for the axis does not include any fraction part
grand totals for both gross and net are included for rows (Cities) and columns (product) and the data is explicitly formatted as a currency.
Not that in the chart definition the number format for the axis does not include any fraction part.
#>
[cmdletbinding(defaultParameterSetName='ChartbyParams')]
[OutputType([OfficeOpenXml.Table.PivotTable.ExcelPivotTable])]
param (
#Name for the new Pivot table - this will be the name of a sheet in the workbook
#Name for the new PivotTable - this will be the name of a sheet in the Workbook.
[Parameter(Mandatory = $true)]
[string]$PivotTableName,
#By default a pivot table 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.)
#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.)
[OfficeOpenXml.ExcelAddressBase]
$Address,
#An excel package object for the workbook.
$ExcelPackage,
#Worksheet where the data is found
#Worksheet where the data is found.
$SourceWorkSheet,
#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.
$SourceRange,
#Fields to set as rows in the Pivot table
#Fields to set as rows in the PivotTable.
$PivotRows,
#A hash table in form "FieldName"="Function", where function is one of
#Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP
#Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP.
$PivotData,
#Fields to set as columns in the Pivot table
#Fields to set as columns in the PivotTable.
$PivotColumns,
#Fields to use to filter in the Pivot table
#Fields to use to filter in the PivotTable.
$PivotFilter,
#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.
#If there are multiple data items in a PivotTable, by default they are shown on separate rows; this switch makes them separate columns.
[Switch]$PivotDataToColumn,
#Define whther totals should be added to rows, columns neither, or both (the default is both)
#Define whether totals should be added to rows, columns neither, or both (the default is both).
[ValidateSet("Both","Columns","Rows","None")]
[String]$PivotTotals = "Both",
#Included for compatibility - equivalent to -PivotTotals "None"
#Included for compatibility - equivalent to -PivotTotals "None".
[Switch]$NoTotalsInPivot,
#Number format to apply to the data cells in the Pivot table
#Number format to apply to the data cells in the PivotTable.
[string]$PivotNumberFormat,
#Apply a table style to the PivotTable
#Apply a table style to the PivotTable.
[OfficeOpenXml.Table.TableStyles]$PivotTableSyle,
#Use a chart definition instead of specifying chart settings one by one
#Use a chart definition instead of specifying chart settings one by one.
[Parameter(ParameterSetName='ChartbyDef', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
$PivotChartDefinition,
#If specified a chart Will be included.
#If specified, a chart will be included.
[Parameter(ParameterSetName='ChartbyParams')]
[Switch]$IncludePivotChart,
#Optional title for the pivot chart, by default the title omitted.
[Parameter(ParameterSetName='ChartbyParams')]
[String]$ChartTitle = "",
#Height of the chart in Pixels (400 by default)
#Height of the chart in Pixels (400 by default).
[Parameter(ParameterSetName='ChartbyParams')]
[int]$ChartHeight = 400 ,
#Width of the chart in Pixels (600 by default)
#Width of the chart in Pixels (600 by default).
[Parameter(ParameterSetName='ChartbyParams')]
[int]$ChartWidth = 600,
#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).
[Parameter(ParameterSetName='ChartbyParams')]
[Int]$ChartRow = 0 ,
#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)
#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).
[Parameter(ParameterSetName='ChartbyParams')]
[Int]$ChartColumn = 4,
#Vertical offset of the chart from the cell corner.
@@ -102,25 +102,25 @@
[Parameter(ParameterSetName='ChartbyParams')]
#Horizontal offset of the chart from the cell corner.
[Int]$ChartColumnOffSetPixels = 0,
#Type of chart
#Type of chart; defaults to "Pie".
[Parameter(ParameterSetName='ChartbyParams')]
[OfficeOpenXml.Drawing.Chart.eChartType]$ChartType = 'Pie',
#If specified hides the chart legend
#If specified hides the chart legend.
[Parameter(ParameterSetName='ChartbyParams')]
[Switch]$NoLegend,
#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.
#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.
[Parameter(ParameterSetName='ChartbyParams')]
[Switch]$ShowCategory,
#If specified attaches percentages to slices in a pie chart.
[Parameter(ParameterSetName='ChartbyParams')]
[Switch]$ShowPercent,
#If there is already content in the workbook the sheet with the Pivot table will not be active UNLESS Activate is specified
#If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified.
[switch]$Activate,
#Return the pivot table so it can be customized
#Return the PivotTable so it can be customized.
[Switch]$PassThru
)
if ($PivotTableName.length -gt 250) {
Write-warning -Message "Pivot table name will be truncated"
Write-warning -Message "PivotTable name will be truncated"
$PivotTableName = $PivotTableName.Substring(0,250)
}
if ($Address) {
@@ -130,13 +130,13 @@
try {
if (-not $ExcelPackage) {Write-Warning -message "This combination of Parameters needs to include the ExcelPackage." ; return }
[OfficeOpenXml.ExcelWorksheet]$wsPivot = Add-WorkSheet -ExcelPackage $ExcelPackage -WorksheetName $pivotTableName -Activate:$Activate
if ($wsPivot.Name -ne $PivotTableName) {Write-Warning -Message "The Worksheet name for the pivot table does not match the table name '$PivotTableName'; probably because excess or illegal characters were removed." }
if ($wsPivot.Name -ne $PivotTableName) {Write-Warning -Message "The Worksheet name for the PivotTable does not match the table name '$PivotTableName'; probably because excess or illegal characters were removed." }
if ($PivotFilter) {$Address = $wsPivot.Cells["A3"]} else { $Address = $wsPivot.Cells["A1"]}
}
catch {throw "Could not create the sheet for the Pivot table. $_" }
catch {throw "Could not create the sheet for the PivotTable. $_" }
}
#if the pivot doesn't exist, create it.
if (-not $wsPivot) {throw "There was a problem getting the worksheet for the pivot table"}
if (-not $wsPivot) {throw "There was a problem getting the worksheet for the PivotTable"}
if (-not $wsPivot.PivotTables[$pivotTableName] ) {
try {
#Accept a string or a worksheet object as $SourceWorksheet - we don't need a worksheet if we have a Rangebase .
@@ -160,7 +160,7 @@
elseif ( $SourceRange -is [String] -or $SourceRange -is [OfficeOpenXml.ExcelAddress]) {
$pivotTable = $wsPivot.PivotTables.Add($Address,$SourceWorkSheet.Cells[$SourceRange], $pivotTableName)
}
else {Write-warning "Could not create a pivot table with the Source Range provided."; return}
else {Write-warning "Could not create a PivotTable with the Source Range provided."; return}
foreach ($Row in $PivotRows) {
try {$null = $pivotTable.RowFields.Add($pivotTable.Fields[$Row]) }
catch {Write-Warning -message "Could not add '$row' to Rows in PivotTable $pivotTableName." }
@@ -203,7 +203,7 @@
catch {Write-Warning -Message "Failed adding PivotTable '$pivotTableName': $_"}
}
else {
Write-Warning -Message "Pivot table defined in $($pivotTableName) already exists, only the data range will be changed."
Write-Warning -Message "PivotTable defined in $($pivotTableName) already exists, only the data range will be changed."
$pivotTable = $wsPivot.PivotTables[$pivotTableName]
if (-not $SourceRange) { $SourceRange = $SourceWorkSheet.Dimension.Address}
$pivotTable.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref = $SourceRange
@@ -230,11 +230,11 @@
function New-PivotTableDefinition {
<#
.Synopsis
Creates Pivot table definitons for Export-Excel
Creates PivotTable definitons for Export-Excel
.Description
Export-Excel allows a single Pivot table to be defined using the parameters -IncludePivotTable, -PivotColumns -PivotRows,
=PivotData, -PivotFilter, -PivotTotals, -PivotDataToColumn, -IncludePivotChart and -ChartType.
Its -PivotTableDefintion paramater allows multiple pivot tables to be defined, with additional parameters.
Export-Excel allows a single PivotTable to be defined using the parameters -IncludePivotTable, -PivotColumns -PivotRows,
-PivotData, -PivotFilter, -PivotTotals, -PivotDataToColumn, -IncludePivotChart and -ChartType.
Its -PivotTableDefintion paramater allows multiple PivotTables to be defined, with additional parameters.
New-PivotTableDefinition is a convenient way to build these definitions.
.Example
>
@@ -254,24 +254,24 @@ function New-PivotTableDefinition {
$SourceWorkSheet,
#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/
$SourceRange,
#Fields to set as rows in the Pivot table
#Fields to set as rows in the PivotTable
$PivotRows,
#A hash table in form "FieldName"="Function", where function is one of
#Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP
[hashtable]$PivotData,
#Fields to set as columns in the Pivot table
#Fields to set as columns in the PivotTable
$PivotColumns,
#Fields to use to filter in the Pivot table
#Fields to use to filter in the PivotTable
$PivotFilter,
#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.
[Switch]$PivotDataToColumn,
#By default Pivot tables have Totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected.
#By default PivotTables have Totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected.
#Define whther totals should be added to rows, columns neither, or both (the default is both)
[ValidateSet("Both","Columns","Rows","None")]
[String]$PivotTotals = "Both",
#Included for compatibility - equivalent to -PivotTotals "None"
[Switch]$NoTotalsInPivot,
#Number format to apply to the data cells in the Pivot table
#Number format to apply to the data cells in the PivotTable
[string]$PivotNumberFormat,
#Apply a table style to the PivotTable
[OfficeOpenXml.Table.TableStyles]$PivotTableSyle,
@@ -314,7 +314,7 @@ function New-PivotTableDefinition {
#If specified attaches percentages to slices in a pie chart.
[Parameter(ParameterSetName='ChartbyParams')]
[Switch]$ShowPercent,
#If there is already content in the workbook the sheet with the Pivot table will not be active UNLESS Activate is specified
#If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified
[switch]$Activate
)
$validDataFuntions = [system.enum]::GetNames([OfficeOpenXml.Table.PivotTable.DataFieldFunctions])

View File

@@ -5,26 +5,26 @@
.DESCRIPTION
Set-ExcelColumn can take a value which is either a string containing a value or formula or a scriptblock
which evaluates to a string, and optionally a column number and fills that value down the column.
A column heading can be specified and the column can be made a named range.
A column heading can be specified, and the column can be made a named range.
The column can be formatted in the same operation.
.EXAMPLE
Set-ExcelColumn -Worksheet $ws -Column 5 -NumberFormat 'Currency'
$ws contains a worksheet object - and column E is set to use the local currecy format.
$ws contains a worksheet object - and column E is set to use the local currency format.
Intelisense will complete predefined number formats. You can see how currency is interpreted on the local computer with the command
Expand-NumberFormat currency
.EXAMPLE
Set-ExcelColumn -Worksheet $ws -Heading "WinsToFastLaps" -Value {"=E$row/C$row"} -Column 7 -AutoSize -AutoNameRange
Here, $WS already contains a worksheet which contains counts of races won and fastest laps recorded by racing drivers (in columns C and E)
Here, $WS already contains a worksheet which contains counts of races won and fastest laps recorded by racing drivers (in columns C and E).
Set-ExcelColumn specifies that Column 7 should have a heading of "WinsToFastLaps" and the data cells should contain =E2/C2 , =E3/C3 etc
the new data cells should become a named range, which will also be named "WinsToFastLaps" the column width will be set automatically
.EXAMPLE
the new data cells should become a named range, which will also be named "WinsToFastLaps" the column width will be set automatically.
.EXAMPLE.
Set-ExcelColumn -Worksheet $ws -Heading "Link" -Value {"https://en.wikipedia.org" + $worksheet.cells["B$Row"].value } -AutoSize
In this example, the worksheet in $ws has partial links to wikipedia pages in column B.
The -Value parameter is is a script block and it outputs a string which begins https... and ends with the value of cell at column
B in the current row. When given a valid URI, Set-ExcelColumn makes it a hyperlink. The column will be autosized to fit the links.
The -Value parameter is is a script block and it outputs a string which begins https... and ends with the value of cell at
column B in the current row. When given a valid URI, Set-ExcelColumn makes it a hyperlink. The column will be autosized to fit the links.
.EXAMPLE
4..6 | Set-ExcelColumn -Worksheet $ws -AutoNameRange
@@ -35,78 +35,77 @@
[Alias("Set-Column")]
[OutputType([OfficeOpenXml.ExcelColumn],[String])]
Param (
#If specifing the worksheet by name the ExcelPackage object which contains it needs to be passed
#If specifying the worksheet by name, the ExcelPackage object which contains the Sheet also needs to be passed.
[Parameter(ParameterSetName="Package",Mandatory=$true)]
[OfficeOpenXml.ExcelPackage]$ExcelPackage,
#The sheet to update can be a given as a name or an Excel Worksheet object - this sets it by name
#The sheet to update can be a given as a name or an Excel Worksheet object - this sets it by name.
[Parameter(ParameterSetName="Package")]
#The sheet to update can be a given as a name or an Excel Worksheet object - $workSheet contains the object
[String]$Worksheetname = "Sheet1",
#The worksheet object can be passed instead of passing a sheet name and a package.
#This passes the worksheet object instead of passing a sheet name and a package.
[Parameter(ParameterSetName="sheet",Mandatory=$true)]
[OfficeOpenXml.ExcelWorksheet]$Worksheet,
#Column to fill down - first column is 1. 0 will be interpreted as first unused column
#Column to fill down - the first column is 1. 0 will be interpreted as first empty column.
[Parameter(ValueFromPipeline=$true)]
[ValidateRange(0,16384)]
$Column = 0 ,
#First row to fill data in
#First row to fill data in.
[ValidateRange(1,1048576)]
[Int]$StartRow ,
#value, formula or script block to fill in. Script block can use $row, $column [number], $columnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn
#A value, formula or scriptblock to fill in. A script block can use $worksheet, $row, $column [number], $columnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn.
$Value ,
#Optional column heading
#Optional column heading.
$Heading ,
#Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc
#Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc.
[Alias("NFormat")]
$NumberFormat,
#Style of border to draw around the row
#Style of border to draw around the row.
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderAround,
#Colour for the text - if none specified it will be left as it it is
#Colour for the text - if none specified it will be left as it it is.
[System.Drawing.Color]$FontColor,
#Make text bold; use -Bold:$false to remove bold
#Make text bold; use -Bold:$false to remove bold.
[Switch]$Bold,
#Make text italic; use -Italic:$false to remove italic
#Make text italic; use -Italic:$false to remove italic.
[Switch]$Italic,
#Underline the text using the underline style in -underline type; use -Underline:$false to remove underlining
#Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining.
[Switch]$Underline,
#Should Underline use single or double, normal or accounting mode : default is single normal
#Should Underline use single or double, normal or accounting mode ? the default is single normal.
[OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single,
#Strike through text; use -Strikethru:$false to remove Strike through
#Strike through text; use -Strikethru:$false to remove Strike through.
[Switch]$StrikeThru,
#Subscript or superscript (or none)
#Subscript or Superscript (or None).
[OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift,
#Font to use - Excel defaults to Calibri
#Font to use - Excel defaults to Calibri.
[String]$FontName,
#Point size for the text
#Point size for the text.
[float]$FontSize,
#Change background colour
#Change background color.
[System.Drawing.Color]$BackgroundColor,
#Background pattern - solid by default
#Background pattern - Solid by default.
[OfficeOpenXml.Style.ExcelFillStyle]$BackgroundPattern = [OfficeOpenXml.Style.ExcelFillStyle]::Solid ,
#Secondary colour for background pattern
#Secondary color for background pattern.
[Alias("PatternColour")]
[System.Drawing.Color]$PatternColor,
#Turn on text wrapping; use -WrapText:$false to turn off word wrapping
#Turn on text wrapping; use -WrapText:$false to turn off word wrapping.
[Switch]$WrapText,
#Position cell contents to left, right, center etc. default is 'General'
#Position cell contents to Left, Right, Center etc. Default is 'General'.
[OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment,
#Position cell contents to top bottom or centre
#Position cell contents to Top, Bottom or Center.
[OfficeOpenXml.Style.ExcelVerticalAlignment]$VerticalAlignment,
#Degrees to rotate text. Up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise.
[ValidateRange(-90, 90)]
[int]$TextRotation ,
#Autofit cells to width
#Autofit cells to width.
[Alias("AutoFit")]
[Switch]$AutoSize,
#Set cells to a fixed width, ignored if Autosize is specified
#Set cells to a fixed width, ignored if -Autosize is specified.
[float]$Width,
#Set the inserted data to be a named range (ignored if header is not specified)
#Set the inserted data to be a named range.
[Switch]$AutoNameRange,
#Hide the column
#Hide the column.
[Switch]$Hide,
#If Sepecified returns the range of cells which were affected
[Switch]$ReturnRange,
#If Specified, return an ExcelPackage object to allow further work to be done on the file.
#If Sepecified, returns the range of cells which were affected.
[Switch]$Specified,
#If Specified, return the Column to allow further work to be done on it.
[Switch]$PassThru
)
@@ -176,7 +175,7 @@
#endregion
if ($PSBoundParameters.ContainsKey('Hide')) {$workSheet.Column($Column).Hidden = [bool]$Hide}
#return the new data if -passthru was specified.
if ($passThru) { $Worksheet.Column($Column)}
if ($PassThru) { $Worksheet.Column($Column)}
elseif ($ReturnRange) { $theRange}
}
}

View File

@@ -1,11 +1,11 @@
Function Set-ExcelRow {
<#
.Synopsis
Fills values into a [new] row in an Excel spreadsheet. And sets row formmats.
Fills values into a [new] row in an Excel spreadsheet. And sets row formats.
.Description
Set-ExcelRow accepts either a Worksheet object or an Excel package object returned by Export-Excel and the name of a sheet,
Set-ExcelRow accepts either a Worksheet object or an Excel Package object returned by Export-Excel and the name of a sheet,
and inserts the chosen contents into a row of the sheet.
The contents can be a constant e.g. "42" , a formula or a script block which is converted into a constant or formula.
The contents can be a constant e.g. "42", a formula or a script block which is converted into a constant or a formula.
The first cell of the row can optionally be given a heading.
.Example
Set-ExcelRow -Worksheet $ws -Heading Total -Value {"=sum($columnName`2:$columnName$endrow)" }
@@ -26,84 +26,84 @@
[Alias("Set-Row")]
[OutputType([OfficeOpenXml.ExcelRow],[String])]
Param (
#An Excel package object - e.g. from Export-Excel -passthru - requires a sheet name
#An Excel package object - e.g. from Export-Excel -passthru - requires a sheet name.
[Parameter(ParameterSetName="Package",Mandatory=$true)]
[OfficeOpenXml.ExcelPackage]$ExcelPackage,
#the name to update in the package
#The name of the sheet to update in the package.
[Parameter(ParameterSetName="Package")]
$Worksheetname = "Sheet1",
#A worksheet object
#A worksheet object instead of passing a name and package.
[Parameter(ParameterSetName="Sheet",Mandatory=$true)]
[OfficeOpenXml.Excelworksheet] $Worksheet,
#Row to fill right - first row is 1. 0 will be interpreted as first unused row
#Row to fill right - first row is 1. 0 will be interpreted as first unused row.
[Parameter(ValueFromPipeline = $true)]
$Row = 0 ,
#Position in the row to start from
#Position in the row to start from.
[int]$StartColumn,
#Value, formula or script block to fill in. Script block can use $worksheet, $row, $Column [number], $ColumnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn
$Value,
#Optional Row heading
#Optional Row heading.
$Heading ,
#Set the heading in bold type
#Set the heading in bold type.
[Switch]$HeadingBold,
#Change the size of the heading type
#Change the size of the heading type.
[Int]$HeadingSize ,
#Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc
#Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc.
[Alias("NFormat")]
$NumberFormat,
#Style of border to draw around the row
#Style of border to draw around the row.
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderAround,
#Color of the border
[System.Drawing.Color]$BorderColor=[System.Drawing.Color]::Black,
#Style for the bottom border
#Style for the bottom border.
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderBottom,
#Style for the top border
#Style for the top border.
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderTop,
#Style for the left border
#Style for the left border.
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderLeft,
#Style for the right border
#Style for the right border.
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderRight,
#Colour for the text - if none specified it will be left as it it is
#Colour for the text - if none specified it will be left as it it is.
[System.Drawing.Color]$FontColor,
#Make text bold; use -Bold:$false to remove bold
#Make text bold; use -Bold:$false to remove bold.
[Switch]$Bold,
#Make text italic; use -Italic:$false to remove italic
#Make text italic; use -Italic:$false to remove italic.
[Switch]$Italic,
#Underline the text using the underline style in -underline type; use -Underline:$false to remove underlining
#Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining.
[Switch]$Underline,
#Should Underline use single or double, normal or accounting mode : default is single normal
#Should Underline use single or double, normal or accounting mode : default is single normal.
[OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single,
#Strike through text; use -Strikethru:$false to remove Strike through
#Strike through text; use -Strikethru:$false to remove Strike through.
[Switch]$StrikeThru,
#Subscript or superscript (or none)
#Subscript or Superscript (or none).
[OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift,
#Font to use - Excel defaults to Calibri
#Font to use - Excel defaults to Calibri.
[String]$FontName,
#Point size for the text
#Point size for the text.
[float]$FontSize,
#Change background colour
#Change background color.
[System.Drawing.Color]$BackgroundColor,
#Background pattern - solid by default
#Background pattern - solid by default.
[OfficeOpenXml.Style.ExcelFillStyle]$BackgroundPattern = [OfficeOpenXml.Style.ExcelFillStyle]::Solid ,
#Secondary colour for background pattern
#Secondary color for background pattern.
[Alias("PatternColour")]
[System.Drawing.Color]$PatternColor,
#Turn on text wrapping; use -WrapText:$false to turn off word wrapping
#Turn on text wrapping; use -WrapText:$false to turn off word wrapping.
[Switch]$WrapText,
#Position cell contents to left, right, center etc. default is 'General'
#Position cell contents to Left, Right, Center etc. default is 'General'.
[OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment,
#Position cell contents to top bottom or centre
#Position cell contents to Top Bottom or Center.
[OfficeOpenXml.Style.ExcelVerticalAlignment]$VerticalAlignment,
#Degrees to rotate text. Up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise
#Degrees to rotate text. Up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise.
[ValidateRange(-90, 90)]
[int]$TextRotation ,
#Set cells to a fixed hieght
#Set cells to a fixed hieght.
[float]$Height,
#Hide the Row
#Hide the Row.
[Switch]$Hide,
#If Sepecified returns the range of cells which were affected
#If Sepecified returns the range of cells which were affected.
[Switch]$ReturnRange,
#If Specified, return a row object to allow further work to be done
#If Specified, return a row object to allow further work to be done.
[Switch]$PassThru
)
begin {

View File

@@ -1,22 +1,23 @@
Function Set-ExcelRange {
<#
.SYNOPSIS
Applies Number, font, alignment and colour formatting, values or formulas to a range of Excel Cells
Applies Number, font, alignment and color formatting, values or formulas to a range of Excel Cells.
.DESCRIPTION
Set-ExcelRange was created to set the style elements for a range of cells, this includes autosizing and hiding, setting
font elements (Name, Size, Bold, Italic, Underline & UnderlineStyle and Subscript & SuperScript), font and background colors,
borders, text wrapping, rotation, aliginment within cells, and number format. It was orignally named "Set-ExcelRange"
It has been extended to set Values, Formulas and set ArrayFormulas (sometimes called Ctrl-shift-Enter [CSE] formulas); because of this
the name has become Set-ExcelRange - but the old name of Set-Format is preserved as an alias name may swapped.
Set-ExcelRange was created to set the style elements for a range of cells, this includes
auto-sizing and hiding, setting font elements (Name, Size, Bold, Italic, Underline & UnderlineStyle and Subscript & SuperScript),
font and background colors, borders, text wrapping, rotation, aliginment within cells, and number format.
It was orignally named "Set-Format",but it has been extended to set Values, Formulas and
ArrayFormulas (sometimes called Ctrl-shift-Enter [CSE] formulas); because of this
The name has become Set-ExcelRange - but the old name of Set-Format is preserved as an alias name.
.EXAMPLE
$sheet.Column(3) | Set-ExcelRange -HorizontalAlignment Right -NumberFormat "#,###" -AutoFit
Selects column 3 from a sheet object (within a workbook object, which is a child of the ExcelPackage object) and passes it to Set-ExcelRange
which formats as an integer with comma seperated groups, aligns it right, and auto-fits the column to the contents.
which formats as an integer with comma-separated groups, aligns it right, and auto-fits the column to the contents.
.EXAMPLE
Set-ExcelRange -Range $sheet.Cells["E1:H1048576"] -HorizontalAlignment Right -NumberFormat "#,###"
Instead of piping the address in this version specifies a block of cells and applies similar formatting
Instead of piping the address, this version specifies a block of cells and applies similar formatting.
.EXAMPLE
Set-ExcelRange $excel.Workbook.Worksheets[1].Tables["Processes"] -Italic
@@ -25,77 +26,77 @@
[cmdletbinding()]
[Alias("Set-Format")]
Param (
#One or more row(s), Column(s) and/or block(s) of cells to format
#One or more row(s), Column(s) and/or block(s) of cells to format.
[Parameter(ValueFromPipeline = $true,Position=0)]
[Alias("Address")]
$Range ,
#The worksheet where the format is to be applied
#The worksheet where the format is to be applied.
[OfficeOpenXml.ExcelWorksheet]$WorkSheet ,
#Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc
#Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc.
[Alias("NFormat")]
$NumberFormat,
#Style of border to draw around the range
#Style of border to draw around the range.
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderAround,
#Color of the border
#Color of the border.
[System.Drawing.Color]$BorderColor=[System.Drawing.Color]::Black,
#Style for the bottom border
#Style for the bottom border.
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderBottom,
#Style for the top border
#Style for the top border.
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderTop,
#Style for the left border
#Style for the left border.
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderLeft,
#Style for the right border
#Style for the right border.
[OfficeOpenXml.Style.ExcelBorderStyle]$BorderRight,
#Colour for the text - if none specified it will be left as it it is
#Colour for the text - if none is specified it will be left as it is.
[System.Drawing.Color]$FontColor,
#Value for the cell
#Value for the cell.
$Value,
#Formula for the cell
#Formula for the cell.
$Formula,
#Specifies formula should be an array formula (a.k.a CSE [ctrl-shift-enter] formula )
#Specifies formula should be an array formula (a.k.a CSE [ctrl-shift-enter] formula).
[Switch]$ArrayFormula,
#Clear Bold, Italic, StrikeThrough and Underline and set colour to black
#Clear Bold, Italic, StrikeThrough and Underline and set colour to black.
[Switch]$ResetFont,
#Make text bold; use -Bold:$false to remove bold
#Make text bold; use -Bold:$false to remove bold.
[Switch]$Bold,
#Make text italic; use -Italic:$false to remove italic
#Make text italic; use -Italic:$false to remove italic.
[Switch]$Italic,
#Underline the text using the underline style in -underline type; use -Underline:$false to remove underlining
#Underline the text using the underline style in -underline type; use -Underline:$false to remove underlining.
[Switch]$Underline,
#Should Underline use single or double, normal or accounting mode : default is single normal
#Should Underline use single or double, normal or accounting mode: the default is single normal.
[OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single,
#Strike through text; use -Strikethru:$false to remove Strike through
[Switch]$StrikeThru,
#Subscript or superscript (or none)
#Subscript or Superscript (or none).
[OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift,
#Font to use - Excel defaults to Calibri
#Font to use - Excel defaults to Calibri.
[String]$FontName,
#Point size for the text
#Point size for the text.
[float]$FontSize,
#Change background colour
#Change background color.
[System.Drawing.Color]$BackgroundColor,
#Background pattern - solid by default
#Background pattern - Solid by default.
[OfficeOpenXml.Style.ExcelFillStyle]$BackgroundPattern = [OfficeOpenXml.Style.ExcelFillStyle]::Solid ,
#Secondary colour for background pattern
#Secondary color for background pattern.
[Alias("PatternColour")]
[System.Drawing.Color]$PatternColor,
#Turn on text wrapping; use -WrapText:$false to turn off word wrapping
#Turn on text wrapping; use -WrapText:$false to turn off word wrapping.
[Switch]$WrapText,
#Position cell contents to left, right, center etc. default is 'General'
#Position cell contents to Left, Right, Center etc. default is 'General'.
[OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment,
#Position cell contents to top bottom or center
#Position cell contents to Top Bottom or Center.
[OfficeOpenXml.Style.ExcelVerticalAlignment]$VerticalAlignment,
#Degrees to rotate text. Up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise.
[ValidateRange(-90, 90)]
[int]$TextRotation ,
#Autofit cells to width (columns or ranges only)
#Autofit cells to width (columns or ranges only).
[Alias("AutoFit")]
[Switch]$AutoSize,
#Set cells to a fixed width (columns or ranges only), ignored if Autosize is specified
#Set cells to a fixed width (columns or ranges only), ignored if Autosize is specified.
[float]$Width,
#Set cells to a fixed hieght (rows or ranges only)
#Set cells to a fixed hieght (rows or ranges only).
[float]$Height,
#Hide a row or column (not a range); use -Hidden:$false to unhide
#Hide a row or column (not a range); use -Hidden:$false to unhide.
[Switch]$Hidden
)
process {