From 6d97018de672f2f4f4b3b1c47dbf2262f2d35ea2 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sun, 17 Nov 2019 15:30:15 +0000 Subject: [PATCH 01/25] Move help from Comment-based to md. Relocate functions (sans help) --- AddDataValidation.ps1 | 99 - ArgumentCompletion.ps1 | 131 + Charting/BarChart.md | 137 + Charting.ps1 => Charting/Charting.ps1 | 0 Charting/ColumnChart.md | 137 + Charting/LineChart.md | 137 + Charting/PieChart.md | 137 + Charting/doChart.md | 134 + ColorCompletion.ps1 | 44 - ConvertFromExcelToSQLInsert.ps1 | 118 - Examples/XlRangeToImage/XlRangeToImage.ps1 | 2 +- Export-Excel.ps1 | 1399 - .../Add-ConditionalFormatting.ps1 | 123 +- ExportedCommands/Add-ExcelChart.ps1 | 142 + .../Add-ExcelDataValidationRule.ps1 | 58 + ExportedCommands/Add-ExcelName.ps1 | 30 + ExportedCommands/Add-ExcelTable.ps1 | 75 + ExportedCommands/Add-PivotTable.ps1 | 176 + ExportedCommands/Add-Worksheet.ps1 | 80 + ExportedCommands/Close-ExcelPackage.ps1 | 34 + .../Compare-WorkSheet.ps1 | 87 - .../Convert-ExcelRangeToImage.ps1 | 24 +- ExportedCommands/ConvertFrom-ExcelData.md | 161 + .../ConvertFrom-ExcelData.ps1 | 23 +- ExportedCommands/ConvertFrom-ExcelSheet.md | 140 + ExportedCommands/ConvertFrom-ExcelSheet.ps1 | 48 + .../ConvertFrom-ExcelToSQLInsert.ps1 | 48 + ExportedCommands/ConvertTo-ExcelXlsx.md | 72 + .../ConvertTo-ExcelXlsx.ps1 | 4 - .../Copy-ExcelWorkSheet.ps1 | 35 - ExportedCommands/Expand-NumberFormat.ps1 | 77 + ExportedCommands/Export-Excel.ps1 | 670 + ExportedCommands/Export-ExcelSheet.md | 138 + .../Export-ExcelSheet.ps1 | 0 .../Export-MultipleExcelSheets.md | 120 + .../Export-MultipleExcelSheets.ps1 | 27 + .../Export-StocksToExcel.ps1 | 0 ExportedCommands/Get-ExcelColumnName.md | 60 + .../Get-ExcelColumnName.ps1 | 0 .../Get-ExcelSheetInfo.ps1 | 18 - ExportedCommands/Get-ExcelWorkbookInfo.ps1 | 27 + ExportedCommands/Get-HtmlTable.md | 121 + .../Get-HtmlTable.ps1 | 0 ExportedCommands/Get-Range.md | 87 + .../Get-Range.ps1 | 0 ExportedCommands/Get-XYRange.md | 57 + .../Get-XYRange.ps1 | 0 ExportedCommands/Import-Excel.ps1 | 399 + ExportedCommands/Import-Html.md | 121 + .../Import-Html.ps1 | 0 ExportedCommands/Import-UPS.md | 72 + .../Import-UPS.ps1 | 0 ExportedCommands/Import-USPS.md | 72 + ExportedCommands/Import-USPS.ps1 | 9 + ExportedCommands/Invoke-Sum.md | 87 + .../Invoke-Sum.ps1 | 0 .../Join-Worksheet.ps1 | 82 +- ExportedCommands/Merge-MultipleSheets.ps1 | 147 + ExportedCommands/Merge-Worksheet.ps1 | 263 + .../New-ConditionalFormattingIconSet.ps1 | 28 - ExportedCommands/New-ConditionalText.ps1 | 41 + ExportedCommands/New-ExcelChartDefinition.ps1 | 88 + ExportedCommands/New-ExcelStyle.md | 570 + ExportedCommands/New-ExcelStyle.ps1 | 45 + ExportedCommands/New-PSItem.md | 42 + .../New-PSItem.ps1 | 0 ExportedCommands/New-PivotTableDefinition.ps1 | 72 + ExportedCommands/Open-ExcelPackage.ps1 | 44 + .../Remove-WorkSheet.ps1 | 17 - ExportedCommands/Select-Worksheet.ps1 | 24 + .../Send-SQLDataToExcel.ps1 | 92 - ExportedCommands/Set-CellStyle.md | 119 + .../Set-CellStyle.ps1 | 0 .../Set-ExcelColumn.ps1 | 81 - ExportedCommands/Set-ExcelRange.ps1 | 199 + .../Set-ExcelRow.ps1 | 67 - ExportedCommands/Set-WorkSheetProtection.md | 349 + .../Set-WorkSheetProtection.ps1 | 29 - .../Update-FirstObjectProperties.ps1 | 23 + Get-ExcelWorkbookInfo.ps1 | 65 - ImportExcel.psd1 | 4 +- ImportExcel.psm1 | 589 +- InferData.ps1 => InferData/InferData.ps1 | 0 InferData/Invoke-AllTests.md | 87 + InferData/Test-Boolean.md | 57 + InferData/Test-Date.md | 57 + InferData/Test-Integer.md | 57 + InferData/Test-Number.md | 57 + InferData/Test-String.md | 57 + Merge-Worksheet.ps1 | 539 - New-ConditionalText.ps1 | 84 - New-ExcelChart.ps1 | 471 - New-Plot.md | 42 + Open-ExcelPackage.ps1 | 129 - Pivot/Pivot.md | 107 + Pivot.ps1 => Pivot/Pivot.ps1 | 0 PivotTable.ps1 | 420 - SetFormat.ps1 | 496 - Update-FirstObjectProperties.ps1 | 98 - .../Set-Row_Set-Column-SetFormat.tests.ps1 | 12 - en-US/ImportExcel-help.xml | 23342 ++++++++++++++++ mdHelp/Add-ConditionalFormatting.md | 482 + mdHelp/Add-ExcelChart.md | 736 + mdHelp/Add-ExcelDataValidationRule.md | 319 + mdHelp/Add-ExcelName.md | 72 + mdHelp/Add-ExcelTable.md | 236 + mdHelp/Add-PivotTable.md | 659 + mdHelp/Add-WorkSheet.md | 248 + mdHelp/Close-ExcelPackage.md | 143 + mdHelp/Compare-WorkSheet.md | 397 + mdHelp/Convert-ExcelRangeToImage.md | 117 + mdHelp/ConvertFrom-ExcelToSQLInsert.md | 225 + mdHelp/Copy-ExcelWorkSheet.md | 150 + mdHelp/Expand-NumberFormat.md | 70 + mdHelp/Export-Excel.md | 1397 + mdHelp/Get-ExcelSheetInfo.md | 60 + mdHelp/Get-ExcelWorkbookInfo.md | 82 + mdHelp/Import-Excel.md | 425 + mdHelp/Join-Worksheet.md | 553 + mdHelp/Merge-MultipleSheets.md | 330 + mdHelp/Merge-Worksheet.md | 462 + mdHelp/New-ConditionalFormattingIconSet.md | 92 + mdHelp/New-ConditionalText.md | 153 + mdHelp/New-ExcelChartDefinition.md | 634 + mdHelp/New-PivotTableDefinition.md | 538 + mdHelp/Open-ExcelPackage.md | 120 + mdHelp/Remove-WorkSheet.md | 135 + mdHelp/Select-Worksheet.md | 127 + mdHelp/Send-SQLDataToExcel.md | 288 + mdHelp/Set-ExcelColumn.md | 567 + mdHelp/Set-ExcelRange.md | 594 + mdHelp/Set-ExcelRow.md | 622 + mdHelp/Update-FirstObjectProperties.md | 94 + 133 files changed, 41075 insertions(+), 5241 deletions(-) delete mode 100644 AddDataValidation.ps1 create mode 100644 ArgumentCompletion.ps1 create mode 100644 Charting/BarChart.md rename Charting.ps1 => Charting/Charting.ps1 (100%) create mode 100644 Charting/ColumnChart.md create mode 100644 Charting/LineChart.md create mode 100644 Charting/PieChart.md create mode 100644 Charting/doChart.md delete mode 100644 ColorCompletion.ps1 delete mode 100644 ConvertFromExcelToSQLInsert.ps1 delete mode 100644 Export-Excel.ps1 rename AddConditionalFormatting.ps1 => ExportedCommands/Add-ConditionalFormatting.ps1 (58%) create mode 100644 ExportedCommands/Add-ExcelChart.ps1 create mode 100644 ExportedCommands/Add-ExcelDataValidationRule.ps1 create mode 100644 ExportedCommands/Add-ExcelName.ps1 create mode 100644 ExportedCommands/Add-ExcelTable.ps1 create mode 100644 ExportedCommands/Add-PivotTable.ps1 create mode 100644 ExportedCommands/Add-Worksheet.ps1 create mode 100644 ExportedCommands/Close-ExcelPackage.ps1 rename Compare-WorkSheet.ps1 => ExportedCommands/Compare-WorkSheet.ps1 (68%) rename ConvertExcelToImageFile.ps1 => ExportedCommands/Convert-ExcelRangeToImage.ps1 (69%) create mode 100644 ExportedCommands/ConvertFrom-ExcelData.md rename ConvertFromExcelData.ps1 => ExportedCommands/ConvertFrom-ExcelData.ps1 (58%) create mode 100644 ExportedCommands/ConvertFrom-ExcelSheet.md create mode 100644 ExportedCommands/ConvertFrom-ExcelSheet.ps1 create mode 100644 ExportedCommands/ConvertFrom-ExcelToSQLInsert.ps1 create mode 100644 ExportedCommands/ConvertTo-ExcelXlsx.md rename ConvertToExcelXlsx.ps1 => ExportedCommands/ConvertTo-ExcelXlsx.ps1 (94%) rename Copy-ExcelWorkSheet.ps1 => ExportedCommands/Copy-ExcelWorkSheet.ps1 (68%) create mode 100644 ExportedCommands/Expand-NumberFormat.ps1 create mode 100644 ExportedCommands/Export-Excel.ps1 create mode 100644 ExportedCommands/Export-ExcelSheet.md rename Export-ExcelSheet.ps1 => ExportedCommands/Export-ExcelSheet.ps1 (100%) create mode 100644 ExportedCommands/Export-MultipleExcelSheets.md create mode 100644 ExportedCommands/Export-MultipleExcelSheets.ps1 rename Export-StocksToExcel.ps1 => ExportedCommands/Export-StocksToExcel.ps1 (100%) create mode 100644 ExportedCommands/Get-ExcelColumnName.md rename Get-ExcelColumnName.ps1 => ExportedCommands/Get-ExcelColumnName.ps1 (100%) rename Get-ExcelSheetInfo.ps1 => ExportedCommands/Get-ExcelSheetInfo.ps1 (61%) create mode 100644 ExportedCommands/Get-ExcelWorkbookInfo.ps1 create mode 100644 ExportedCommands/Get-HtmlTable.md rename Get-HtmlTable.ps1 => ExportedCommands/Get-HtmlTable.ps1 (100%) create mode 100644 ExportedCommands/Get-Range.md rename Get-Range.ps1 => ExportedCommands/Get-Range.ps1 (100%) create mode 100644 ExportedCommands/Get-XYRange.md rename Get-XYRange.ps1 => ExportedCommands/Get-XYRange.ps1 (100%) create mode 100644 ExportedCommands/Import-Excel.ps1 create mode 100644 ExportedCommands/Import-Html.md rename Import-Html.ps1 => ExportedCommands/Import-Html.ps1 (100%) create mode 100644 ExportedCommands/Import-UPS.md rename TrackingUtils.ps1 => ExportedCommands/Import-UPS.ps1 (100%) create mode 100644 ExportedCommands/Import-USPS.md create mode 100644 ExportedCommands/Import-USPS.ps1 create mode 100644 ExportedCommands/Invoke-Sum.md rename Invoke-Sum.ps1 => ExportedCommands/Invoke-Sum.ps1 (100%) rename Join-Worksheet.ps1 => ExportedCommands/Join-Worksheet.ps1 (52%) create mode 100644 ExportedCommands/Merge-MultipleSheets.ps1 create mode 100644 ExportedCommands/Merge-Worksheet.ps1 rename New-ConditionalFormattingIconSet.ps1 => ExportedCommands/New-ConditionalFormattingIconSet.ps1 (58%) create mode 100644 ExportedCommands/New-ConditionalText.ps1 create mode 100644 ExportedCommands/New-ExcelChartDefinition.ps1 create mode 100644 ExportedCommands/New-ExcelStyle.md create mode 100644 ExportedCommands/New-ExcelStyle.ps1 create mode 100644 ExportedCommands/New-PSItem.md rename New-PSItem.ps1 => ExportedCommands/New-PSItem.ps1 (100%) create mode 100644 ExportedCommands/New-PivotTableDefinition.ps1 create mode 100644 ExportedCommands/Open-ExcelPackage.ps1 rename RemoveWorksheet.ps1 => ExportedCommands/Remove-WorkSheet.ps1 (53%) create mode 100644 ExportedCommands/Select-Worksheet.ps1 rename Send-SQLDataToExcel.ps1 => ExportedCommands/Send-SQLDataToExcel.ps1 (51%) create mode 100644 ExportedCommands/Set-CellStyle.md rename Set-CellStyle.ps1 => ExportedCommands/Set-CellStyle.ps1 (100%) rename Set-Column.ps1 => ExportedCommands/Set-ExcelColumn.ps1 (57%) create mode 100644 ExportedCommands/Set-ExcelRange.ps1 rename Set-Row.ps1 => ExportedCommands/Set-ExcelRow.ps1 (64%) create mode 100644 ExportedCommands/Set-WorkSheetProtection.md rename Set-WorkSheetProtection.ps1 => ExportedCommands/Set-WorkSheetProtection.ps1 (51%) create mode 100644 ExportedCommands/Update-FirstObjectProperties.ps1 delete mode 100644 Get-ExcelWorkbookInfo.ps1 rename InferData.ps1 => InferData/InferData.ps1 (100%) create mode 100644 InferData/Invoke-AllTests.md create mode 100644 InferData/Test-Boolean.md create mode 100644 InferData/Test-Date.md create mode 100644 InferData/Test-Integer.md create mode 100644 InferData/Test-Number.md create mode 100644 InferData/Test-String.md delete mode 100644 Merge-Worksheet.ps1 delete mode 100644 New-ConditionalText.ps1 delete mode 100644 New-ExcelChart.ps1 create mode 100644 New-Plot.md delete mode 100644 Open-ExcelPackage.ps1 create mode 100644 Pivot/Pivot.md rename Pivot.ps1 => Pivot/Pivot.ps1 (100%) delete mode 100644 PivotTable.ps1 delete mode 100644 SetFormat.ps1 delete mode 100644 Update-FirstObjectProperties.ps1 create mode 100644 en-US/ImportExcel-help.xml create mode 100644 mdHelp/Add-ConditionalFormatting.md create mode 100644 mdHelp/Add-ExcelChart.md create mode 100644 mdHelp/Add-ExcelDataValidationRule.md create mode 100644 mdHelp/Add-ExcelName.md create mode 100644 mdHelp/Add-ExcelTable.md create mode 100644 mdHelp/Add-PivotTable.md create mode 100644 mdHelp/Add-WorkSheet.md create mode 100644 mdHelp/Close-ExcelPackage.md create mode 100644 mdHelp/Compare-WorkSheet.md create mode 100644 mdHelp/Convert-ExcelRangeToImage.md create mode 100644 mdHelp/ConvertFrom-ExcelToSQLInsert.md create mode 100644 mdHelp/Copy-ExcelWorkSheet.md create mode 100644 mdHelp/Expand-NumberFormat.md create mode 100644 mdHelp/Export-Excel.md create mode 100644 mdHelp/Get-ExcelSheetInfo.md create mode 100644 mdHelp/Get-ExcelWorkbookInfo.md create mode 100644 mdHelp/Import-Excel.md create mode 100644 mdHelp/Join-Worksheet.md create mode 100644 mdHelp/Merge-MultipleSheets.md create mode 100644 mdHelp/Merge-Worksheet.md create mode 100644 mdHelp/New-ConditionalFormattingIconSet.md create mode 100644 mdHelp/New-ConditionalText.md create mode 100644 mdHelp/New-ExcelChartDefinition.md create mode 100644 mdHelp/New-PivotTableDefinition.md create mode 100644 mdHelp/Open-ExcelPackage.md create mode 100644 mdHelp/Remove-WorkSheet.md create mode 100644 mdHelp/Select-Worksheet.md create mode 100644 mdHelp/Send-SQLDataToExcel.md create mode 100644 mdHelp/Set-ExcelColumn.md create mode 100644 mdHelp/Set-ExcelRange.md create mode 100644 mdHelp/Set-ExcelRow.md create mode 100644 mdHelp/Update-FirstObjectProperties.md diff --git a/AddDataValidation.ps1 b/AddDataValidation.ps1 deleted file mode 100644 index 5328089..0000000 --- a/AddDataValidation.ps1 +++ /dev/null @@ -1,99 +0,0 @@ -Function Add-ExcelDataValidationRule { - <# - .Synopsis - Adds data validation to a range of cells - .Example - > - >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 - > - >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 are 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 - > - >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. - #> - - [CmdletBinding()] - Param( - #The range of cells to be validate, e.g. "B2:C100" - [Parameter(ValueFromPipeline = $true,Position=0)] - [Alias("Address")] - $Range , - #The worksheet where the cells should be validated - [OfficeOpenXml.ExcelWorksheet]$WorkSheet , - #An option corresponding to a choice from the 'Allow' pull down on the settings page in the Excel dialog. Any means "any allowed" i.e. no Validation - [ValidateSet('Any','Custom','DateTime','Decimal','Integer','List','TextLength','Time')] - $ValidationType, - #The operator to apply to Decimal, Integer, TextLength, DateTime and time fields, e.g. equal, between - [OfficeOpenXml.DataValidation.ExcelDataValidationOperator]$Operator = [OfficeOpenXml.DataValidation.ExcelDataValidationOperator]::equal , - #For Decimal, Integer, TextLength, DateTime the [first] data value - $Value, - #When using the between operator, the second data value - $Value2, - #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 - $Formula, - #When using the between operator, the second data value as a formula - $Formula2, - #When using the list validation type, a set of values (rather than refering to Sheet!B$2:B$100 ) - $ValueSet, - #Corresponds to the the 'Show Error alert ...' check box on error alert page in the Excel dialog - [switch]$ShowErrorMessage, - #Stop, Warning, or Infomation, corresponding to to the style setting in the Excel dialog - [OfficeOpenXml.DataValidation.ExcelDataValidationWarningStyle]$ErrorStyle, - #The title for the message box corresponding to to the title setting in the Excel dialog - [String]$ErrorTitle, - #The error message corresponding to to the Error message setting in the Excel dialog - [String]$ErrorBody, - #Corresponds to the the 'Show Input message ...' check box on input message page in the Excel dialog - [switch]$ShowPromptMessage, - #The prompt message corresponding to to the Input message setting in the Excel dialog - [String]$PromptBody, - #The title for the message box corresponding to to the title setting in the Excel dialog - [String]$PromptTitle, - #By default the 'Ignore blank' option will be selected, unless NoBlank is sepcified. - [String]$NoBlank - ) - if ($Range -is [Array]) { - $null = $PSBoundParameters.Remove("Range") - $Range | Add-ExcelDataValidationRule @PSBoundParameters - } - else { - #We should accept, a worksheet and a name of a range or a cell address; a table; the address of a table; a named range; a row, a column or .Cells[ ] - if (-not $WorkSheet -and $Range.worksheet) {$WorkSheet = $Range.worksheet} - if ($Range.Address) {$Range = $Range.Address} - - if ($Range -isnot [string] -or -not $WorkSheet) {Write-Warning -Message "You need to provide a worksheet and range of cells." ;return} - #else we assume Range is a range. - - $validation = $WorkSheet.DataValidations."Add$ValidationType`Validation"($Range) - if ($validation.AllowsOperator) {$validation.Operator = $Operator} - if ($PSBoundParameters.ContainsKey('value')) { - $validation.Formula.Value = $Value - } - elseif ($Formula) {$validation.Formula.ExcelFormula = $Formula} - elseif ($ValueSet) {Foreach ($v in $ValueSet) {$validation.Formula.Values.Add($V)}} - if ($PSBoundParameters.ContainsKey('Value2')) { - $validation.Formula2.Value = $Value2 - } - elseif ($Formula2) {$validation.Formula2.ExcelFormula = $Formula} - $validation.ShowErrorMessage = [bool]$ShowErrorMessage - $validation.ShowInputMessage = [bool]$ShowPromptMessage - $validation.AllowBlank = -not $NoBlank - - if ($PromptTitle) {$validation.PromptTitle = $PromptTitle} - if ($ErrorTitle) {$validation.ErrorTitle = $ErrorTitle} - if ($PromptBody) {$validation.Prompt = $PromptBody} - if ($ErrorBody) {$validation.Error = $ErrorBody} - if ($ErrorStyle) {$validation.ErrorStyle = $ErrorStyle} - } - } diff --git a/ArgumentCompletion.ps1 b/ArgumentCompletion.ps1 new file mode 100644 index 0000000..55823e0 --- /dev/null +++ b/ArgumentCompletion.ps1 @@ -0,0 +1,131 @@ +function ColorCompletion { + param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) + [System.Drawing.KnownColor].GetFields() | Where-Object {$_.IsStatic -and $_.name -like "$wordToComplete*" } | + Sort-Object name | ForEach-Object {New-CompletionResult $_.name $_.name + } +} + +function ListFonts { + param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) + if (-not $script:FontFamilies) { + $script:FontFamilies = @("","") + try { + $script:FontFamilies = (New-Object System.Drawing.Text.InstalledFontCollection).Families.Name + } + catch {} + } + $script:FontFamilies.where({$_ -Gt "" -and $_ -like "$wordToComplete*"} ) | ForEach-Object { + New-Object -TypeName System.Management.Automation.CompletionResult -ArgumentList "'$_'" , $_ , + ([System.Management.Automation.CompletionResultType]::ParameterValue) , $_ + } +} + +function NumberFormatCompletion { + param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) + $numformats = [ordered]@{ + "General" = "General" # format ID 0 + "Number" = "0.00" # format ID 2 + "Percentage" = "0.00%" # format ID 10 + "Scientific" = "0.00E+00" # format ID 11 + "Fraction" = "# ?/?" # format ID 12 + "Short Date" = "Localized" # format ID 14 - will be translated to "mm-dd-yy" which is localized on load by Excel. + "Short Time" = "Localized" # format ID 20 - will be translated to "h:mm" which is localized on load by Excel. + "Long Time" = "Localized" # format ID 21 - will be translated to "h:mm:ss" which is localized on load by Excel. + "Date-Time" = "Localized" # format ID 22 - will be translated to "m/d/yy h:mm" which is localized on load by Excel. + "Currency" = [cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol + "#,##0.00" + "Text" = "@" # format ID 49 + "h:mm AM/PM" = "h:mm AM/PM" # format ID 18 + "h:mm:ss AM/PM" = "h:mm:ss AM/PM" # format ID 19 + "mm:ss" = "mm:ss" # format ID 45 + "[h]:mm:ss" = "Elapsed hours" # format ID 46 + "mm:ss.0" = "mm:ss.0" # format ID 47 + "d-mmm-yy" = "Localized" # format ID 15 which is localized on load by Excel. + "d-mmm" = "Localized" # format ID 16 which is localized on load by Excel. + "mmm-yy" = "mmm-yy" # format ID 17 which is localized on load by Excel. + "0" = "Whole number" # format ID 1 + "0.00" = "Number, 2 decimals" # format ID 2 or "number" + "#,##0" = "Thousand separators" # format ID 3 + "#,##0.00" = "Thousand separators and 2 decimals" # format ID 4 + "#," = "Whole thousands" + "#.0,," = "Millions, 1 Decimal" + "0%" = "Nearest whole percentage" # format ID 9 + "0.00%" = "Percentage with decimals" # format ID 10 or "Percentage" + "00E+00" = "Scientific" # format ID 11 or "Scientific" + "# ?/?" = "One Digit fraction" # format ID 12 or "Fraction" + "# ??/??" = "Two Digit fraction" # format ID 13 + "@" = "Text" # format ID 49 or "Text" + } + $numformats.keys.where({$_ -like "$wordToComplete*"} ) | ForEach-Object { + New-Object -TypeName System.Management.Automation.CompletionResult -ArgumentList "'$_'" , $_ , + ([System.Management.Automation.CompletionResultType]::ParameterValue) , $numformats[$_] + } +} + +function WorksheetArgumentCompleter { + param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) + $xlPath = $fakeBoundParameter['Path'] + if (Test-Path -Path $xlPath) { + $xlpkg = Open-ExcelPackage -ReadOnly -Path $xlPath + $WorksheetNames = $xlPkg.Workbook.Worksheets.Name + Close-ExcelPackage -nosave -ExcelPackage $xlpkg + $WorksheetNames.where( { $_ -like "*$wordToComplete*" }) | foreach-object { + New-Object -TypeName System.Management.Automation.CompletionResult -ArgumentList "'$_'", + $_ , ([System.Management.Automation.CompletionResultType]::ParameterValue) , $_ + } + } +} + +If (Get-Command -ErrorAction SilentlyContinue -name Register-ArgumentCompleter) { + Register-ArgumentCompleter -CommandName Export-Excel -ParameterName TitleBackgroundColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName DataBarColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName ForeGroundColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName PatternColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Compare-Worksheet -ParameterName AllDataBackgroundColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Compare-Worksheet -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Compare-Worksheet -ParameterName FontColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Compare-Worksheet -ParameterName TabColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Join-Worksheet -ParameterName TitleBackgroundColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Merge-Worksheet -ParameterName AddBackgroundColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Merge-Worksheet -ParameterName ChangeBackgroundColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Merge-Worksheet ` -ParameterName DeleteBackgroundColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Merge-MulipleSheets -ParameterName KeyFontColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Merge-MulipleSheets -ParameterName AddBackgroundColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Merge-MulipleSheets -ParameterName ChangeBackgroundColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Merge-MulipleSheets ` -ParameterName DeleteBackgroundColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Merge-MulipleSheets -ParameterName KeyFontColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName New-ConditionalText -ParameterName PatternColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName New-ConditionalText -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName New-ConditionalText -ParameterName ConditionalTextColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName New-ExcelStyle -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName New-ExcelStyle -ParameterName FontColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName New-ExcelStyle -ParameterName BorderColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName New-ExcelStyle -ParameterName PatternColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Set-ExcelRange -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Set-ExcelRange -ParameterName FontColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Set-ExcelRange -ParameterName BorderColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Set-ExcelRange -ParameterName PatternColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Set-ExcelColumn -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Set-ExcelColumn -ParameterName FontColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Set-ExcelColumn -ParameterName PatternColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Set-ExcelRow -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Set-ExcelRow -ParameterName FontColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName Set-ExcelRow -ParameterName PatternColor -ScriptBlock $Function:ColorCompletion + Register-ArgumentCompleter -CommandName New-ExcelStyle -ParameterName FontName -ScriptBlock $Function:ListFonts + Register-ArgumentCompleter -CommandName Set-ExcelColumn -ParameterName FontName -ScriptBlock $Function:ListFonts + Register-ArgumentCompleter -CommandName Set-ExcelRange -ParameterName FontName -ScriptBlock $Function:ListFonts + Register-ArgumentCompleter -CommandName Set-ExcelRow -ParameterName FontName -ScriptBlock $Function:ListFonts + Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName Export-Excel -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName New-ExcelStyle -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName Set-ExcelRange -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName Set-ExcelColumn -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName Set-ExcelRow -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName Add-PivotTable -ParameterName PivotNumberFormat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName New-PivotTableDefinition -ParameterName PivotNumberFormat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName New-ExcelChartDefinition -ParameterName XAxisNumberformat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName New-ExcelChartDefinition -ParameterName YAxisNumberformat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName Add-ExcelChart -ParameterName XAxisNumberformat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName Add-ExcelChart -ParameterName YAxisNumberformat -ScriptBlock $Function:NumberFormatCompletion + Register-ArgumentCompleter -CommandName Import-Excel -ParameterName WorksheetName -ScriptBlock $Function:WorksheetArgumentCompleter +} diff --git a/Charting/BarChart.md b/Charting/BarChart.md new file mode 100644 index 0000000..0c73fa6 --- /dev/null +++ b/Charting/BarChart.md @@ -0,0 +1,137 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# BarChart + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +BarChart [[-targetData] ] [[-title] ] [[-ChartType] ] [-NoLegend] [-ShowCategory] + [-ShowPercent] [] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -ChartType +{{ Fill ChartType Description }} + +```yaml +Type: eChartType +Parameter Sets: (All) +Aliases: +Accepted values: 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 + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoLegend +{{ Fill NoLegend Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowCategory +{{ Fill ShowCategory Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowPercent +{{ Fill ShowPercent Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -targetData +{{ Fill targetData Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -title +{{ Fill title Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### System.Object + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/Charting.ps1 b/Charting/Charting.ps1 similarity index 100% rename from Charting.ps1 rename to Charting/Charting.ps1 diff --git a/Charting/ColumnChart.md b/Charting/ColumnChart.md new file mode 100644 index 0000000..0e57227 --- /dev/null +++ b/Charting/ColumnChart.md @@ -0,0 +1,137 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# ColumnChart + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +ColumnChart [[-targetData] ] [[-title] ] [[-ChartType] ] [-NoLegend] + [-ShowCategory] [-ShowPercent] [] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -ChartType +{{ Fill ChartType Description }} + +```yaml +Type: eChartType +Parameter Sets: (All) +Aliases: +Accepted values: 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 + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoLegend +{{ Fill NoLegend Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowCategory +{{ Fill ShowCategory Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowPercent +{{ Fill ShowPercent Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -targetData +{{ Fill targetData Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -title +{{ Fill title Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### System.Object + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/Charting/LineChart.md b/Charting/LineChart.md new file mode 100644 index 0000000..e45ea45 --- /dev/null +++ b/Charting/LineChart.md @@ -0,0 +1,137 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# LineChart + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +LineChart [[-targetData] ] [[-title] ] [[-ChartType] ] [-NoLegend] [-ShowCategory] + [-ShowPercent] [] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -ChartType +{{ Fill ChartType Description }} + +```yaml +Type: eChartType +Parameter Sets: (All) +Aliases: +Accepted values: 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 + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoLegend +{{ Fill NoLegend Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowCategory +{{ Fill ShowCategory Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowPercent +{{ Fill ShowPercent Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -targetData +{{ Fill targetData Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -title +{{ Fill title Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### System.Object + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/Charting/PieChart.md b/Charting/PieChart.md new file mode 100644 index 0000000..93c7fdd --- /dev/null +++ b/Charting/PieChart.md @@ -0,0 +1,137 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# PieChart + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +PieChart [[-targetData] ] [[-title] ] [[-ChartType] ] [-NoLegend] [-ShowCategory] + [-ShowPercent] [] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -ChartType +{{ Fill ChartType Description }} + +```yaml +Type: eChartType +Parameter Sets: (All) +Aliases: +Accepted values: 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 + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoLegend +{{ Fill NoLegend Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowCategory +{{ Fill ShowCategory Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowPercent +{{ Fill ShowPercent Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -targetData +{{ Fill targetData Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -title +{{ Fill title Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### System.Object + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/Charting/doChart.md b/Charting/doChart.md new file mode 100644 index 0000000..414559f --- /dev/null +++ b/Charting/doChart.md @@ -0,0 +1,134 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# DoChart + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +DoChart [[-targetData] ] [[-title] ] [[-ChartType] ] [-NoLegend] [-ShowCategory] + [-ShowPercent] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -ChartType +{{ Fill ChartType Description }} + +```yaml +Type: eChartType +Parameter Sets: (All) +Aliases: +Accepted values: 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 + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoLegend +{{ Fill NoLegend Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowCategory +{{ Fill ShowCategory Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowPercent +{{ Fill ShowPercent Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -targetData +{{ Fill targetData Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -title +{{ Fill title Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/ColorCompletion.ps1 b/ColorCompletion.ps1 deleted file mode 100644 index 50d03fd..0000000 --- a/ColorCompletion.ps1 +++ /dev/null @@ -1,44 +0,0 @@ -Function ColorCompletion { - param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) - [System.Drawing.KnownColor].GetFields() | Where-Object {$_.IsStatic -and $_.name -like "$wordToComplete*" } | - Sort-Object name | ForEach-Object {New-CompletionResult $_.name $_.name - } -} - -if (Get-Command -Name register-argumentCompleter -ErrorAction SilentlyContinue) { - Register-ArgumentCompleter -CommandName Export-Excel -ParameterName TitleBackgroundColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName DataBarColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName ForeGroundColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName PatternColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Compare-Worksheet -ParameterName AllDataBackgroundColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Compare-Worksheet -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Compare-Worksheet -ParameterName FontColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Compare-Worksheet -ParameterName TabColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Join-Worksheet -ParameterName TitleBackgroundColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Merge-Worksheet -ParameterName AddBackgroundColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Merge-Worksheet -ParameterName ChangeBackgroundColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Merge-Worksheet ` -ParameterName DeleteBackgroundColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Merge-MulipleSheets -ParameterName KeyFontColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Merge-MulipleSheets -ParameterName AddBackgroundColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Merge-MulipleSheets -ParameterName ChangeBackgroundColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Merge-MulipleSheets ` -ParameterName DeleteBackgroundColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Merge-MulipleSheets -ParameterName KeyFontColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName New-ConditionalText -ParameterName PatternColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName New-ConditionalText -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName New-ConditionalText -ParameterName ConditionalTextColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName New-ExcelStyle -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName New-ExcelStyle -ParameterName FontColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName New-ExcelStyle -ParameterName BorderColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName New-ExcelStyle -ParameterName PatternColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Set-ExcelRange -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Set-ExcelRange -ParameterName FontColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Set-ExcelRange -ParameterName BorderColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Set-ExcelRange -ParameterName PatternColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Set-ExcelColumn -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Set-ExcelColumn -ParameterName FontColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Set-ExcelColumn -ParameterName PatternColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Set-ExcelRow -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Set-ExcelRow -ParameterName FontColor -ScriptBlock $Function:ColorCompletion - Register-ArgumentCompleter -CommandName Set-ExcelRow -ParameterName PatternColor -ScriptBlock $Function:ColorCompletion -} \ No newline at end of file diff --git a/ConvertFromExcelToSQLInsert.ps1 b/ConvertFromExcelToSQLInsert.ps1 deleted file mode 100644 index 7a3f00c..0000000 --- a/ConvertFromExcelToSQLInsert.ps1 +++ /dev/null @@ -1,118 +0,0 @@ -function ConvertFrom-ExcelToSQLInsert { - <# - .SYNOPSIS - Generate SQL insert statements from Excel spreadsheet. - .DESCRIPTION - Generate SQL insert statements from Excel spreadsheet. - .PARAMETER TableName - Name of the target database table. - .PARAMETER Path - Path to an existing .XLSX file - This parameter is passed to Import-Excel as is. - .PARAMETER WorkSheetname - Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported. - This parameter is passed to Import-Excel as is. - .PARAMETER StartRow - The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. - When the parameters ‘-NoHeader’ and ‘-HeaderName’ are not provided, this row will contain the column headers that will be used as property names. When one of both parameters are provided, the property names are automatically created and this row will be treated as a regular row containing data. - .PARAMETER Header - Specifies custom property names to use, instead of the values defined in the column headers of the TopRow. - If you provide fewr header names than there is data in the worksheet, then only the data with a corresponding header name will be imported and the data without header name will be disregarded. - If you provide more header names than there is data in the worksheet, then all data will be imported and all objects will have all the property names you defined in the header names. As such, the last properties will be blank as there is no data for them. - .PARAMETER NoHeader - Automatically generate property names (P1, P2, P3, ..) instead of the ones defined in the column headers of the TopRow. - This switch is best used when you want to import the complete worksheet ‘as is’ and are not concerned with the property names. - .PARAMETER DataOnly - Import only rows and columns that contain data, empty rows and empty columns are not imported. - .PARAMETER ConvertEmptyStringsToNull - If specified, cells without any data are replaced with NULL, instead of an empty string. - This is to address behviors in certain DBMS where an empty string is insert as 0 for INT column, instead of a NULL value. - - .EXAMPLE - 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:\> Import-Excel -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 - 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); - - #> - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - $TableName, - [Alias("FullName")] - [Parameter(ValueFromPipelineByPropertyName = $true, ValueFromPipeline = $true, Mandatory = $true)] - [ValidateScript( { Test-Path $_ -PathType Leaf })] - $Path, - [Alias("Sheet")] - $WorkSheetname = 1, - [Alias('HeaderRow', 'TopRow')] - [ValidateRange(1, 9999)] - [Int]$StartRow, - [string[]]$Header, - [switch]$NoHeader, - [switch]$DataOnly, - [switch]$ConvertEmptyStringsToNull, - [switch]$UseMSSQLSyntax - ) - - $null = $PSBoundParameters.Remove('TableName') - $null = $PSBoundParameters.Remove('ConvertEmptyStringsToNull') - $null = $PSBoundParameters.Remove('UseMSSQLSyntax') - - $params = @{} + $PSBoundParameters - - ConvertFrom-ExcelData @params { - param($propertyNames, $record) - - $ColumnNames = "'" + ($PropertyNames -join "', '") + "'" - if($UseMSSQLSyntax) { - $ColumnNames = "[" + ($PropertyNames -join "], [") + "]" - } - - $values = foreach ($propertyName in $PropertyNames) { - if ($ConvertEmptyStringsToNull.IsPresent -and [string]::IsNullOrEmpty($record.$propertyName)) { - 'NULL' - } - else { - "'" + $record.$propertyName + "'" - } - } - $targetValues = ($values -join ", ") - - "INSERT INTO {0} ({1}) Values({2});" -f $TableName, $ColumnNames, $targetValues - } -} \ No newline at end of file diff --git a/Examples/XlRangeToImage/XlRangeToImage.ps1 b/Examples/XlRangeToImage/XlRangeToImage.ps1 index fdfe98a..be7cfa2 100644 --- a/Examples/XlRangeToImage/XlRangeToImage.ps1 +++ b/Examples/XlRangeToImage/XlRangeToImage.ps1 @@ -21,4 +21,4 @@ West,Berry,4 Export-Excel $xlFileName -ReturnRange ` -ConditionalText (New-ConditionalText Apple), (New-ConditionalText Berry -ConditionalTextColor White -BackgroundColor Purple) -Convert-XlRangeToImage -Path $xlFileName -workSheetname sheet1 -range $range -Show +Convert-ExcelXlRangeToImage -Path $xlFileName -workSheetname sheet1 -range $range -Show diff --git a/Export-Excel.ps1 b/Export-Excel.ps1 deleted file mode 100644 index 4459690..0000000 --- a/Export-Excel.ps1 +++ /dev/null @@ -1,1399 +0,0 @@ -function Export-Excel { - <# - .SYNOPSIS - Exports data to an Excel worksheet. - .DESCRIPTION - Exports data to an Excel file and where possible tries to convert numbers - in text fields so Excel recognizes them as numbers instead of text. - After all: Excel is a spreadsheet program used for number manipulation - and calculations. If number conversion is not desired, use the - parameter -NoNumberConversion *. - .PARAMETER Path - Path to a new or existing .XLSX file. - .PARAMETER ExcelPackage - An object representing an Excel Package - usually this is returned by specifying -PassThru allowing multiple commands to work on the same workbook without saving and reloading each time. - .PARAMETER WorksheetName - The name of a sheet within the workbook - "Sheet1" by default. - .PARAMETER ClearSheet - If specified Export-Excel will remove any existing worksheet with the selected name. The Default behaviour is to overwrite cells in this sheet as needed (but leaving non-overwritten ones in place). - .PARAMETER Append - If specified data will be added to the end of an existing sheet, using the same column headings. - .PARAMETER TargetData - Data to insert onto the worksheet - this is usually provided from the pipeline. - .PARAMETER DisplayPropertySet - Many (but not all) objects have a hidden property named psStandardmembers with a child property DefaultDisplayPropertySet ; this parameter reduces the properties exported to those in this set. - .PARAMETER NoAliasOrScriptPropeties - Some objects duplicate existing properties by adding aliases, or have Script properties which take a long time to return a value and slow the export down, if specified this removes these properties - .PARAMETER ExcludeProperty - Specifies properties which may exist in the target data but should not be placed on the worksheet. - .PARAMETER Calculate - If specified a recalculation of the worksheet will be requested before saving. - .PARAMETER Title - Text of a title to be placed in the top left cell. - .PARAMETER TitleBold - Sets the title in boldface type. - .PARAMETER TitleSize - Sets the point size for the title. - .PARAMETER TitleBackgroundColor - Sets the cell background color for the title cell. - .PARAMETER TitleFillPattern - Sets the fill pattern for the title cell. - .PARAMETER Password - Sets password protection on the workbook. - .PARAMETER IncludePivotTable - Adds a PivotTable using the data in the worksheet. - .PARAMETER PivotTableName - If a PivotTable is created from command line parameters, specifies the name of the new sheet holding the pivot. Defaults to "WorksheetName-PivotTable". - .PARAMETER PivotRows - Name(s) of column(s) from the spreadsheet which will provide the Row name(s) in a PivotTable created from command line parameters. - .PARAMETER PivotColumns - Name(s) of columns from the spreadsheet which will provide the Column name(s) in a PivotTable created from command line parameters. - .PARAMETER PivotFilter - Name(s) columns from the spreadsheet which will provide the Filter name(s) in a PivotTable created from command line parameters. - .PARAMETER PivotData - In a PivotTable created from command line parameters, the fields to use in the table body are given as a Hash table in the form ColumnName = Average|Count|CountNums|Max|Min|Product|None|StdDev|StdDevP|Sum|Var|VarP. - .PARAMETER PivotDataToColumn - If there are multiple datasets in a PivotTable, by default they are shown as separate rows under the given row heading; this switch makes them separate columns. - .PARAMETER NoTotalsInPivot - In a PivotTable created from command line parameters, prevents the addition of totals to rows and columns. - .PARAMETER PivotTotals - By default, PivotTables have totals for each row (on the right) and for each column at the bottom. This allows just one or neither to be selected. - .PARAMETER PivotTableDefinition - Instead of describing a single PivotTable with multiple command-line parameters; you can use a HashTable in the form PivotTableName = Definition; - Definition is itself a Hashtable with Sheet, PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values. - .PARAMETER IncludePivotChart - Include a chart with the PivotTable - implies -IncludePivotTable. - .PARAMETER ChartType - The type for PivotChart (one of Excel's defined chart types). - .PARAMETER NoLegend - Exclude the legend from the PivotChart. - .PARAMETER ShowCategory - Add category labels to the PivotChart. - .PARAMETER ShowPercent - Add percentage labels to the PivotChart. - .PARAMETER ConditionalFormat - One or more conditional formatting rules defined with New-ConditionalFormattingIconSet. - .PARAMETER ConditionalText - Applies a Conditional formatting rule defined with New-ConditionalText. When specific conditions are met the format is applied. - .PARAMETER NoNumberConversion - By default we convert all values to numbers if possible, but this isn't always desirable. NoNumberConversion allows you to add exceptions for the conversion. The only Wildcard allowed is * for all properties - .PARAMETER BoldTopRow - Makes the top row boldface. - .PARAMETER NoHeader - Does not put field names at the top of columns. - .PARAMETER RangeName - Makes the data in the worksheet a named range. - .PARAMETER TableName - Makes the data in the worksheet a table with a name, and applies a style to it. The name must not contain spaces. If a style is specified without a name, table1, table2 etc. will be used. - .PARAMETER TableStyle - Selects the style for the named table - if a name is specified without a style, 'Medium6' is used as a default. - .PARAMETER BarChart - Creates a "quick" bar chart using the first text column as labels and the first numeric column as values - .PARAMETER ColumnChart - Creates a "quick" column chart using the first text column as labels and the first numeric column as values - .PARAMETER LineChart - Creates a "quick" line chart using the first text column as labels and the first numeric column as values - .PARAMETER PieChart - Creates a "quick" pie chart using the first text column as labels and the first numeric column as values - .PARAMETER ExcelChartDefinition - A hash table containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-Pivot] charts. - .PARAMETER HideSheet - Name(s) of Sheet(s) to hide in the workbook, supports wildcards. If the selection would cause all sheets to be hidden, the sheet being worked on will be revealed. - .PARAMETER UnHideSheet - Name(s) of Sheet(s) to reveal in the workbook, supports wildcards. - .PARAMETER MoveToStart - If specified, the worksheet will be moved to the start of the workbook. - -MoveToStart takes precedence over -MoveToEnd, -Movebefore and -MoveAfter if more than one is specified. - .PARAMETER MoveToEnd - 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.) - .PARAMETER MoveBefore - If specified, the worksheet will be moved before the nominated one (which can be a position starting from 1, or a name). - -MoveBefore takes precedence over -MoveAfter if both are specified. - .PARAMETER MoveAfter - If specified, the worksheet will be moved after the nominated one (which can be a position starting from 1, or a name or *). - If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically. - .PARAMETER KillExcel - Closes Excel - prevents errors writing to the file because Excel has it open. - .PARAMETER AutoNameRange - Makes each column a named range. - .PARAMETER StartRow - Row to start adding data. 1 by default. Row 1 will contain the title if any. Then headers will appear (Unless -No header is specified) then the data appears. - .PARAMETER StartColumn - Column to start adding data - 1 by default. - .PARAMETER FreezeTopRow - Freezes headers etc. in the top row. - .PARAMETER FreezeFirstColumn - Freezes titles etc. in the left column. - .PARAMETER FreezeTopRowFirstColumn - Freezes top row and left column (equivalent to Freeze pane 2,2 ). - .PARAMETER FreezePane - Freezes panes at specified coordinates (in the form RowNumber, ColumnNumber). - .PARAMETER AutoFilter - Enables the Excel filter on the complete header row, so users can easily sort, filter and/or search the data in the selected column. - .PARAMETER AutoSize - Sizes the width of the Excel column to the maximum width needed to display all the containing data in that cell. - .PARAMETER MaxAutoSizeRows - Autosizing can be time consuming, so this sets a maximum number of rows to look at for the Autosize operation. Default is 1000; If 0 is specified ALL rows will be checked - .PARAMETER Activate - If there is already content in the workbook, a new sheet will not be active UNLESS Activate is specified; if a PivotTable is included it will be the active sheet - .PARAMETER Now - The -Now switch is a shortcut that automatically creates a temporary file, enables "AutoSize", "TableName" and "Show", and opens the file immediately. - .PARAMETER NumberFormat - Formats all values that can be converted to a number to the format specified. - - Examples: - # integer (not really needed unless you need to round numbers, Excel will use default cell properties). - '0' - - # integer without displaying the number 0 in the cell. - '#' - - # number with 1 decimal place. - '0.0' - - # 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.00' - - # percentage (1 = 100%, 0.01 = 1%) - '0%' - - # Blue color for positive numbers and a red color for negative numbers. All numbers will be proceeded by a dollar sign '$'. - '[Blue]$#,##0.00;[Red]-$#,##0.00' - - .PARAMETER ReZip - If specified, Export-Excel will expand the contents of the .XLSX file (which is multiple files in a zip archive) and rebuild it. - .PARAMETER NoClobber - Not used. Left in to avoid problems with older scripts, it may be removed in future versions. - .PARAMETER CellStyleSB - A script block which is run at the end of the export to apply styles to cells (although it can be used for other purposes). - The script block is given three paramaters; an object containing the current worksheet, the Total number of Rows and the number of the last column. - .PARAMETER Show - Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first. - .PARAMETER ReturnRange - If specified, Export-Excel returns the range of added cells in the format "A1:Z100". - .PARAMETER PassThru - If specified, Export-Excel returns an object representing the Excel package without saving the package first. - To save, you need to call Close-ExcelPackage or send the object back to Export-Excel, or use its .Save() or SaveAs() method. - .EXAMPLE - Get-Process | Export-Excel .\Test.xlsx -show - Export all the processes to the Excel file 'Test.xlsx' and open the file immediately. - - .EXAMPLE - > - PS> $ExcelParams = @{ - Path = $env:TEMP + '\Excel.xlsx' - Show = $true - Verbose = $true - } - Remove-Item -Path $ExcelParams.Path -Force -EA Ignore - 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 - > - PS> $ExcelParams = @{ - Path = $env:TEMP + '\Excel.xlsx' - Show = $true - Verbose = $true - } - Remove-Item -Path $ExcelParams.Path -Force -EA Ignore - [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 - > - PS> $ExcelParams = @{ - Path = $env:TEMP + '\Excel.xlsx' - Show = $true - Verbose = $true - } - Remove-Item -Path $ExcelParams.Path -Force -EA Ignore - [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 - > - PS> $ExcelParams = @{ - Path = $env:TEMP + '\Excel.xlsx' - Show = $true - Verbose = $true - } - Remove-Item -Path $ExcelParams.Path -Force -EA Ignore - 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, whith a - background fill color of "LightPink" and the text in "DarkRed". - Where condition is not met the color willbe the default, black - text on a white background. - - .EXAMPLE - > - PS> $ExcelParams = @{ - Path = $env:TEMP + '\Excel.xlsx' - Show = $true - Verbose = $true - } - Remove-Item -Path $ExcelParams.Path -Force -EA Ignore - 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 - > - PS> $ExcelParams = @{ - Path = $env:TEMP + '\Excel.xlsx' - Show = $true - Verbose = $true - } - Remove-Item -Path $ExcelParams.Path -Force -EA Ignore - - $Array = @() - - $Obj1 = [PSCustomObject]@{ - Member1 = 'First' - Member2 = 'Second' - } - - $Obj2 = [PSCustomObject]@{ - Member1 = 'First' - Member2 = 'Second' - Member3 = 'Third' - } - - $Obj3 = [PSCustomObject]@{ - Member1 = 'First' - Member2 = 'Second' - Member3 = 'Third' - Member4 = 'Fourth' - } - - $Array = $Obj1, $Obj2, $Obj3 - $Array | Out-GridView -Title 'Not showing Member3 and Member4' - $Array | Update-FirstObjectProperties | Export-Excel @ExcelParams -WorksheetName Numbers - - Updates the first object of the array by adding property 'Member3' and 'Member4'. - Afterwards. all objects are exported to an Excel file and all column headers are visible. - - .EXAMPLE - Get-Process | Export-Excel .\test.xlsx -WorksheetName Processes -IncludePivotTable -Show -PivotRows Company -PivotData PM - - .EXAMPLE - Get-Process | Export-Excel .\test.xlsx -WorksheetName Processes -ChartType PieExploded3D -IncludePivotChart -IncludePivotTable -Show -PivotRows Company -PivotData PM - - .EXAMPLE - Get-Service | Export-Excel 'c:\temp\test.xlsx' -Show -IncludePivotTable -PivotRows status -PivotData @{status='count'} - - .EXAMPLE - > - PS> $pt = [ordered]@{} - $pt.pt1=@{ SourceWorkSheet = 'Sheet1'; - PivotRows = 'Status' - PivotData = @{'Status'='count'} - IncludePivotChart = $true - ChartType = 'BarClustered3D' - } - $pt.pt2=@{ SourceWorkSheet = 'Sheet2'; - PivotRows = 'Company' - PivotData = @{'Company'='count'} - IncludePivotChart = $true - ChartType = 'PieExploded3D' - } - Remove-Item -Path .\test.xlsx - Get-Service | Select-Object -Property Status,Name,DisplayName,StartType | Export-Excel -Path .\test.xlsx -AutoSize - Get-Process | Select-Object -Property Name,Company,Handles,CPU,VM | Export-Excel -Path .\test.xlsx -AutoSize -WorksheetName 'sheet2' - Export-Excel -Path .\test.xlsx -PivotTableDefinition $pt -Show - - This example defines two PivotTables. Then it puts Service data on Sheet1 - with one call to Export-Excel and Process Data on sheet2 with a second - call to Export-Excel. The third and final call adds the two PivotTables - and opens the spreadsheet in Excel. - .EXAMPLE - > - PS> Remove-Item -Path .\test.xlsx - $excel = Get-Service | Select-Object -Property Status,Name,DisplayName,StartType | Export-Excel -Path .\test.xlsx -PassThru - $excel.Workbook.Worksheets["Sheet1"].Row(1).style.font.bold = $true - $excel.Workbook.Worksheets["Sheet1"].Column(3 ).width = 29 - $excel.Workbook.Worksheets["Sheet1"].Column(3 ).Style.wraptext = $true - $excel.Save() - $excel.Dispose() - Start-Process .\test.xlsx - - This example uses -PassThru. It puts service information into sheet1 of the - workbook and saves the ExcelPackage object in $Excel. It then uses the package - object to apply formatting, and then saves the workbook and disposes of the object - before loading the document in Excel. Other commands in the module remove the need - to work directly with the package object in this way. - - .EXAMPLE - > - PS> Remove-Item -Path .\test.xlsx -ErrorAction Ignore - $excel = Get-Process | Select-Object -Property Name,Company,Handles,CPU,PM,NPM,WS | Export-Excel -Path .\test.xlsx -ClearSheet -WorksheetName "Processes" -PassThru - $sheet = $excel.Workbook.Worksheets["Processes"] - $sheet.Column(1) | Set-ExcelRange -Bold -AutoFit - $sheet.Column(2) | Set-ExcelRange -Width 29 -WrapText - $sheet.Column(3) | Set-ExcelRange -HorizontalAlignment Right -NFormat "#,###" - Set-ExcelRange -Address $sheet.Cells["E1:H1048576"] -HorizontalAlignment Right -NFormat "#,###" - Set-ExcelRange -Address $sheet.Column(4) -HorizontalAlignment Right -NFormat "#,##0.0" -Bold - Set-ExcelRange -Address $sheet.Row(1) -Bold -HorizontalAlignment Center - Add-ConditionalFormatting -WorkSheet $sheet -Range "D2:D1048576" -DataBarColor Red - Add-ConditionalFormatting -WorkSheet $sheet -Range "G2:G1048576" -RuleType GreaterThan -ConditionValue "104857600" -ForeGroundColor Red - foreach ($c in 5..9) {Set-ExcelRange -Address $sheet.Column($c) -AutoFit } - Export-Excel -ExcelPackage $excel -WorksheetName "Processes" -IncludePivotChart -ChartType ColumnClustered -NoLegend -PivotRows company -PivotData @{'Name'='Count'} -Show - - This a more sophisticated version of the previous example showing different - ways of using Set-ExcelRange, and also adding conditional formatting. - In the final command a PivotChart is added and the workbook is opened in Excel. - .EXAMPLE - 0..360 | ForEach-Object {[pscustomobject][ordered]@{X=$_; Sinx="=Sin(Radians(x)) "} } | Export-Excel -now -LineChart -AutoNameRange - - Creates a line chart showing the value of Sine(x) for values of X between 0 and 360 degrees. - - .EXAMPLE - > - 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 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 oder to get the -OutputAs parameter for the Invoke-Sqlcmd cmdlet. - - .LINK - https://github.com/dfinke/ImportExcel - #> - [CmdletBinding(DefaultParameterSetName = 'Default')] - [OutputType([OfficeOpenXml.ExcelPackage])] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] - Param( - [Parameter(ParameterSetName = 'Default', Position = 0)] - [String]$Path, - [Parameter(Mandatory = $true, ParameterSetName = "Package")] - [OfficeOpenXml.ExcelPackage]$ExcelPackage, - [Parameter(ValueFromPipeline = $true)] - [Alias('TargetData')] - $InputObject, - [Switch]$Calculate, - [Switch]$Show, - [String]$WorksheetName = 'Sheet1', - [String]$Password, - [switch]$ClearSheet, - [switch]$Append, - [String]$Title, - [OfficeOpenXml.Style.ExcelFillStyle]$TitleFillPattern = 'Solid', - [Switch]$TitleBold, - [Int]$TitleSize = 22, - $TitleBackgroundColor, - [Switch]$IncludePivotTable, - [String]$PivotTableName, - [String[]]$PivotRows, - [String[]]$PivotColumns, - $PivotData, - [String[]]$PivotFilter, - [Switch]$PivotDataToColumn, - [Hashtable]$PivotTableDefinition, - [Switch]$IncludePivotChart, - [OfficeOpenXml.Drawing.Chart.eChartType]$ChartType = 'Pie', - [Switch]$NoLegend, - [Switch]$ShowCategory, - [Switch]$ShowPercent, - [Switch]$AutoSize, - $MaxAutoSizeRows = 1000, - [Switch]$NoClobber, - [Switch]$FreezeTopRow, - [Switch]$FreezeFirstColumn, - [Switch]$FreezeTopRowFirstColumn, - [Int[]]$FreezePane, - [Switch]$AutoFilter, - [Switch]$BoldTopRow, - [Switch]$NoHeader, - [ValidateScript( { - if (-not $_) { throw 'RangeName is null or empty.' } - elseif ($_[0] -notmatch '[a-z]') { throw 'RangeName starts with an invalid character.' } - else { $true } - })] - [String]$RangeName, - [Alias('Table')] - $TableName, - [OfficeOpenXml.Table.TableStyles]$TableStyle = [OfficeOpenXml.Table.TableStyles]::Medium6, - [Switch]$Barchart, - [Switch]$PieChart, - [Switch]$LineChart , - [Switch]$ColumnChart , - [Object[]]$ExcelChartDefinition, - [String[]]$HideSheet, - [String[]]$UnHideSheet, - [Switch]$MoveToStart, - [Switch]$MoveToEnd, - $MoveBefore , - $MoveAfter , - [Switch]$KillExcel, - [Switch]$AutoNameRange, - [Int]$StartRow = 1, - [Int]$StartColumn = 1, - [alias('PT')] - [Switch]$PassThru, - [String]$Numberformat = 'General', - [string[]]$ExcludeProperty, - [Switch]$NoAliasOrScriptPropeties, - [Switch]$DisplayPropertySet, - [String[]]$NoNumberConversion, - [Object[]]$ConditionalFormat, - [Object[]]$ConditionalText, - [Object[]]$Style, - [ScriptBlock]$CellStyleSB, - #If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified - [switch]$Activate, - [Parameter(ParameterSetName = 'Default')] - [Switch]$Now, - [Switch]$ReturnRange, - #By default PivotTables have Totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected. - [ValidateSet("Both","Columns","Rows","None")] - [String]$PivotTotals = "Both", - #Included for compatibility - equivalent to -PivotTotals "None" - [Switch]$NoTotalsInPivot, - [Switch]$ReZip - ) - - begin { - $numberRegex = [Regex]'\d' - $isDataTypeValueType = $false - if ($NoClobber) {Write-Warning -Message "-NoClobber parameter is no longer used" } - #Open the file, get the worksheet, and decide where in the sheet we are writing, and if there is a number format to apply. - try { - $script:Header = $null - if ($Append -and $ClearSheet) {throw "You can't use -Append AND -ClearSheet." ; return} - #To force -Now not to format as a table, allow $false in -TableName to be "No table" - $TableName = if ($null -eq $TableName -or ($TableName -is [bool] -and $false -eq $TableName)) { $null } else {[String]$TableName} - if ($Now -or (-not $Path -and -not $ExcelPackage) ) { - if (-not $PSBoundParameters.ContainsKey("Path")) { $Path = [System.IO.Path]::GetTempFileName() -replace '\.tmp', '.xlsx' } - if (-not $PSBoundParameters.ContainsKey("Show")) { $Show = $true } - if (-not $PSBoundParameters.ContainsKey("AutoSize")) { $AutoSize = $true } - #"Now" option will create a table, unless something passed in TableName/Table Style. False in TableName will block autocreation - if (-not $PSBoundParameters.ContainsKey("TableName") -and - -not $PSBoundParameters.ContainsKey("TableStyle") -and - -not $AutoFilter) { - $TableName = 'Table1' - } - } - if ($ExcelPackage) { - $pkg = $ExcelPackage - $Path = $pkg.File - } - Else { $pkg = Open-ExcelPackage -Path $Path -Create -KillExcel:$KillExcel -Password:$Password} - } - catch {throw "Could not open Excel Package $path"} - try { - $params = @{WorksheetName=$WorksheetName} - foreach ($p in @("ClearSheet", "MoveToStart", "MoveToEnd", "MoveBefore", "MoveAfter", "Activate")) {if ($PSBoundParameters[$p]) {$params[$p] = $PSBoundParameters[$p]}} - $ws = $pkg | Add-WorkSheet @params - if ($ws.Name -ne $WorksheetName) { - Write-Warning -Message "The Worksheet name has been changed from $WorksheetName to $($ws.Name), this may cause errors later." - $WorksheetName = $ws.Name - } - } - catch {throw "Could not get worksheet $worksheetname"} - try { - if ($Append -and $ws.Dimension) { - #if there is a title or anything else above the header row, append needs to be combined wih a suitable startrow parameter - $headerRange = $ws.Dimension.Address -replace "\d+$", $StartRow - #using a slightly odd syntax otherwise header ends up as a 2D array - $ws.Cells[$headerRange].Value | ForEach-Object -Begin {$Script:header = @()} -Process {$Script:header += $_ } - #if we did not get AutoNameRange, but headers have ranges of the same name make autoNameRange True, otherwise make it false - if (-not $AutoNameRange) { - $AutoNameRange = $true ; foreach ($h in $header) {if ($ws.names.name -notcontains $h) {$AutoNameRange = $false} } - } - #if we did not get a Rangename but there is a Range which covers the active part of the sheet, set Rangename to that. - if (-not $RangeName -and $ws.names.where({$_.name[0] -match '[a-z]'})) { - $theRange = $ws.names.where({ - ($_.Name[0] -match '[a-z]' ) -and - ($_.Start.Row -eq $StartRow) -and - ($_.Start.Column -eq $StartColumn) -and - ($_.End.Row -eq $ws.Dimension.End.Row) -and - ($_.End.Column -eq $ws.Dimension.End.column) } , 'First', 1) - if ($theRange) {$rangename = $theRange.name} - } - - #if we did not get a table name but there is a table which covers the active part of the sheet, set table name to that, and don't do anything with autofilter - if ($null -eq $TableName -and $ws.Tables.Where({$_.address.address -eq $ws.dimension.address})) { - $TableName = $ws.Tables.Where({$_.address.address -eq $ws.dimension.address},'First', 1).Name - $AutoFilter = $false - } - #if we did not get $autofilter but a filter range is set and it covers the right area, set autofilter to true - elseif (-not $AutoFilter -and $ws.Names['_xlnm._FilterDatabase']) { - if ( ($ws.Names['_xlnm._FilterDatabase'].Start.Row -eq $StartRow) -and - ($ws.Names['_xlnm._FilterDatabase'].Start.Column -eq $StartColumn) -and - ($ws.Names['_xlnm._FilterDatabase'].End.Row -eq $ws.Dimension.End.Row) -and - ($ws.Names['_xlnm._FilterDatabase'].End.Column -eq $ws.Dimension.End.Column) ) {$AutoFilter = $true} - } - - $row = $ws.Dimension.End.Row - Write-Debug -Message ("Appending: headers are " + ($script:Header -join ", ") + " Start row is $row") - if ($Title) {Write-Warning -Message "-Title Parameter is ignored when appending."} - } - elseif ($Title) { - #Can only add a title if not appending! - $Row = $StartRow - $ws.Cells[$Row, $StartColumn].Value = $Title - $ws.Cells[$Row, $StartColumn].Style.Font.Size = $TitleSize - - if ($PSBoundParameters.ContainsKey("TitleBold")) { - #Set title to Bold face font if -TitleBold was specified. - #Otherwise the default will be unbolded. - $ws.Cells[$Row, $StartColumn].Style.Font.Bold = [boolean]$TitleBold - } - if ($TitleBackgroundColor ) { - if ($TitleBackgroundColor -is [string]) {$TitleBackgroundColor = [System.Drawing.Color]::$TitleBackgroundColor } - $ws.Cells[$Row, $StartColumn].Style.Fill.PatternType = $TitleFillPattern - $ws.Cells[$Row, $StartColumn].Style.Fill.BackgroundColor.SetColor($TitleBackgroundColor) - } - $Row ++ ; $startRow ++ - } - else { $Row = $StartRow } - $ColumnIndex = $StartColumn - $Numberformat = Expand-NumberFormat -NumberFormat $Numberformat - if ((-not $ws.Dimension) -and ($Numberformat -ne $ws.Cells.Style.Numberformat.Format)) { - $ws.Cells.Style.Numberformat.Format = $Numberformat - $setNumformat = $false - } - else { $setNumformat = ($Numberformat -ne $ws.Cells.Style.Numberformat.Format) } - } - catch {throw "Failed preparing to export to worksheet '$WorksheetName' to '$Path': $_"} - #region Special case -inputobject passed a dataTable object - <# If inputObject was passed via the pipeline it won't be visible until the process block, we will only see it here if it was passed as a parameter - if it is a data table don't do foreach on it (slow) - put the whole table in and set dates on date columns, - set things up for the end block, and skip the process block #> - if ($InputObject -is [System.Data.DataTable]) { - #don't leave caller with a renamed table, save the name and set it back later - $orginalTableName = $InputObject.TableName - if ($TableName) { - $InputObject.TableName = $TableName - } - while ($InputObject.TableName -in $pkg.Workbook.Worksheets.Tables.name) { - Write-Warning "Table name $($InputObject.TableName) is not unique, adding '_' to it " - $InputObject.TableName += "_" - } - if ($TableName -or $PSBoundParameters.ContainsKey("TableStyle")) { - $TableName = $null - $null = $ws.Cells[$row,$StartColumn].LoadFromDataTable($InputObject, (-not $noHeader),$TableStyle ) - } - else { - $null = $ws.Cells[$row,$StartColumn].LoadFromDataTable($InputObject, (-not $noHeader) ) - } - $InputObject.TableName = $orginalTableName - foreach ($c in $InputObject.Columns.where({$_.datatype -eq [datetime]})) { - Set-ExcelColumn -Worksheet $ws -Column ($c.Ordinal + $StartColumn) -NumberFormat 'Date-Time' - } - foreach ($c in $InputObject.Columns.where({$_.datatype -eq [timespan]})) { - Set-ExcelColumn -Worksheet $ws -Column ($c.Ordinal + $StartColumn) -NumberFormat '[h]:mm:ss' - } - $ColumnIndex += $InputObject.Columns.Count - 1 - if ($noHeader) {$row += $InputObject.Rows.Count -1 } - else {$row += $InputObject.Rows.Count } - $null = $PSBoundParameters.Remove('InputObject') - $firstTimeThru = $false - } - #endregion - else {$firstTimeThru = $true} - } - - process { if ($PSBoundParameters.ContainsKey("InputObject")) { - try { - if ($null -eq $InputObject) {$row += 1} - foreach ($TargetData in $InputObject) { - if ($firstTimeThru) { - $firstTimeThru = $false - $isDataTypeValueType = ($null -eq $TargetData) -or ($TargetData.GetType().name -match 'string|timespan|datetime|bool|byte|char|decimal|double|float|int|long|sbyte|short|uint|ulong|ushort|URI|ExcelHyperLink') - if ($isDataTypeValueType ) { - $script:Header = @(".") # dummy value to make sure we go through the "for each name in $header" - if (-not $Append) {$row -= 1} # By default row will be 1, it is incremented before inserting values (so it ends pointing at final row.); si first data row is 2 - move back up 1 if there is no header . - } - if ($null -ne $TargetData) {Write-Debug "DataTypeName is '$($TargetData.GetType().name)' isDataTypeValueType '$isDataTypeValueType'" } - } - #region Add headers - if we are appending, or we have been through here once already we will have the headers - if (-not $script:Header) { - if ($DisplayPropertySet -and $TargetData.psStandardmembers.DefaultDisplayPropertySet.ReferencedPropertyNames) { - $script:Header = $TargetData.psStandardmembers.DefaultDisplayPropertySet.ReferencedPropertyNames.Where( {$_ -notin $ExcludeProperty}) - } - else { - if ($NoAliasOrScriptPropeties) {$propType = "Property"} else {$propType = "*"} - $script:Header = $TargetData.PSObject.Properties.where( {$_.MemberType -like $propType}).Name - } - foreach ($exclusion in $ExcludeProperty) {$script:Header = $script:Header -notlike $exclusion} - if ($NoHeader) { - # Don't push the headers to the spreadsheet - $Row -= 1 - } - else { - $ColumnIndex = $StartColumn - foreach ($Name in $script:Header) { - $ws.Cells[$Row, $ColumnIndex].Value = $Name - Write-Verbose "Cell '$Row`:$ColumnIndex' add header '$Name'" - $ColumnIndex += 1 - } - } - } - #endregion - #region Add non header values - $Row += 1 - $ColumnIndex = $StartColumn - <# - For each item in the header OR for the Data item if this is a simple Type or data table : - If it is a date insert with one of Excel's built in formats - recognized as "Date and time to be localized" - if it is a timespan insert with a built in format for elapsed hours, minutes and seconds - if its any other numeric insert as is , setting format if need be. - Preserve URI, Insert a data table, convert non string objects to string. - For strings, check for fomula, URI or Number, before inserting as a string (ignore nulls) #> - foreach ($Name in $script:Header) { - if ($isDataTypeValueType) {$v = $TargetData} - else {$v = $TargetData.$Name} - try { - if ($v -is [DateTime]) { - $ws.Cells[$Row, $ColumnIndex].Value = $v - $ws.Cells[$Row, $ColumnIndex].Style.Numberformat.Format = 'm/d/yy h:mm' # This is not a custom format, but a preset recognized as date and localized. - } - elseif ($v -is [TimeSpan]) { - $ws.Cells[$Row, $ColumnIndex].Value = $v - $ws.Cells[$Row, $ColumnIndex].Style.Numberformat.Format = '[h]:mm:ss' - } - elseif ($v -is [System.ValueType]) { - $ws.Cells[$Row, $ColumnIndex].Value = $v - if ($setNumformat) {$ws.Cells[$Row, $ColumnIndex].Style.Numberformat.Format = $Numberformat } - } - elseif ($v -is [uri] ) { - $ws.Cells[$Row, $ColumnIndex].HyperLink = $v - $ws.Cells[$Row, $ColumnIndex].Style.Font.Color.SetColor([System.Drawing.Color]::Blue) - $ws.Cells[$Row, $ColumnIndex].Style.Font.UnderLine = $true - } - elseif ($v -isnot [String] ) { #Other objects or null. - if ($null -ne $v) { $ws.Cells[$Row, $ColumnIndex].Value = $v.toString()} - } - elseif ($v[0] -eq '=') { - $ws.Cells[$Row, $ColumnIndex].Formula = ($v -replace '^=','') - if ($setNumformat) {$ws.Cells[$Row, $ColumnIndex].Style.Numberformat.Format = $Numberformat } - } - elseif ( [System.Uri]::IsWellFormedUriString($v , [System.UriKind]::Absolute) ) { - if ($v -match "^xl://internal/") { - $referenceAddress = $v -replace "^xl://internal/" , "" - $display = $referenceAddress -replace "!A1$" , "" - $h = New-Object -TypeName OfficeOpenXml.ExcelHyperLink -ArgumentList $referenceAddress , $display - $ws.Cells[$Row, $ColumnIndex].HyperLink = $h - } - else {$ws.Cells[$Row, $ColumnIndex].HyperLink = $v } #$ws.Cells[$Row, $ColumnIndex].Value = $v.AbsoluteUri - $ws.Cells[$Row, $ColumnIndex].Style.Font.Color.SetColor([System.Drawing.Color]::Blue) - $ws.Cells[$Row, $ColumnIndex].Style.Font.UnderLine = $true - } - else { - $number = $null - if ( $numberRegex.IsMatch($v) -and # if it contains digit(s) - this syntax is quicker than -match for many items and cuts out slow checks for non numbers - $NoNumberConversion -ne '*' -and # and NoNumberConversion isn't specified - $NoNumberConversion -notcontains $Name -and - [Double]::TryParse($v, [System.Globalization.NumberStyles]::Any, [System.Globalization.NumberFormatInfo]::CurrentInfo, [Ref]$number) - ) { - $ws.Cells[$Row, $ColumnIndex].Value = $number - if ($setNumformat) {$ws.Cells[$Row, $ColumnIndex].Style.Numberformat.Format = $Numberformat } - } - else { - $ws.Cells[$Row, $ColumnIndex].Value = $v - } - - } - } - catch {Write-Warning -Message "Could not insert the '$Name' property at Row $Row, Column $ColumnIndex"} - $ColumnIndex += 1 - } - $ColumnIndex -= 1 # column index will be the last column whether isDataTypeValueType was true or false - #endregion - } - } - catch {throw "Failed exporting data to worksheet '$WorksheetName' to '$Path': $_" } - - }} - - end { - if ($firstTimeThru -and $ws.Dimension) { - $LastRow = $ws.Dimension.End.Row - $LastCol = $ws.Dimension.End.Column - $endAddress = $ws.Dimension.End.Address - } - else { - $LastRow = $Row - $LastCol = $ColumnIndex - $endAddress = [OfficeOpenXml.ExcelAddress]::GetAddress($LastRow , $LastCol) - } - $startAddress = [OfficeOpenXml.ExcelAddress]::GetAddress($StartRow, $StartColumn) - $dataRange = "{0}:{1}" -f $startAddress, $endAddress - - Write-Debug "Data Range '$dataRange'" - if ($AutoNameRange) { - try { - if (-not $script:header) { - # if there aren't any headers, use the the first row of data to name the ranges: this is the last point that headers will be used. - $headerRange = $ws.Dimension.Address -replace "\d+$", $StartRow - #using a slightly odd syntax otherwise header ends up as a 2D array - $ws.Cells[$headerRange].Value | ForEach-Object -Begin {$Script:header = @()} -Process {$Script:header += $_ } - if ($PSBoundParameters.ContainsKey($TargetData)) { #if Export was called with data that writes no header start the range at $startRow ($startRow is data) - $targetRow = $StartRow - } - else { $targetRow = $StartRow + 1 } #if Export was called without data to add names (assume $startRow is a header) or... - } # ... called with data that writes a header, then start the range at $startRow + 1 - else { $targetRow = $StartRow + 1 } - - #Dimension.start.row always seems to be one so we work out the target row - #, but start.column is the first populated one and .Columns is the count of populated ones. - # if we have 5 columns from 3 to 8, headers are numbered 0..4, so that is in the for loop and used for getting the name... - # but we have to add the start column on when referencing positions - foreach ($c in 0..($LastCol - $StartColumn)) { - $targetRangeName = @($script:Header)[$c] #Let Add-ExcelName fix (and warn about) bad names - Add-ExcelName -RangeName $targetRangeName -Range $ws.Cells[$targetRow, ($StartColumn + $c ), $LastRow, ($StartColumn + $c )] - try {#this test can throw with some names, surpress any error - if ([OfficeOpenXml.FormulaParsing.ExcelUtilities.ExcelAddressUtil]::IsValidAddress(($targetRangeName -replace '\W' , '_' ))) { - Write-Warning -Message "AutoNameRange: Property name '$targetRangeName' is also a valid Excel address and may cause issues. Consider renaming the property." - } - } - Catch { - Write-Warning -Message "AutoNameRange: Testing '$targetRangeName' caused an error. This should be harmless, but a change of property name may be needed.." - } - } - } - catch {Write-Warning -Message "Failed adding named ranges to worksheet '$WorksheetName': $_" } - } - #Empty string is not allowed as a name for ranges or tables. - if ($RangeName) { Add-ExcelName -Range $ws.Cells[$dataRange] -RangeName $RangeName} - - #Allow table to be inserted by specifying Name, or Style or both; only process autoFilter if there is no table (they clash). - if ($null -ne $TableName) { - Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $PSBoundParameters['TableName'] -TableStyle $TableStyle - } - elseif ($PSBoundParameters.ContainsKey('TableStyle')) { - Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName "" -TableStyle $TableStyle - } - elseif ($AutoFilter) { - try { - $ws.Cells[$dataRange].AutoFilter = $true - Write-Verbose -Message "Enabled autofilter. " - } - catch {Write-Warning -Message "Failed adding autofilter to worksheet '$WorksheetName': $_"} - } - - if ($PivotTableDefinition) { - foreach ($item in $PivotTableDefinition.GetEnumerator()) { - $params = $item.value - if ($Activate) {$params.Activate = $true } - if ($params.keys -notcontains 'SourceRange' -and - ($params.Keys -notcontains 'SourceWorkSheet' -or $params.SourceWorkSheet -eq $WorksheetName)) {$params.SourceRange = $dataRange} - if ($params.Keys -notcontains 'SourceWorkSheet') {$params.SourceWorkSheet = $ws } - if ($params.Keys -notcontains 'NoTotalsInPivot' -and $NoTotalsInPivot ) {$params.PivotTotals = 'None'} - if ($params.Keys -notcontains 'PivotTotals' -and $PivotTotals ) {$params.PivotTotals = $PivotTotals} - if ($params.Keys -notcontains 'PivotDataToColumn' -and $PivotDataToColumn) {$params.PivotDataToColumn = $true} - - Add-PivotTable -ExcelPackage $pkg -PivotTableName $item.key @Params - } - } - if ($IncludePivotTable -or $IncludePivotChart) { - $params = @{ - 'SourceRange' = $dataRange - } - if ($PivotTableName -and ($pkg.workbook.worksheets.tables.name -contains $PivotTableName)) { - Write-Warning -Message "The selected PivotTable name '$PivotTableName' is already used as a table name. Adding a suffix of 'Pivot'." - $PivotTableName += 'Pivot' - } - - if ($PivotTableName) {$params.PivotTableName = $PivotTableName} - else {$params.PivotTableName = $WorksheetName + 'PivotTable'} - if ($Activate) {$params.Activate = $true } - if ($PivotFilter) {$params.PivotFilter = $PivotFilter} - if ($PivotRows) {$params.PivotRows = $PivotRows} - if ($PivotColumns) {$Params.PivotColumns = $PivotColumns} - if ($PivotData) {$Params.PivotData = $PivotData} - if ($NoTotalsInPivot) {$params.PivotTotals = "None" } - Elseif ($PivotTotals) {$params.PivotTotals = $PivotTotals} - if ($PivotDataToColumn) {$params.PivotDataToColumn = $true} - if ($IncludePivotChart) { - $params.IncludePivotChart = $true - $Params.ChartType = $ChartType - if ($ShowCategory) {$params.ShowCategory = $true} - if ($ShowPercent) {$params.ShowPercent = $true} - if ($NoLegend) {$params.NoLegend = $true} - } - Add-PivotTable -ExcelPackage $pkg -SourceWorkSheet $ws @params - } - - try { - #Allow single switch or two seperate ones. - if ($FreezeTopRowFirstColumn -or ($FreezeTopRow -and $FreezeFirstColumn)) { - $ws.View.FreezePanes(2, 2) - Write-Verbose -Message "Froze top row and first column" - } - elseif ($FreezeTopRow) { - $ws.View.FreezePanes(2, 1) - Write-Verbose -Message "Froze top row" - } - elseif ($FreezeFirstColumn) { - $ws.View.FreezePanes(1, 2) - Write-Verbose -Message "Froze first column" - } - #Must be 1..maxrows or and array of 1..maxRows,1..MaxCols - if ($FreezePane) { - $freezeRow, $freezeColumn = $FreezePane - if (-not $freezeColumn -or $freezeColumn -eq 0) { - $freezeColumn = 1 - } - - if ($freezeRow -ge 1) { - $ws.View.FreezePanes($freezeRow, $freezeColumn) - Write-Verbose -Message "Froze panes at row $freezeRow and column $FreezeColumn" - } - } - } - catch {Write-Warning -Message "Failed adding Freezing the panes in worksheet '$WorksheetName': $_"} - - if ($PSBoundParameters.ContainsKey("BoldTopRow")) { #it sets bold as far as there are populated cells: for whole row could do $ws.row($x).style.font.bold = $true - try { - if ($Title) { - $range = $ws.Dimension.Address -replace '\d+', ($StartRow + 1) - } - else { - $range = $ws.Dimension.Address -replace '\d+', $StartRow - } - $ws.Cells[$range].Style.Font.Bold = [boolean]$BoldTopRow - Write-Verbose -Message "Set $range font style to bold." - } - catch {Write-Warning -Message "Failed setting the top row to bold in worksheet '$WorksheetName': $_"} - } - if ($AutoSize -and -not $env:NoAutoSize) { - try { - #Don't fit the all the columns in the sheet; if we are adding cells beside things with hidden columns, that unhides them - if ($MaxAutoSizeRows -and $MaxAutoSizeRows -lt $LastRow ) { - $AutosizeRange = [OfficeOpenXml.ExcelAddress]::GetAddress($startRow,$StartColumn, $MaxAutoSizeRows , $LastCol) - $ws.Cells[$AutosizeRange].AutoFitColumns() - } - else {$ws.Cells[$dataRange].AutoFitColumns() } - Write-Verbose -Message "Auto-sized columns" - } - catch { Write-Warning -Message "Failed autosizing columns of worksheet '$WorksheetName': $_"} - } - elseif ($AutoSize) {Write-Warning -Message "Auto-fitting columns is not available with this OS configuration." } - - foreach ($Sheet in $HideSheet) { - try { - $pkg.Workbook.WorkSheets.Where({$_.Name -like $sheet}) | ForEach-Object { - $_.Hidden = 'Hidden' - Write-verbose -Message "Sheet '$($_.Name)' Hidden." - } - } - catch {Write-Warning -Message "Failed hiding worksheet '$sheet': $_"} - } - foreach ($Sheet in $UnHideSheet) { - try { - $pkg.Workbook.WorkSheets.Where({$_.Name -like $sheet}) | ForEach-Object { - $_.Hidden = 'Visible' - Write-verbose -Message "Sheet '$($_.Name)' shown" - } - } - catch {Write-Warning -Message "Failed showing worksheet '$sheet': $_"} - } - if (-not $pkg.Workbook.Worksheets.Where({$_.Hidden -eq 'visible'})) { - Write-Verbose -Message "No Sheets were left visible, making $WorksheetName visible" - $ws.Hidden = 'Visible' - } - - foreach ($chartDef in $ExcelChartDefinition) { - if ($chartDef -is [System.Management.Automation.PSCustomObject]) { - $params = @{} - $chartDef.PSObject.Properties | ForEach-Object {if ( $null -ne $_.value) {$params[$_.name] = $_.value}} - Add-ExcelChart -Worksheet $ws @params - } - elseif ($chartDef -is [hashtable] -or $chartDef -is[System.Collections.Specialized.OrderedDictionary]) { - Add-ExcelChart -Worksheet $ws @chartDef - } - } - - if ($Calculate) { - try { [OfficeOpenXml.CalculationExtension]::Calculate($ws) } - catch { Write-Warning "One or more errors occured while calculating, save will continue, but there may be errors in the workbook. $_"} - } - - if ($Barchart -or $PieChart -or $LineChart -or $ColumnChart) { - if ($NoHeader) {$FirstDataRow = $startRow} - else {$FirstDataRow = $startRow + 1 } - $range = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, $startColumn, $FirstDataRow, $lastCol ) - $xCol = $ws.cells[$range] | Where-Object {$_.value -is [string] } | ForEach-Object {$_.start.column} | Sort-Object | Select-Object -first 1 - if (-not $xcol) { - $xcol = $StartColumn - $range = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, ($startColumn +1), $FirstDataRow, $lastCol ) - } - $yCol = $ws.cells[$range] | Where-Object {$_.value -is [valueType] -or $_.Formula } | ForEach-Object {$_.start.column} | Sort-Object | Select-Object -first 1 - if (-not ($xCol -and $ycol)) { Write-Warning -Message "Can't identify a string column and a number column to use as chart labels and data. "} - else { - $params = @{ - XRange = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, $xcol , $lastrow, $xcol) - YRange = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, $ycol , $lastrow, $ycol) - Title = '' - Column = ($lastCol +1) - Width = 800 - } - if ($ShowPercent) {$params["ShowPercent"] = $true} - if ($ShowCategory) {$params["ShowCategory"] = $true} - if ($NoLegend) {$params["NoLegend"] = $true} - if (-not $NoHeader) {$params["SeriesHeader"] = $ws.Cells[$startRow, $YCol].Value} - if ($ColumnChart) {$Params["chartType"] = "ColumnStacked" } - elseif ($Barchart) {$Params["chartType"] = "BarStacked" } - elseif ($PieChart) {$Params["chartType"] = "PieExploded3D" } - elseif ($LineChart) {$Params["chartType"] = "Line" } - - Add-ExcelChart -Worksheet $ws @params - } - } - - # It now doesn't matter if the conditional formating rules are passed in $conditionalText or $conditional format. - # Just one with an alias for compatiblity it will break things for people who are using both at once - foreach ($c in (@() + $ConditionalText + $ConditionalFormat) ) { - try { - #we can take an object with a .ConditionalType property made by New-ConditionalText or with a .Formatter Property made by New-ConditionalFormattingIconSet or a hash table - if ($c.ConditionalType) { - $cfParams = @{RuleType = $c.ConditionalType; ConditionValue = $c.Text ; - BackgroundColor = $c.BackgroundColor; BackgroundPattern = $c.PatternType ; - ForeGroundColor = $c.ConditionalTextColor} - if ($c.Range) {$cfParams.Range = $c.Range} - else {$cfParams.Range = $ws.Dimension.Address } - Add-ConditionalFormatting -WorkSheet $ws @cfParams - Write-Verbose -Message "Added conditional formatting to range $($c.range)" - } - elseif ($c.formatter) { - switch ($c.formatter) { - "ThreeIconSet" {Add-ConditionalFormatting -WorkSheet $ws -ThreeIconsSet $c.IconType -range $c.range -reverse:$c.reverse } - "FourIconSet" {Add-ConditionalFormatting -WorkSheet $ws -FourIconsSet $c.IconType -range $c.range -reverse:$c.reverse } - "FiveIconSet" {Add-ConditionalFormatting -WorkSheet $ws -FiveIconsSet $c.IconType -range $c.range -reverse:$c.reverse } - } - Write-Verbose -Message "Added conditional formatting to range $($c.range)" - } - elseif ($c -is [hashtable] -or $c -is[System.Collections.Specialized.OrderedDictionary]) { - if (-not $c.Range -or $c.Address) {$c.Address = $ws.Dimension.Address } - Add-ConditionalFormatting -WorkSheet $ws @c - } - } - catch {throw "Error applying conditional formatting to worksheet $_"} - } - foreach ($s in $Style) { - if (-not $s.Range) {$s["Range"] = $ws.Dimension.Address } - Set-ExcelRange -WorkSheet $ws @s - } - if ($CellStyleSB) { - try { - $TotalRows = $ws.Dimension.Rows - $LastColumn = $ws.Dimension.Address -replace "^.*:(\w*)\d+$" , '$1' - & $CellStyleSB $ws $TotalRows $LastColumn - } - catch {Write-Warning -Message "Failed processing CellStyleSB in worksheet '$WorksheetName': $_"} - } - - #Can only add password, may want to support -password $Null removing password. - if ($Password) { - try { - $ws.Protection.SetPassword($Password) - Write-Verbose -Message 'Set password on workbook' - } - - catch {throw "Failed setting password for worksheet '$WorksheetName': $_"} - } - - if ($PassThru) { $pkg } - else { - if ($ReturnRange) {$dataRange } - - if ($Password) { $pkg.Save($Password) } - else { $pkg.Save() } - Write-Verbose -Message "Saved workbook $($pkg.File)" - if ($ReZip) { - Write-Verbose -Message "Re-Zipping $($pkg.file) using .NET ZIP library" - try { - Add-Type -AssemblyName 'System.IO.Compression.Filesystem' -ErrorAction stop - } - catch { - Write-Error "The -ReZip parameter requires .NET Framework 4.5 or later to be installed. Recommend to install Powershell v4+" - continue - } - try { - $TempZipPath = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath ([System.IO.Path]::GetRandomFileName()) - $null = [io.compression.zipfile]::ExtractToDirectory($pkg.File, $TempZipPath) - Remove-Item $pkg.File -Force - $null = [io.compression.zipfile]::CreateFromDirectory($TempZipPath, $pkg.File) - } - catch {throw "Error resizipping $path : $_"} - } - - $pkg.Dispose() - - if ($Show) { Invoke-Item $Path } - } - - } -} - -function Add-WorkSheet { - <# - .Synopsis - Adds a worksheet to an existing workbook. - .Description - If the named worksheet already exists, the -Clearsheet parameter decides whether it should be deleted and a new one returned, - or if not specified the existing sheet will be returned. By default the sheet is created at the end of the work book, the - -MoveXXXX switches allow the sheet to be [re]positioned at the start or before or after another sheet. A new sheet will only be - made the default sheet when excel opens if -Activate is specified. - .Example - $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 - $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 - $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. - #> - [cmdletBinding()] - [OutputType([OfficeOpenXml.ExcelWorksheet])] - 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 whichever fits at the time. - [Parameter(Mandatory = $true, ParameterSetName = "WorkBook")] - [OfficeOpenXml.ExcelWorkbook]$ExcelWorkbook, - #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, - #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. - [Switch]$MoveToStart, - #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 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 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. - [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, - #Ignored but retained for backwards compatibility. - [Switch] $NoClobber - ) - #if we were given a workbook use it, if we were given a package, use its workbook - if ($ExcelPackage -and -not $ExcelWorkbook) {$ExcelWorkbook = $ExcelPackage.Workbook} - - # If WorksheetName was given, try to use that worksheet. If it wasn't, and we are copying an existing sheet, try to use the sheet name - # If we are not copying a sheet, and have no name, use the name "SheetX" where X is the number of the new sheet - if (-not $WorksheetName -and $CopySource -and -not $ExcelWorkbook[$CopySource.Name]) {$WorksheetName = $CopySource.Name} - elseif (-not $WorksheetName) {$WorksheetName = "Sheet" + (1 + $ExcelWorkbook.Worksheets.Count)} - else {$ws = $ExcelWorkbook.Worksheets[$WorksheetName]} - - #If -clearsheet was specified and the named sheet exists, delete it - if ($ws -and $ClearSheet) { $ExcelWorkbook.Worksheets.Delete($WorksheetName) ; $ws = $null } - - #Copy or create new sheet as needed - if (-not $ws -and $CopySource) { - Write-Verbose -Message "Copying into worksheet '$WorksheetName'." - $ws = $ExcelWorkbook.Worksheets.Add($WorksheetName, $CopySource) - } - elseif (-not $ws) { - $ws = $ExcelWorkbook.Worksheets.Add($WorksheetName) - Write-Verbose -Message "Adding worksheet '$WorksheetName'." - } - else {Write-Verbose -Message "Worksheet '$WorksheetName' already existed."} - #region Move sheet if needed - if ($MoveToStart) {$ExcelWorkbook.Worksheets.MoveToStart($WorksheetName) } - elseif ($MoveToEnd ) {$ExcelWorkbook.Worksheets.MoveToEnd($WorksheetName) } - elseif ($MoveBefore ) { - if ($ExcelWorkbook.Worksheets[$MoveBefore]) { - if ($MoveBefore -is [int]) { - $ExcelWorkbook.Worksheets.MoveBefore($ws.Index, $MoveBefore) - } - else {$ExcelWorkbook.Worksheets.MoveBefore($WorksheetName, $MoveBefore)} - } - else {Write-Warning "Can't find worksheet '$MoveBefore'; worsheet '$WorksheetName' will not be moved."} - } - elseif ($MoveAfter ) { - if ($MoveAfter -eq "*") { - if ($WorksheetName -lt $ExcelWorkbook.Worksheets[1].Name) {$ExcelWorkbook.Worksheets.MoveToStart($WorksheetName)} - else { - $i = 1 - While ($i -lt $ExcelWorkbook.Worksheets.Count -and ($ExcelWorkbook.Worksheets[$i + 1].Name -le $WorksheetName) ) { $i++} - $ExcelWorkbook.Worksheets.MoveAfter($ws.Index, $i) - } - } - elseif ($ExcelWorkbook.Worksheets[$MoveAfter]) { - if ($MoveAfter -is [int]) { - $ExcelWorkbook.Worksheets.MoveAfter($ws.Index, $MoveAfter) - } - else { - $ExcelWorkbook.Worksheets.MoveAfter($WorksheetName, $MoveAfter) - } - } - else {Write-Warning "Can't find worksheet '$MoveAfter'; worsheet '$WorksheetName' will not be moved."} - } - #endregion - if ($Activate) {Select-Worksheet -ExcelWorksheet $ws } - if ($ExcelPackage -and -not (Get-Member -InputObject $ExcelPackage -Name $ws.Name)) { - $sb = [scriptblock]::Create(('$this.workbook.Worksheets["{0}"]' -f $ws.name)) - Add-Member -InputObject $ExcelPackage -MemberType ScriptProperty -Name $ws.name -Value $sb - } - return $ws -} - -function Select-Worksheet { - <# - .SYNOPSIS - 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 which sheet is the selected tab when Excel opens the file. - .EXAMPLE - Select-Worksheet -ExcelWorkbook $ExcelWorkbook -WorksheetName "NewSheet" - $ExcelWorkbook holds a workbook object containing a sheet named "NewSheet"; - 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. - .EXAMPLE - Select-Worksheet -ExcelWorksheet $ws - $ws holds an Excel worksheet which will become the [only] active sheet - in its workbook. - #> - param ( - #An object representing an ExcelPackage. - [Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Package', Position = 0)] - [OfficeOpenXml.ExcelPackage]$ExcelPackage, - #An Excel workbook to which the Worksheet will be added - a package contains one Workbook so you can use workbook or package as it suits. - [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. - [Parameter(ParameterSetName='Sheet',Mandatory=$true)] - [OfficeOpenXml.ExcelWorksheet]$ExcelWorksheet - ) - #if we were given a package, use its workbook - if ($ExcelPackage -and -not $ExcelWorkbook) {$ExcelWorkbook = $ExcelPackage.Workbook} - #if we now have workbook, get the worksheet; if we were given a sheet get the workbook - if ($ExcelWorkbook -and $WorksheetName) {$ExcelWorksheet = $ExcelWorkbook.Worksheets[$WorksheetName]} - elseif ($ExcelWorksheet -and -not $ExcelWorkbook) {$ExcelWorkbook = $ExcelWorksheet.Workbook ; } - #if we didn't get to a worksheet give up. If we did set all works sheets to not selected and then the one we want to selected. - if (-not $ExcelWorksheet) {Write-Warning -Message "The worksheet $WorksheetName was not found." ; return } - else { - foreach ($w in $ExcelWorkbook.Worksheets) {$w.View.TabSelected = $false} - $ExcelWorksheet.View.TabSelected = $true - } -} - -function Add-ExcelName { - <# - .SYNOPSIS - 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 - Add-ExcelName -Range $ws.Cells[$dataRange] -RangeName $rangeName - $WS is a worksheet, and $dataRange is a string describing a range of cells - e.g. "A1:Z10" - which will become a named range, using the name in $rangeName. - #> - [CmdletBinding()] - param( - #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. - [String]$RangeName - ) - try { - $ws = $Range.Worksheet - if (-not $RangeName) { - $RangeName = $ws.Cells[$Range.Start.Address].Value - $Range = ($Range.Worksheet.cells[($range.start.row +1), $range.start.Column , $range.end.row, $range.end.column]) - } - if ($RangeName -match '\W') { - Write-Warning -Message "Range name '$RangeName' contains illegal characters, they will be replaced with '_'." - $RangeName = $RangeName -replace '\W','_' - } - if ($ws.names[$RangeName]) { - Write-verbose -Message "Updating Named range '$RangeName' to $($Range.FullAddressAbsolute)." - $ws.Names[$RangeName].Address = $Range.FullAddressAbsolute - } - else { - Write-verbose -Message "Creating Named range '$RangeName' as $($Range.FullAddressAbsolute)." - $null = $ws.Names.Add($RangeName, $Range) - } - } - catch {Write-Warning -Message "Failed adding named range '$RangeName' to worksheet '$($ws.Name)': $_" } -} - -function Add-ExcelTable { - <# - .SYNOPSIS - Adds Tables to Excel workbooks. - .DESCRIPTION - Unlike named ranges, where the name only needs to be unique within a sheet, Table names must be unique in the workbook - Tables carry formatting by default have a filter. The filter, header, Totals, first and last column highlights - .EXAMPLE - Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $TableName - - $WS is a worksheet, and $dataRange is a string describing a range of cells - e.g. "A1:Z10" - this range which will become a table, named $TableName - .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, 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. - [Parameter(Mandatory=$true)] - [OfficeOpenXml.ExcelRange]$Range, - #The name for the Table - this should be unqiue in the Workbook - auto generated names will be used if this is left empty. - [String]$TableName = "", - #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. - [Switch]$ShowHeader , - #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, - #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. - [Switch]$ShowFirstColumn, - #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 changes to be made. - [Switch]$PassThru - ) - try { - if ($TableName -eq "" -or $null -eq $TableName) { - $tbl = $Range.Worksheet.Tables.Add($Range, "") - } - else { - if ([OfficeOpenXml.FormulaParsing.ExcelUtilities.ExcelAddressUtil]::IsValidAddress($TableName)) { - Write-Warning -Message "$TableName reads as an Excel address, and so is not allowed as a table name." - return - } - if ($TableName -notMatch '^[A-Z]') { - Write-Warning -Message "$TableName is not allowed as a table name because it does not begin with a letter." - return - } - if ($TableName -match "\W") { - Write-Warning -Message "At least one character in $TableName is illegal in a table name and will be replaced with '_' . " - $TableName = $TableName -replace '\W', '_' - } - $ws = $Range.Worksheet - #if the table exists in this worksheet, update it. - if ($ws.Tables[$TableName]) { - $tbl =$ws.Tables[$TableName] - $tbl.TableXml.table.ref = $Range.Address - Write-Verbose -Message "Re-defined table '$TableName', now at $($Range.Address)." - } - elseif ($ws.Workbook.Worksheets.Tables.Name -contains $TableName) { - Write-Warning -Message "The Table name '$TableName' is already used on a different worksheet." - return - } - else { - $tbl = $ws.Tables.Add($Range, $TableName) - Write-Verbose -Message "Defined table '$($tbl.Name)' at $($Range.Address)" - } - } - #it seems that show total changes some of the others, so the sequence matters. - if ($PSBoundParameters.ContainsKey('ShowHeader')) {$tbl.ShowHeader = [bool]$ShowHeader} - if ($PSBoundParameters.ContainsKey('TotalSettings')) { - $tbl.ShowTotal = $true - foreach ($k in $TotalSettings.keys) { - if (-not $tbl.Columns[$k]) {Write-Warning -Message "Table does not have a Column '$k'."} - elseif ($TotalSettings[$k] -notin @("Average", "Count", "CountNums", "Max", "Min", "None", "StdDev", "Sum", "Var") ) { - Write-Warning -Message "'$($TotalSettings[$k])' is not a valid total function." - } - else {$tbl.Columns[$k].TotalsRowFunction = $TotalSettings[$k]} - } - } - elseif ($PSBoundParameters.ContainsKey('ShowTotal')) {$tbl.ShowTotal = [bool]$ShowTotal} - if ($PSBoundParameters.ContainsKey('ShowFilter')) {$tbl.ShowFilter = [bool]$ShowFilter} - if ($PSBoundParameters.ContainsKey('ShowFirstColumn')) {$tbl.ShowFirstColumn = [bool]$ShowFirstColumn} - if ($PSBoundParameters.ContainsKey('ShowLastColumn')) {$tbl.ShowLastColumn = [bool]$ShowLastColumn} - if ($PSBoundParameters.ContainsKey('ShowRowStripes')) {$tbl.ShowRowStripes = [bool]$ShowRowStripes} - if ($PSBoundParameters.ContainsKey('ShowColumnStripes')) {$tbl.ShowColumnStripes = [bool]$ShowColumnStripes} - $tbl.TableStyle = $TableStyle - - if ($PassThru) {return $tbl} - } - catch {Write-Warning -Message "Failed adding table '$TableName' to worksheet '$WorksheetName': $_"} -} diff --git a/AddConditionalFormatting.ps1 b/ExportedCommands/Add-ConditionalFormatting.ps1 similarity index 58% rename from AddConditionalFormatting.ps1 rename to ExportedCommands/Add-ConditionalFormatting.ps1 index d1f3d71..cf204b8 100644 --- a/AddConditionalFormatting.ps1 +++ b/ExportedCommands/Add-ConditionalFormatting.ps1 @@ -1,172 +1,51 @@ -try { - #ensure that color and font lookups are available - [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") -} -catch {} -Function Add-ConditionalFormatting { - <# - .Synopsis - Adds conditional formatting to all or part of a worksheet. - .Description - Conditional formatting allows Excel to: - * Mark cells with icons depending on their value - * Show a databar whose length indicates the value or a two or three color scale where the color indicates the relative value - * Change the color, font, or number format of cells which meet given criteria - Add-ConditionalFormatting allows these parameters to be set; for fine tuning of - the rules, the -PassThru switch will return the rule so that you can modify - things which are specific to that type of rule, example, the values which - correspond to each icon in an Icon-Set. - .Example - > - $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 - > - $r = Add-ConditionalFormatting -WorkSheet $excel.Workbook.Worksheets[1] -Range "B1:B100" -ThreeIconsSet Flags -Passthru - $r.Reverse = $true ; $r.Icon1.Type = "Num"; $r.Icon2.Type = "Num" ; $r.Icon2.value = 100 ; $r.Icon3.type = "Num" ;$r.Icon3.value = 1000 - - Again Export-Excel has been called with -PassThru leaving a package object - in $Excel. This time B1:B100 has been conditionally formatted with 3 icons, - using the "Flags" Icon-Set. Add-ConditionalFormatting does not provide access - to every option in the formatting rule, so -PassThru has been used and the - rule is modified to apply the flags in reverse order, and transitions - between flags are set to 100 and 1000. - .Example - 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 - 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 - > - $excel = Get-ChildItem | Select-Object -Property Name,Length,LastWriteTime,CreationTime | Export-Excel "$env:temp\test43.xlsx" -PassThru -AutoSize - $ws = $excel.Workbook.Worksheets["Sheet1"] - $ws.Cells["E1"].Value = "SavedAt" - $ws.Cells["F1"].Value = [datetime]::Now - $ws.Cells["F1"].Style.Numberformat.Format = (Expand-NumberFormat -NumberFormat 'Date-Time') - $lastRow = $ws.Dimension.End.Row - - Add-ConditionalFormatting -WorkSheet $ws -address "A2:A$Lastrow" -RuleType LessThan -ConditionValue "A" -ForeGroundColor Gray - Add-ConditionalFormatting -WorkSheet $ws -address "B2:B$Lastrow" -RuleType GreaterThan -ConditionValue 1000000 -NumberFormat '#,###,,.00"M"' - Add-ConditionalFormatting -WorkSheet $ws -address "C2:C$Lastrow" -RuleType GreaterThan -ConditionValue "=INT($F$1-7)" -ForeGroundColor Green -StopIfTrue - Add-ConditionalFormatting -WorkSheet $ws -address "D2:D$Lastrow" -RuleType Equal -ConditionValue "=C2" -ForeGroundColor Blue -StopIfTrue - - Close-ExcelPackage -Show $excel - - The first few lines of code export a list of file and directory names, sizes - and dates to a spreadsheet. It puts the date of the export in cell F1. - The first Conditional format changes the color of files and folders that begin - with a ".", "_" or anything else which sorts before "A". - The second Conditional format changes the Number format of numbers bigger than - 1 million, for example 1,234,567,890 will dispay as "1,234.57M" - The third highlights datestamps of files less than a week old when the export - was run; the = is necessary in the condition value otherwise the rule will - look for the the text INT($F$1-7), and the cell address for the date is fixed - using the standard Excel $ notation. - The final Conditional format looks for files which have not changed since they - were created. Here the condition value is "=C2". The = sign means C2 is treated - as a formula, not literal text. Unlike the file age, we want the cell used to - change for each cell where the conditional format applies. The first cell in - the conditional format range is D2, which is compared against C2, then D3 is - compared against C3 and so on. A common mistake is to include the title row in - the range and accidentally apply conditional formatting to it, or to begin the - range at row 2 but use row 1 as the starting point for comparisons. - .Example - Add-ConditionalFormatting $ws.Cells["B:B"] GreaterThan 10000000 -Fore Red -Stop -Pri 1 - - This version shows the shortest syntax - the Address, Ruletype, and - Conditionvalue can be identified from their position, and ForegroundColor, - StopIfTrue and Priority can all be shortend. - - #> +Function Add-ConditionalFormatting { Param ( - #A block of cells to format - you can use a named range with -Address $ws.names[1] or $ws.cells["RangeName"] [Parameter(Mandatory = $true, Position = 0)] [Alias("Range")] $Address , - #The worksheet where the format is to be applied [OfficeOpenXml.ExcelWorksheet]$WorkSheet , - #A standard named-rule - Top / Bottom / Less than / Greater than / Contains etc. [Parameter(Mandatory = $true, ParameterSetName = "NamedRule", Position = 1)] [OfficeOpenXml.ConditionalFormatting.eExcelConditionalFormattingRuleType]$RuleType , - #Text color for matching objects [Parameter(ParameterSetName = "NamedRule")] [Alias("ForegroundColour","FontColor")] $ForegroundColor, - #Color for databar type charts [Parameter(Mandatory = $true, ParameterSetName = "DataBar")] [Alias("DataBarColour")] $DataBarColor, - #One of the three-icon set types (e.g. Traffic Lights) [Parameter(Mandatory = $true, ParameterSetName = "ThreeIconSet")] [OfficeOpenXml.ConditionalFormatting.eExcelconditionalFormatting3IconsSetType]$ThreeIconsSet, - #A four-icon set name [Parameter(Mandatory = $true, ParameterSetName = "FourIconSet")] [OfficeOpenXml.ConditionalFormatting.eExcelconditionalFormatting4IconsSetType]$FourIconsSet, - #A five-icon set name [Parameter(Mandatory = $true, ParameterSetName = "FiveIconSet")] [OfficeOpenXml.ConditionalFormatting.eExcelconditionalFormatting5IconsSetType]$FiveIconsSet, - #Use the Icon-Set in reverse order, or reverse the orders of Two- & Three-Color Scales [Parameter(ParameterSetName = "NamedRule")] [Parameter(ParameterSetName = "ThreeIconSet")] [Parameter(ParameterSetName = "FourIconSet")] [Parameter(ParameterSetName = "FiveIconSet")] [switch]$Reverse, - #A value for the condition (for example 2000 if the test is 'lessthan 2000'; Formulas should begin with "=" ) [Parameter(ParameterSetName = "NamedRule",Position = 2)] $ConditionValue, - #A second value for the conditions like "Between X and Y" [Parameter(ParameterSetName = "NamedRule",Position = 3)] $ConditionValue2, - #Background color for matching items [Parameter(ParameterSetName = "NamedRule")] $BackgroundColor, - #Background pattern for matching items [Parameter(ParameterSetName = "NamedRule")] [OfficeOpenXml.Style.ExcelFillStyle]$BackgroundPattern = [OfficeOpenXml.Style.ExcelFillStyle]::None , - #Secondary color when a background pattern requires it [Parameter(ParameterSetName = "NamedRule")] $PatternColor, - #Sets the numeric format for matching items [Parameter(ParameterSetName = "NamedRule")] $NumberFormat, - #Put matching items in bold face [Parameter(ParameterSetName = "NamedRule")] [switch]$Bold, - #Put matching items in italic [Parameter(ParameterSetName = "NamedRule")] [switch]$Italic, - #Underline matching items [Parameter(ParameterSetName = "NamedRule")] [switch]$Underline, - #Strikethrough text of matching items [Parameter(ParameterSetName = "NamedRule")] [switch]$StrikeThru, - #Prevent the processing of subsequent rules [Parameter(ParameterSetName = "NamedRule")] [switch]$StopIfTrue, - #Set the sequence for rule processing [int]$Priority, - #If specified pass the rule back to the caller to allow additional customization. [switch]$PassThru ) diff --git a/ExportedCommands/Add-ExcelChart.ps1 b/ExportedCommands/Add-ExcelChart.ps1 new file mode 100644 index 0000000..6f77258 --- /dev/null +++ b/ExportedCommands/Add-ExcelChart.ps1 @@ -0,0 +1,142 @@ + +function Add-ExcelChart { + [cmdletbinding(DefaultParameterSetName = 'Worksheet')] + [OutputType([OfficeOpenXml.Drawing.Chart.ExcelChart])] + param( + [Parameter(ParameterSetName = 'Worksheet', Mandatory = $true)] + [OfficeOpenXml.ExcelWorksheet]$Worksheet, + [Parameter(ParameterSetName = 'PivotTable', Mandatory = $true)] + [OfficeOpenXml.Table.PivotTable.ExcelPivotTable]$PivotTable , + [String]$Title, + [OfficeOpenXml.Drawing.Chart.eChartType]$ChartType = "ColumnStacked", + [OfficeOpenXml.Drawing.Chart.eTrendLine[]]$ChartTrendLine, + $XRange, + $YRange, + [int]$Width = 500, + [int]$Height = 350, + [int]$Row = 0, + [int]$RowOffSetPixels = 10, + [int]$Column = 6, + [int]$ColumnOffSetPixels = 5, + [OfficeOpenXml.Drawing.Chart.eLegendPosition]$LegendPosition, + $LegendSize, + [Switch]$LegendBold, + [Switch]$NoLegend, + [Switch]$ShowCategory, + [Switch]$ShowPercent, + [String[]]$SeriesHeader, + [Switch]$TitleBold, + [Int]$TitleSize , + [String]$XAxisTitleText, + [Switch]$XAxisTitleBold, + $XAxisTitleSize , + [string]$XAxisNumberformat, + $XMajorUnit, + $XMinorUnit, + $XMaxValue, + $XMinValue, + [OfficeOpenXml.Drawing.Chart.eAxisPosition]$XAxisPosition , + [String]$YAxisTitleText, + [Switch]$YAxisTitleBold, + $YAxisTitleSize, + [string]$YAxisNumberformat, + $YMajorUnit, + $YMinorUnit, + $YMaxValue, + $YMinValue, + [OfficeOpenXml.Drawing.Chart.eAxisPosition]$YAxisPosition, + [Switch]$PassThru + ) + try { + if ($PivotTable) { + $Worksheet = $PivotTable.WorkSheet + $chart = $Worksheet.Drawings.AddChart(("Chart" + $PivotTable.Name ), $ChartType, $PivotTable) + } + else { + $ChartName = 'Chart' + (Split-Path -Leaf ([System.IO.path]::GetTempFileName())) -replace 'tmp|\.', '' + $chart = $Worksheet.Drawings.AddChart($ChartName, $ChartType) + $chartDefCount = @($YRange).Count + if ($chartDefCount -eq 1) { + $Series = $chart.Series.Add($YRange, $XRange) + if ($ChartTrendLine) { + if ($ChartType -notmatch "stacked|3D$|pie|Doughnut|Cone|Cylinder|Pyramid") { + foreach ($trendLine in $ChartTrendLine) { + $null = $Series.TrendLines.Add($trendLine) + } + } + else { + Write-Warning "Chart trend line is not supported for chart type: $ChartType" + } + } + if ($SeriesHeader) { $Series.Header = $SeriesHeader } + else { $Series.Header = 'Series 1' } + } + else { + for ($idx = 0; $idx -lt $chartDefCount; $idx += 1) { + if ($Yrange.count -eq $xrange.count) { + $Series = $chart.Series.Add($YRange[$idx], $XRange[$idx]) + } + else { + $Series = $chart.Series.Add($YRange[$idx], $XRange) + } + if ($SeriesHeader.Count -gt 0) { + if ($SeriesHeader[$idx] -match '^=') { $Series.HeaderAddress = $SeriesHeader[$idx] -replace '^=', '' } + else { $Series.Header = $SeriesHeader[$idx] } + } + else { $Series.Header = "Series $($idx)" } + } + } + } + if ($Title) { + $chart.Title.Text = $Title + if ($TitleBold) { $chart.Title.Font.Bold = $true } + if ($TitleSize) { $chart.Title.Font.Size = $TitleSize } + } + if ($NoLegend) { $chart.Legend.Remove() } + else { + if ($PSBoundParameters.ContainsKey('LegendPosition')) { $chart.Legend.Position = $LegendPosition } + if ($PSBoundParameters.ContainsKey('LegendBold')) { $chart.Legend.Font.Bold = [boolean]$LegendBold } + if ($LegendSize) { $chart.Legend.Font.Size = $LegendSize } + } + + if ($XAxisTitleText) { + $chart.XAxis.Title.Text = $XAxisTitleText + if ($PSBoundParameters.ContainsKey('XAxisTitleBold')) { + $chart.XAxis.Title.Font.Bold = [boolean]$XAxisTitleBold + } + 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" } + #$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 } + if ($null -ne $XMinValue) { $chart.XAxis.MinValue = $XMinValue } + if ($null -ne $XMaxValue) { $chart.XAxis.MaxValue = $XMaxValue } + if ($XAxisNumberformat) { $chart.XAxis.Format = (Expand-NumberFormat $XAxisNumberformat) } + + if ($YAxisTitleText) { + $chart.YAxis.Title.Text = $YAxisTitleText + if ($PSBoundParameters.ContainsKey('YAxisTitleBold')) { + $chart.YAxis.Title.Font.Bold = [boolean]$YAxisTitleBold + } + 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" } + #$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 } + if ($null -ne $YMinValue) { $chart.YAxis.MinValue = $YMinValue } + if ($null -ne $YMaxValue) { $chart.YAxis.MaxValue = $YMaxValue } + if ($YAxisNumberformat) { $chart.YAxis.Format = (Expand-NumberFormat $YAxisNumberformat) } + if ($null -ne $chart.Datalabel) { + $chart.Datalabel.ShowCategory = [boolean]$ShowCategory + $chart.Datalabel.ShowPercent = [boolean]$ShowPercent + } + + $chart.SetPosition($Row, $RowOffsetPixels, $Column, $ColumnOffsetPixels) + $chart.SetSize($Width, $Height) + + if ($PassThru) { return $chart } + } + catch { Write-Warning -Message "Failed adding Chart to worksheet '$($WorkSheet).name': $_" } +} diff --git a/ExportedCommands/Add-ExcelDataValidationRule.ps1 b/ExportedCommands/Add-ExcelDataValidationRule.ps1 new file mode 100644 index 0000000..a98ba8f --- /dev/null +++ b/ExportedCommands/Add-ExcelDataValidationRule.ps1 @@ -0,0 +1,58 @@ +Function Add-ExcelDataValidationRule { + [CmdletBinding()] + Param( + [Parameter(ValueFromPipeline = $true,Position=0)] + [Alias("Address")] + $Range , + [OfficeOpenXml.ExcelWorksheet]$WorkSheet , + [ValidateSet('Any','Custom','DateTime','Decimal','Integer','List','TextLength','Time')] + $ValidationType, + [OfficeOpenXml.DataValidation.ExcelDataValidationOperator]$Operator = [OfficeOpenXml.DataValidation.ExcelDataValidationOperator]::equal , + $Value, + $Value2, + $Formula, + $Formula2, + $ValueSet, + [switch]$ShowErrorMessage, + [OfficeOpenXml.DataValidation.ExcelDataValidationWarningStyle]$ErrorStyle, + [String]$ErrorTitle, + [String]$ErrorBody, + [switch]$ShowPromptMessage, + [String]$PromptBody, + [String]$PromptTitle, + [String]$NoBlank + ) + if ($Range -is [Array]) { + $null = $PSBoundParameters.Remove("Range") + $Range | Add-ExcelDataValidationRule @PSBoundParameters + } + else { + #We should accept, a worksheet and a name of a range or a cell address; a table; the address of a table; a named range; a row, a column or .Cells[ ] + if (-not $WorkSheet -and $Range.worksheet) {$WorkSheet = $Range.worksheet} + if ($Range.Address) {$Range = $Range.Address} + + if ($Range -isnot [string] -or -not $WorkSheet) {Write-Warning -Message "You need to provide a worksheet and range of cells." ;return} + #else we assume Range is a range. + + $validation = $WorkSheet.DataValidations."Add$ValidationType`Validation"($Range) + if ($validation.AllowsOperator) {$validation.Operator = $Operator} + if ($PSBoundParameters.ContainsKey('value')) { + $validation.Formula.Value = $Value + } + elseif ($Formula) {$validation.Formula.ExcelFormula = $Formula} + elseif ($ValueSet) {Foreach ($v in $ValueSet) {$validation.Formula.Values.Add($V)}} + if ($PSBoundParameters.ContainsKey('Value2')) { + $validation.Formula2.Value = $Value2 + } + elseif ($Formula2) {$validation.Formula2.ExcelFormula = $Formula} + $validation.ShowErrorMessage = [bool]$ShowErrorMessage + $validation.ShowInputMessage = [bool]$ShowPromptMessage + $validation.AllowBlank = -not $NoBlank + + if ($PromptTitle) {$validation.PromptTitle = $PromptTitle} + if ($ErrorTitle) {$validation.ErrorTitle = $ErrorTitle} + if ($PromptBody) {$validation.Prompt = $PromptBody} + if ($ErrorBody) {$validation.Error = $ErrorBody} + if ($ErrorStyle) {$validation.ErrorStyle = $ErrorStyle} + } + } diff --git a/ExportedCommands/Add-ExcelName.ps1 b/ExportedCommands/Add-ExcelName.ps1 new file mode 100644 index 0000000..93b8378 --- /dev/null +++ b/ExportedCommands/Add-ExcelName.ps1 @@ -0,0 +1,30 @@ +function Add-ExcelName { + [CmdletBinding()] + param( + #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. + [String]$RangeName + ) + try { + $ws = $Range.Worksheet + if (-not $RangeName) { + $RangeName = $ws.Cells[$Range.Start.Address].Value + $Range = ($Range.Worksheet.cells[($range.start.row +1), $range.start.Column , $range.end.row, $range.end.column]) + } + if ($RangeName -match '\W') { + Write-Warning -Message "Range name '$RangeName' contains illegal characters, they will be replaced with '_'." + $RangeName = $RangeName -replace '\W','_' + } + if ($ws.names[$RangeName]) { + Write-verbose -Message "Updating Named range '$RangeName' to $($Range.FullAddressAbsolute)." + $ws.Names[$RangeName].Address = $Range.FullAddressAbsolute + } + else { + Write-verbose -Message "Creating Named range '$RangeName' as $($Range.FullAddressAbsolute)." + $null = $ws.Names.Add($RangeName, $Range) + } + } + catch {Write-Warning -Message "Failed adding named range '$RangeName' to worksheet '$($ws.Name)': $_" } +} diff --git a/ExportedCommands/Add-ExcelTable.ps1 b/ExportedCommands/Add-ExcelTable.ps1 new file mode 100644 index 0000000..5cb25ec --- /dev/null +++ b/ExportedCommands/Add-ExcelTable.ps1 @@ -0,0 +1,75 @@ +function Add-ExcelTable { + [CmdletBinding()] + [OutputType([OfficeOpenXml.Table.ExcelTable])] + param ( + [Parameter(Mandatory=$true)] + [OfficeOpenXml.ExcelRange]$Range, + [String]$TableName = "", + [OfficeOpenXml.Table.TableStyles]$TableStyle = 'Medium6', + [Switch]$ShowHeader , + [Switch]$ShowFilter, + [Switch]$ShowTotal, + [hashtable]$TotalSettings, + [Switch]$ShowFirstColumn, + [Switch]$ShowLastColumn, + [Switch]$ShowRowStripes, + [Switch]$ShowColumnStripes, + [Switch]$PassThru + ) + try { + if ($TableName -eq "" -or $null -eq $TableName) { + $tbl = $Range.Worksheet.Tables.Add($Range, "") + } + else { + if ([OfficeOpenXml.FormulaParsing.ExcelUtilities.ExcelAddressUtil]::IsValidAddress($TableName)) { + Write-Warning -Message "$TableName reads as an Excel address, and so is not allowed as a table name." + return + } + if ($TableName -notMatch '^[A-Z]') { + Write-Warning -Message "$TableName is not allowed as a table name because it does not begin with a letter." + return + } + if ($TableName -match "\W") { + Write-Warning -Message "At least one character in $TableName is illegal in a table name and will be replaced with '_' . " + $TableName = $TableName -replace '\W', '_' + } + $ws = $Range.Worksheet + #if the table exists in this worksheet, update it. + if ($ws.Tables[$TableName]) { + $tbl =$ws.Tables[$TableName] + $tbl.TableXml.table.ref = $Range.Address + Write-Verbose -Message "Re-defined table '$TableName', now at $($Range.Address)." + } + elseif ($ws.Workbook.Worksheets.Tables.Name -contains $TableName) { + Write-Warning -Message "The Table name '$TableName' is already used on a different worksheet." + return + } + else { + $tbl = $ws.Tables.Add($Range, $TableName) + Write-Verbose -Message "Defined table '$($tbl.Name)' at $($Range.Address)" + } + } + #it seems that show total changes some of the others, so the sequence matters. + if ($PSBoundParameters.ContainsKey('ShowHeader')) {$tbl.ShowHeader = [bool]$ShowHeader} + if ($PSBoundParameters.ContainsKey('TotalSettings')) { + $tbl.ShowTotal = $true + foreach ($k in $TotalSettings.keys) { + if (-not $tbl.Columns[$k]) {Write-Warning -Message "Table does not have a Column '$k'."} + elseif ($TotalSettings[$k] -notin @("Average", "Count", "CountNums", "Max", "Min", "None", "StdDev", "Sum", "Var") ) { + Write-Warning -Message "'$($TotalSettings[$k])' is not a valid total function." + } + else {$tbl.Columns[$k].TotalsRowFunction = $TotalSettings[$k]} + } + } + elseif ($PSBoundParameters.ContainsKey('ShowTotal')) {$tbl.ShowTotal = [bool]$ShowTotal} + if ($PSBoundParameters.ContainsKey('ShowFilter')) {$tbl.ShowFilter = [bool]$ShowFilter} + if ($PSBoundParameters.ContainsKey('ShowFirstColumn')) {$tbl.ShowFirstColumn = [bool]$ShowFirstColumn} + if ($PSBoundParameters.ContainsKey('ShowLastColumn')) {$tbl.ShowLastColumn = [bool]$ShowLastColumn} + if ($PSBoundParameters.ContainsKey('ShowRowStripes')) {$tbl.ShowRowStripes = [bool]$ShowRowStripes} + if ($PSBoundParameters.ContainsKey('ShowColumnStripes')) {$tbl.ShowColumnStripes = [bool]$ShowColumnStripes} + $tbl.TableStyle = $TableStyle + + if ($PassThru) {return $tbl} + } + catch {Write-Warning -Message "Failed adding table '$TableName' to worksheet '$WorksheetName': $_"} +} diff --git a/ExportedCommands/Add-PivotTable.ps1 b/ExportedCommands/Add-PivotTable.ps1 new file mode 100644 index 0000000..cd7fc46 --- /dev/null +++ b/ExportedCommands/Add-PivotTable.ps1 @@ -0,0 +1,176 @@ +function Add-PivotTable { + [cmdletbinding(defaultParameterSetName = 'ChartbyParams')] + [OutputType([OfficeOpenXml.Table.PivotTable.ExcelPivotTable])] + param ( + [Parameter(Mandatory = $true)] + [string]$PivotTableName, + [OfficeOpenXml.ExcelAddressBase] + $Address, + $ExcelPackage, + $SourceWorkSheet, + $SourceRange, + $PivotRows, + $PivotData, + $PivotColumns, + $PivotFilter, + [Switch]$PivotDataToColumn, + [ValidateSet("Both", "Columns", "Rows", "None")] + [String]$PivotTotals = "Both", + [Switch]$NoTotalsInPivot, + [String]$GroupDateRow, + [OfficeOpenXml.Table.PivotTable.eDateGroupBy[]]$GroupDatePart, + [String]$GroupNumericRow, + [double]$GroupNumericMin = 0 , + [double]$GroupNumericMax = [Double]::MaxValue , + [double]$GroupNumericInterval = 100 , + [string]$PivotNumberFormat, + [OfficeOpenXml.Table.TableStyles]$PivotTableStyle, + [Parameter(ParameterSetName = 'ChartbyDef', Mandatory = $true, ValueFromPipelineByPropertyName = $true)] + $PivotChartDefinition, + [Parameter(ParameterSetName = 'ChartbyParams')] + [Switch]$IncludePivotChart, + [Parameter(ParameterSetName = 'ChartbyParams')] + [String]$ChartTitle = "", + [Parameter(ParameterSetName = 'ChartbyParams')] + [int]$ChartHeight = 400 , + [Parameter(ParameterSetName = 'ChartbyParams')] + [int]$ChartWidth = 600, + [Parameter(ParameterSetName = 'ChartbyParams')] + [Int]$ChartRow = 0 , + [Parameter(ParameterSetName = 'ChartbyParams')] + [Int]$ChartColumn = 4, + [Parameter(ParameterSetName = 'ChartbyParams')] + [Int]$ChartRowOffSetPixels = 0 , + [Parameter(ParameterSetName = 'ChartbyParams')] + [Int]$ChartColumnOffSetPixels = 0, + [Parameter(ParameterSetName = 'ChartbyParams')] + [OfficeOpenXml.Drawing.Chart.eChartType]$ChartType = 'Pie', + [Parameter(ParameterSetName = 'ChartbyParams')] + [Switch]$NoLegend, + [Parameter(ParameterSetName = 'ChartbyParams')] + [Switch]$ShowCategory, + [Parameter(ParameterSetName = 'ChartbyParams')] + [Switch]$ShowPercent, + [switch]$Activate, + [Switch]$PassThru + ) + if ($PivotTableName.length -gt 250) { + Write-warning -Message "PivotTable name will be truncated" + $PivotTableName = $PivotTableName.Substring(0, 250) + } + if ($Address) { + [OfficeOpenXml.ExcelWorksheet]$wsPivot = $address.Worksheet + } + else { + 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 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 PivotTable. $_" } + } + #if the pivot doesn't exist, create it. + 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 . + if ( $SourceWorkSheet -is [string]) { + $SourceWorkSheet = $ExcelPackage.Workbook.Worksheets.where( {$_.name -Like $SourceWorkSheet})[0] + } + elseif ( $SourceWorkSheet -is [int] ) { + $SourceWorkSheet = $ExcelPackage.Workbook.Worksheets[$SourceWorkSheet] + } + if ( $SourceRange -is [OfficeOpenXml.Table.ExcelTable]) {$SourceRange = $SourceRange.Address } + if ( $sourceRange -is [OfficeOpenXml.ExcelRange] -or + $SourceRange -is [OfficeOpenXml.ExcelAddress]) { + $pivotTable = $wsPivot.PivotTables.Add($Address, $SourceRange, $pivotTableName) + } + elseif (-not $SourceRange) { + $pivotTable = $wsPivot.PivotTables.Add($Address, $SourceWorkSheet.cells[$SourceWorkSheet.Dimension.Address], $pivotTableName) + } + elseif ($SourceWorkSheet -isnot [OfficeOpenXml.ExcelWorksheet] ) { + Write-Warning -Message "Could not find source Worksheet for pivot-table '$pivotTableName'." ; return + } + 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 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." } + } + foreach ($Column in $PivotColumns) { + try {$null = $pivotTable.ColumnFields.Add($pivotTable.Fields[$Column])} + catch {Write-Warning -message "Could not add '$Column' to Columns in PivotTable $pivotTableName." } + } + if ($PivotData -is [HashTable] -or $PivotData -is [System.Collections.Specialized.OrderedDictionary]) { + $PivotData.Keys | ForEach-Object { + try { + $df = $pivotTable.DataFields.Add($pivotTable.Fields[$_]) + $df.Function = $PivotData.$_ + if ($PivotNumberFormat) {$df.Format = (Expand-NumberFormat -NumberFormat $PivotNumberFormat)} + } + catch {Write-Warning -message "Problem adding data fields to PivotTable $pivotTableName." } + } + } + else { + foreach ($field in $PivotData) { + try { + $df = $pivotTable.DataFields.Add($pivotTable.Fields[$field]) + $df.Function = 'Count' + } + catch {Write-Warning -message "Problem adding data field '$field' to PivotTable $pivotTableName." } + } + } + foreach ( $pFilter in $PivotFilter) { + try { $null = $pivotTable.PageFields.Add($pivotTable.Fields[$pFilter])} + catch {Write-Warning -message "Could not add '$pFilter' to Filter/Page fields in PivotTable $pivotTableName." } + } + if ($NoTotalsInPivot) {$PivotTotals = "None" } + if ($PivotTotals -eq "None" -or $PivotTotals -eq "Columns") { $pivotTable.RowGrandTotals = $false } + elseif ($PivotTotals -eq "Both" -or $PivotTotals -eq "Rows") { $pivotTable.RowGrandTotals = $true } + if ($PivotTotals -eq "None" -or $PivotTotals -eq "Rows") { $pivotTable.ColumGrandTotals = $false } # Epplus spelling mistake, not mine! + elseif ($PivotTotals -eq "Both" -or $PivotTotals -eq "Columns") { $pivotTable.ColumGrandTotals = $true } + if ($PivotDataToColumn ) { $pivotTable.DataOnRows = $false } + if ($PivotTableStyle) { $pivotTable.TableStyle = $PivotTableStyle} + if ($GroupNumericRow) { + $r = $pivotTable.RowFields.Where( {$_.name -eq $GroupNumericRow }) + if (-not $r ) {Write-Warning -Message "Could not find a Row field named '$GroupNumericRow'; no numeric grouping will be done."} + else {$r.AddNumericGrouping($GroupNumericMin, $GroupNumericMax, $GroupNumericInterval)} + } + if ($GroupDateRow -and $PSBoundParameters.ContainsKey("GroupDatePart")) { + $r = $pivotTable.RowFields.Where( {$_.name -eq $GroupDateRow }) + if (-not $r ) {Write-Warning -Message "Could not find a Row field named '$GroupDateRow'; no date grouping will be done."} + else {$r.AddDateGrouping($GroupDatePart)} + } + } + catch {Write-Warning -Message "Failed adding PivotTable '$pivotTableName': $_"} + } + else { + 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.SourceRange = $SourceWorkSheet.cells[$SourceRange] + #change for epPlus 4.5 - Previously needed to hack the xml + # $pivotTable.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref = $SourceRange + + } + + #Create the chart if it doesn't exist, leave alone if it does. + if ($IncludePivotChart -and -not $wsPivot.Drawings["Chart$pivotTableName"] ) { + try {Add-ExcelChart -PivotTable $pivotTable -ChartType $ChartType -Width $ChartWidth -Height $ChartHeight -Row $ChartRow -Column $ChartColumn -RowOffSetPixels $ChartRowOffSetPixels -ColumnOffSetPixels $ChartColumnOffSetPixels -Title $ChartTitle -NoLegend:$NoLegend -ShowCategory:$ShowCategory -ShowPercent:$ShowPercent } + catch {Write-Warning -Message "Failed adding chart for pivotable '$pivotTableName': $_"} + } + elseif ($PivotChartDefinition -and -not $wsPivot.Drawings["Chart$pivotTableName"]) { + if ($PivotChartDefinition -is [System.Management.Automation.PSCustomObject]) { + $params = @{PivotTable = $pivotTable } + $PivotChartDefinition.PSObject.Properties | ForEach-Object {if ( $null -ne $_.value) {$params[$_.name] = $_.value}} + Add-ExcelChart @params + } + elseif ($PivotChartDefinition -is [hashtable] -or $PivotChartDefinition -is [System.Collections.Specialized.OrderedDictionary]) { + Add-ExcelChart -PivotTable $pivotTable @PivotChartDefinition + } + } + if ($PassThru) {return $pivotTable} +} diff --git a/ExportedCommands/Add-Worksheet.ps1 b/ExportedCommands/Add-Worksheet.ps1 new file mode 100644 index 0000000..0a025ab --- /dev/null +++ b/ExportedCommands/Add-Worksheet.ps1 @@ -0,0 +1,80 @@ +function Add-Worksheet { + [cmdletBinding()] + [OutputType([OfficeOpenXml.ExcelWorksheet])] + param( + [Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "Package", Position = 0)] + [OfficeOpenXml.ExcelPackage]$ExcelPackage, + [Parameter(Mandatory = $true, ParameterSetName = "WorkBook")] + [OfficeOpenXml.ExcelWorkbook]$ExcelWorkbook, + [string]$WorksheetName , + [switch]$ClearSheet, + [Switch]$MoveToStart, + [Switch]$MoveToEnd, + $MoveBefore , + $MoveAfter , + [switch]$Activate, + [OfficeOpenXml.ExcelWorksheet]$CopySource, + [parameter(DontShow=$true)] + [Switch] $NoClobber + ) + #if we were given a workbook use it, if we were given a package, use its workbook + if ($ExcelPackage -and -not $ExcelWorkbook) {$ExcelWorkbook = $ExcelPackage.Workbook} + + # If WorksheetName was given, try to use that worksheet. If it wasn't, and we are copying an existing sheet, try to use the sheet name + # If we are not copying a sheet, and have no name, use the name "SheetX" where X is the number of the new sheet + if (-not $WorksheetName -and $CopySource -and -not $ExcelWorkbook[$CopySource.Name]) {$WorksheetName = $CopySource.Name} + elseif (-not $WorksheetName) {$WorksheetName = "Sheet" + (1 + $ExcelWorkbook.Worksheets.Count)} + else {$ws = $ExcelWorkbook.Worksheets[$WorksheetName]} + + #If -clearsheet was specified and the named sheet exists, delete it + if ($ws -and $ClearSheet) { $ExcelWorkbook.Worksheets.Delete($WorksheetName) ; $ws = $null } + + #Copy or create new sheet as needed + if (-not $ws -and $CopySource) { + Write-Verbose -Message "Copying into worksheet '$WorksheetName'." + $ws = $ExcelWorkbook.Worksheets.Add($WorksheetName, $CopySource) + } + elseif (-not $ws) { + $ws = $ExcelWorkbook.Worksheets.Add($WorksheetName) + Write-Verbose -Message "Adding worksheet '$WorksheetName'." + } + else {Write-Verbose -Message "Worksheet '$WorksheetName' already existed."} + #region Move sheet if needed + if ($MoveToStart) {$ExcelWorkbook.Worksheets.MoveToStart($WorksheetName) } + elseif ($MoveToEnd ) {$ExcelWorkbook.Worksheets.MoveToEnd($WorksheetName) } + elseif ($MoveBefore ) { + if ($ExcelWorkbook.Worksheets[$MoveBefore]) { + if ($MoveBefore -is [int]) { + $ExcelWorkbook.Worksheets.MoveBefore($ws.Index, $MoveBefore) + } + else {$ExcelWorkbook.Worksheets.MoveBefore($WorksheetName, $MoveBefore)} + } + else {Write-Warning "Can't find worksheet '$MoveBefore'; worsheet '$WorksheetName' will not be moved."} + } + elseif ($MoveAfter ) { + if ($MoveAfter -eq "*") { + if ($WorksheetName -lt $ExcelWorkbook.Worksheets[1].Name) {$ExcelWorkbook.Worksheets.MoveToStart($WorksheetName)} + else { + $i = 1 + While ($i -lt $ExcelWorkbook.Worksheets.Count -and ($ExcelWorkbook.Worksheets[$i + 1].Name -le $WorksheetName) ) { $i++} + $ExcelWorkbook.Worksheets.MoveAfter($ws.Index, $i) + } + } + elseif ($ExcelWorkbook.Worksheets[$MoveAfter]) { + if ($MoveAfter -is [int]) { + $ExcelWorkbook.Worksheets.MoveAfter($ws.Index, $MoveAfter) + } + else { + $ExcelWorkbook.Worksheets.MoveAfter($WorksheetName, $MoveAfter) + } + } + else {Write-Warning "Can't find worksheet '$MoveAfter'; worsheet '$WorksheetName' will not be moved."} + } + #endregion + if ($Activate) {Select-Worksheet -ExcelWorksheet $ws } + if ($ExcelPackage -and -not (Get-Member -InputObject $ExcelPackage -Name $ws.Name)) { + $sb = [scriptblock]::Create(('$this.workbook.Worksheets["{0}"]' -f $ws.name)) + Add-Member -InputObject $ExcelPackage -MemberType ScriptProperty -Name $ws.name -Value $sb + } + return $ws +} diff --git a/ExportedCommands/Close-ExcelPackage.ps1 b/ExportedCommands/Close-ExcelPackage.ps1 new file mode 100644 index 0000000..d49425e --- /dev/null +++ b/ExportedCommands/Close-ExcelPackage.ps1 @@ -0,0 +1,34 @@ + +Function Close-ExcelPackage { + [CmdLetBinding()] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")] + Param ( + [parameter(Mandatory=$true, ValueFromPipeline=$true)] + [OfficeOpenXml.ExcelPackage]$ExcelPackage, + [switch]$Show, + [Switch]$NoSave, + $SaveAs, + [ValidateNotNullOrEmpty()] + [String]$Password, + [switch]$Calculate + ) + if ( $NoSave) {$ExcelPackage.Dispose()} + else { + if ($Calculate) { + try { [OfficeOpenXml.CalculationExtension]::Calculate($ExcelPackage.Workbook) } + Catch { Write-Warning "One or more errors occured while calculating, save will continue, but there may be errors in the workbook."} + } + if ($SaveAs) { + $SaveAs = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($SaveAs) + if ($Password) {$ExcelPackage.SaveAs( $SaveAs, $Password ) } + else {$ExcelPackage.SaveAs( $SaveAs)} + } + else { + if ($Password) {$ExcelPackage.Save($Password) } + else {$ExcelPackage.Save() } + $SaveAs = $ExcelPackage.File.FullName + } + $ExcelPackage.Dispose() + if ($Show) {Start-Process -FilePath $SaveAs } + } +} diff --git a/Compare-WorkSheet.ps1 b/ExportedCommands/Compare-WorkSheet.ps1 similarity index 68% rename from Compare-WorkSheet.ps1 rename to ExportedCommands/Compare-WorkSheet.ps1 index fb8edf6..8d478ed 100644 --- a/Compare-WorkSheet.ps1 +++ b/ExportedCommands/Compare-WorkSheet.ps1 @@ -1,116 +1,29 @@ Function Compare-WorkSheet { -<# - .Synopsis - Compares two worksheets and shows the differences. - .Description - This command takes two file names, one or two worksheet names and a name - for a "key" column. It reads the worksheet from each file and decides the - column names and builds a hashtable of the key-column values and the - rows in which they appear. - It then uses PowerShell's Compare-Object command to compare the sheets - (explicitly checkingall the column names which have not been excluded). - For the difference rows it adds the row number for the key of that row - - we have to add the key after doing the comparison, otherwise identical - rows at different positions in the file will not be considered a match. - We also add the name of the file and sheet in which the difference occurs. - If -BackgroundColor is specified the difference rows will be changed to - that background in the orginal file. - .Example - Compare-WorkSheet -Referencefile 'Server56.xlsx' -Differencefile 'Server57.xlsx' -WorkSheetName Products -key IdentifyingNumber -ExcludeProperty Install* | Format-Table - - The two workbooks in this example contain the result of redirecting a subset - of properties from Get-WmiObject -Class win32_product to Export-Excel. - The command compares the "Products" pages in the two workbooks, but we - don't want to register a difference if the software was installed on a - different date or from a different place, and excluding Install* removes - InstallDate and InstallSource. This data doesn't have a "Name" column, so - we specify the "IdentifyingNumber" column as the key. - The results will be presented as a table. - .Example - 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 - 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 - 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 - 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 - 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 - 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. -#> [cmdletbinding(DefaultParameterSetName)] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification="Write host used for sub-warning level message to operator which does not form output")] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification="False positives when initializing variable in begin block")] Param( - #First file to compare. [parameter(Mandatory=$true,Position=0)] $Referencefile , - #Second file to compare. [parameter(Mandatory=$true,Position=1)] $Differencefile , - #Name(s) of worksheets to compare. $WorkSheetName = "Sheet1", - #Properties to include in the comparison - supports wildcards, default is "*". $Property = "*" , - #Properties to exclude from the comparison - supports wildcards. $ExcludeProperty , - #Specifies custom property names to use, instead of the values defined in the starting row of the sheet. [Parameter(ParameterSetName='B', Mandatory)] [String[]]$Headername, - #Automatically generate property names (P1, P2, P3 ...) instead of the using the values the starting row of the sheet. [Parameter(ParameterSetName='C', Mandatory)] [switch]$NoHeader, - #The row from where we start to import data: all rows above the start row are disregarded. By default, this is the first row. [int]$Startrow = 1, - #If specified, highlights all the cells - so you can make Equal cells one color, and Different cells another. $AllDataBackgroundColor, - #If specified, highlights the rows with differences. $BackgroundColor, - #If specified identifies the tabs which contain difference rows (ignored if -BackgroundColor is omitted). $TabColor, - #Name of a column which is unique and will be used to add a row to the DIFF object, defaults to "Name". $Key = "Name" , - #If specified, highlights the DIFF columns in rows which have the same key. $FontColor, - #If specified, opens the Excel workbooks instead of outputting the diff to the console (unless -PassThru is also specified). [Switch]$Show, - #If specified, the command tries to the show the DIFF in a Grid-View and not on the console. (unless-PassThru is also specified). This works best with few columns selected, and requires a key. [switch]$GridView, - #If specifieda full set of DIFF data is returned without filtering to the specified properties. [Switch]$PassThru, - #If specified the result will include equal rows as well. By default only different rows are returned. [Switch]$IncludeEqual, - #If specified, the result includes only the rows where both are equal. [Switch]$ExcludeDifferent ) diff --git a/ConvertExcelToImageFile.ps1 b/ExportedCommands/Convert-ExcelRangeToImage.ps1 similarity index 69% rename from ConvertExcelToImageFile.ps1 rename to ExportedCommands/Convert-ExcelRangeToImage.ps1 index 08efd46..988a931 100644 --- a/ConvertExcelToImageFile.ps1 +++ b/ExportedCommands/Convert-ExcelRangeToImage.ps1 @@ -1,28 +1,12 @@ -Function Convert-XlRangeToImage { - <# - .Synopsis - Gets the specified part of an Excel file and exports it as an image - .Description - Excel allows charts to be exported directly to a file, but can't do this with the rest of a sheet. To work round this this function - * Opens a copy of Excel and loads a file - * Selects a worksheet and then a range of cells in that worksheet - * Copies the select to the clipboard - * Saves the clipboard contents as an image file (it will save as .JPG unless the file name ends .BMP or .PNG) - * Copies a single cell to the clipboard (to prevent the "you have put a lot in the clipboard" message appearing) - * Closes Excel - #> +Function Convert-ExcelRangeToImage { + [alias("Convert-XlRangeToImage")] Param ( - #Path to the Excel file [parameter(Mandatory=$true)] $Path, - #Worksheet name - if none is specified "Sheet1" will be assumed $workSheetname = "Sheet1" , - #Range of cells within the sheet, e.g "A1:Z99" [parameter(Mandatory=$true)] $range, - #A bmp, png or jpg file where the result will be saved $destination = "$pwd\temp.png", - #If specified opens the image in the default viewer. [switch]$show ) $extension = $destination -replace '^.*\.(\w+)$' ,'$1' @@ -67,8 +51,8 @@ Add-ConditionalFormatting -WorkSheet $workSheet -Range "b2:B1000" -RuleType Grea Export-Excel -ExcelPackage $excelPackage -WorkSheetname $workSheetname -Convert-XlRangeToImage -Path $Path -workSheetname $workSheetname -range $range -destination "$pwd\temp.png" -show +Convert-ExcelRangeToImage -Path $Path -workSheetname $workSheetname -range $range -destination "$pwd\temp.png" -show #> -#Convert-XlRangeToImage -Path $Path -workSheetname $workSheetname -range $range -destination "$pwd\temp.png" -show \ No newline at end of file +#Convert-ExcelRangeToImage -Path $Path -workSheetname $workSheetname -range $range -destination "$pwd\temp.png" -show \ No newline at end of file diff --git a/ExportedCommands/ConvertFrom-ExcelData.md b/ExportedCommands/ConvertFrom-ExcelData.md new file mode 100644 index 0000000..95a8520 --- /dev/null +++ b/ExportedCommands/ConvertFrom-ExcelData.md @@ -0,0 +1,161 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# ConvertFrom-ExcelData + +## SYNOPSIS +Reads data from a sheet, and for each row, calls a custom scriptblock with a list of property names and the row of data. + +## SYNTAX + +``` +ConvertFrom-ExcelData [-Path] [[-scriptBlock] ] [[-WorkSheetname] ] + [[-HeaderRow] ] [[-Header] ] [-NoHeader] [-DataOnly] [] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### EXAMPLE 1 +``` +ConvertFrom-ExcelData .\testSQLGen.xlsx { +``` + +param($propertyNames, $record) + + $reportRecord = @() + foreach ($pn in $propertyNames) { + $reportRecord += "{0}: {1}" -f $pn, $record.$pn + } + $reportRecord +="" + $reportRecord -join "\`r\`n" +} + +First: John +Last: Doe +The Zip: 12345 +.... + +## PARAMETERS + +### -Path +{{ Fill Path Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: FullName + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -scriptBlock +{{ Fill scriptBlock Description }} + +```yaml +Type: ScriptBlock +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WorkSheetname +{{ Fill WorkSheetname Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: Sheet + +Required: False +Position: 3 +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HeaderRow +{{ Fill HeaderRow Description }} + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Header +{{ Fill Header Description }} + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoHeader +{{ Fill NoHeader Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DataOnly +{{ Fill DataOnly Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/ConvertFromExcelData.ps1 b/ExportedCommands/ConvertFrom-ExcelData.ps1 similarity index 58% rename from ConvertFromExcelData.ps1 rename to ExportedCommands/ConvertFrom-ExcelData.ps1 index 6b18fc1..536c703 100644 --- a/ConvertFromExcelData.ps1 +++ b/ExportedCommands/ConvertFrom-ExcelData.ps1 @@ -1,26 +1,5 @@ function ConvertFrom-ExcelData { - <# - .SYNOPSIS - Reads data from a sheet, and for each row, calls a custom scriptblock with a list of property names and the row of data. - - - .EXAMPLE - ConvertFrom-ExcelData .\testSQLGen.xlsx { - param($propertyNames, $record) - - $reportRecord = @() - foreach ($pn in $propertyNames) { - $reportRecord += "{0}: {1}" -f $pn, $record.$pn - } - $reportRecord +="" - $reportRecord -join "`r`n" - } - - First: John - Last: Doe - The Zip: 12345 - .... - #> + [alias("Use-ExcelData")] param( [Alias("FullName")] [Parameter(ValueFromPipelineByPropertyName = $true, ValueFromPipeline = $true, Mandatory = $true)] diff --git a/ExportedCommands/ConvertFrom-ExcelSheet.md b/ExportedCommands/ConvertFrom-ExcelSheet.md new file mode 100644 index 0000000..b91972c --- /dev/null +++ b/ExportedCommands/ConvertFrom-ExcelSheet.md @@ -0,0 +1,140 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# ConvertFrom-ExcelSheet + +## SYNOPSIS +Reads an Excel file an converts the data to a delimited text file. + +## SYNTAX + +``` +ConvertFrom-ExcelSheet [-Path] [[-OutputPath] ] [[-SheetName] ] [[-Encoding] ] + [[-Extension] ] [[-Delimiter] ] [] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### EXAMPLE 1 +``` +ConvertFrom-ExcelSheet .\TestSheets.xlsx .\data +``` + +Reads each sheet in TestSheets.xlsx and outputs it to the data directory as the sheet name with the extension .txt. + +### EXAMPLE 2 +``` +ConvertFrom-ExcelSheet .\TestSheets.xlsx .\data sheet?0 +``` + +Reads and outputs sheets like Sheet10 and Sheet20 form TestSheets.xlsx and outputs it to the data directory as the sheet name with the extension .txt. + +## PARAMETERS + +### -Path +{{ Fill Path Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: FullName + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OutputPath +{{ Fill OutputPath Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: .\ +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SheetName +{{ Fill SheetName Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: * +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Encoding +{{ Fill Encoding Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: UTF8 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Extension +{{ Fill Extension Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: .csv +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Delimiter +{{ Fill Delimiter Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 6 +Default value: ; +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/ExportedCommands/ConvertFrom-ExcelSheet.ps1 b/ExportedCommands/ConvertFrom-ExcelSheet.ps1 new file mode 100644 index 0000000..2c997af --- /dev/null +++ b/ExportedCommands/ConvertFrom-ExcelSheet.ps1 @@ -0,0 +1,48 @@ +function ConvertFrom-ExcelSheet { + [CmdletBinding()] + param + ( + [Alias("FullName")] + [Parameter(Mandatory = $true)] + [String] + $Path, + [String] + $OutputPath = '.\', + [String] + $SheetName = "*", + [ValidateSet('ASCII', 'BigEndianUniCode', 'Default', 'OEM', 'UniCode', 'UTF32', 'UTF7', 'UTF8')] + [string] + $Encoding = 'UTF8', + [ValidateSet('.txt', '.log', '.csv')] + [string] + $Extension = '.csv', + [ValidateSet(';', ',')] + [string] + $Delimiter = ';' + ) + + $Path = (Resolve-Path $Path).Path + $Stream = New-Object -TypeName System.IO.FileStream -ArgumentList $Path, "Open", "Read", "ReadWrite" + $xl = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Stream + $workbook = $xl.Workbook + + $targetSheets = $workbook.Worksheets | Where-Object { $_.Name -like $SheetName } + + $params = @{ } + $PSBoundParameters + $params.Remove("OutputPath") + $params.Remove("SheetName") + $params.Remove('Extension') + $params.NoTypeInformation = $true + + Foreach ($sheet in $targetSheets) { + Write-Verbose "Exporting sheet: $($sheet.Name)" + + $params.Path = "$OutputPath\$($Sheet.Name)$Extension" + + Import-Excel $Path -Sheet $($sheet.Name) | Export-Csv @params + } + + $Stream.Close() + $Stream.Dispose() + $xl.Dispose() +} diff --git a/ExportedCommands/ConvertFrom-ExcelToSQLInsert.ps1 b/ExportedCommands/ConvertFrom-ExcelToSQLInsert.ps1 new file mode 100644 index 0000000..bd2fda0 --- /dev/null +++ b/ExportedCommands/ConvertFrom-ExcelToSQLInsert.ps1 @@ -0,0 +1,48 @@ +function ConvertFrom-ExcelToSQLInsert { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + $TableName, + [Alias("FullName")] + [Parameter(ValueFromPipelineByPropertyName = $true, ValueFromPipeline = $true, Mandatory = $true)] + [ValidateScript( { Test-Path $_ -PathType Leaf })] + $Path, + [Alias("Sheet")] + $WorkSheetname = 1, + [Alias('HeaderRow', 'TopRow')] + [ValidateRange(1, 9999)] + [Int]$StartRow, + [string[]]$Header, + [switch]$NoHeader, + [switch]$DataOnly, + [switch]$ConvertEmptyStringsToNull, + [switch]$UseMSSQLSyntax + ) + + $null = $PSBoundParameters.Remove('TableName') + $null = $PSBoundParameters.Remove('ConvertEmptyStringsToNull') + $null = $PSBoundParameters.Remove('UseMSSQLSyntax') + + $params = @{} + $PSBoundParameters + + ConvertFrom-ExcelData @params { + param($propertyNames, $record) + + $ColumnNames = "'" + ($PropertyNames -join "', '") + "'" + if($UseMSSQLSyntax) { + $ColumnNames = "[" + ($PropertyNames -join "], [") + "]" + } + + $values = foreach ($propertyName in $PropertyNames) { + if ($ConvertEmptyStringsToNull.IsPresent -and [string]::IsNullOrEmpty($record.$propertyName)) { + 'NULL' + } + else { + "'" + $record.$propertyName + "'" + } + } + $targetValues = ($values -join ", ") + + "INSERT INTO {0} ({1}) Values({2});" -f $TableName, $ColumnNames, $targetValues + } +} \ No newline at end of file diff --git a/ExportedCommands/ConvertTo-ExcelXlsx.md b/ExportedCommands/ConvertTo-ExcelXlsx.md new file mode 100644 index 0000000..99178e7 --- /dev/null +++ b/ExportedCommands/ConvertTo-ExcelXlsx.md @@ -0,0 +1,72 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# ConvertTo-ExcelXlsx + +## SYNOPSIS +Converts an Excel xls to a xlsx using -ComObject + +## SYNTAX + +``` +ConvertTo-ExcelXlsx [-Path] [-Force] [] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -Path +{{ Fill Path Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Force +{{ Fill Force Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/ConvertToExcelXlsx.ps1 b/ExportedCommands/ConvertTo-ExcelXlsx.ps1 similarity index 94% rename from ConvertToExcelXlsx.ps1 rename to ExportedCommands/ConvertTo-ExcelXlsx.ps1 index f280a4c..21ef2f3 100644 --- a/ConvertToExcelXlsx.ps1 +++ b/ExportedCommands/ConvertTo-ExcelXlsx.ps1 @@ -1,8 +1,4 @@ Function ConvertTo-ExcelXlsx { - <# - .SYNOPSIS - Converts an Excel xls to a xlsx using -ComObject - #> [CmdletBinding()] Param ( diff --git a/Copy-ExcelWorkSheet.ps1 b/ExportedCommands/Copy-ExcelWorkSheet.ps1 similarity index 68% rename from Copy-ExcelWorkSheet.ps1 rename to ExportedCommands/Copy-ExcelWorkSheet.ps1 index d6ada62..ca79a29 100644 --- a/Copy-ExcelWorkSheet.ps1 +++ b/ExportedCommands/Copy-ExcelWorkSheet.ps1 @@ -1,48 +1,13 @@ function Copy-ExcelWorkSheet { - <# - .SYNOPSIS - Copies a worksheet between workbooks or within the same workbook. - .DESCRIPTION - Copy-ExcelWorkSheet takes a Source object which is either a worksheet, - or a package, Workbook or path, in which case the source worksheet can be specified - by name or number (starting from 1). - The destination worksheet can be explicitly named, or will follow the name of the source if no name is specified. - The Destination workbook can be given as the path to an XLSx file, an ExcelPackage object or an ExcelWorkbook object. - - .EXAMPLE - C:\> 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 - C:\> 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 - C:\> $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 - C:\> $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 - - #> [CmdletBinding()] param( - #An ExcelWorkbook or ExcelPackage object or the path to an XLSx file where the data is found. [Parameter(Mandatory = $true,ValueFromPipeline=$true)] [Alias('SourceWorkbook')] $SourceObject, - #Name or number (starting from 1) of the worksheet in the source workbook (defaults to 1). $SourceWorkSheet = 1 , - #An ExcelWorkbook or ExcelPackage object or the path to an XLSx file where the data should be copied. [Parameter(Mandatory = $true)] $DestinationWorkbook, - #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. $DestinationWorksheet, - #if the destination is an excel package or a path, launch excel and open the file on completion. [Switch]$Show ) begin { diff --git a/ExportedCommands/Expand-NumberFormat.ps1 b/ExportedCommands/Expand-NumberFormat.ps1 new file mode 100644 index 0000000..2027f47 --- /dev/null +++ b/ExportedCommands/Expand-NumberFormat.ps1 @@ -0,0 +1,77 @@ + +function Expand-NumberFormat { + <# + .SYNOPSIS + Converts short names for number formats to the formatting strings used in Excel + .DESCRIPTION + Where you can type a number format you can write, for example, 'Short-Date' + and the module will translate it into the format string used by Excel. + Some formats, like Short-Date change how they are presented when Excel + loads (so date will use the local ordering of year, month and Day). Other + formats change how they appear when loaded with different cultures + (depending on the country "," or "." or " " may be the thousand seperator + although Excel always stores it as ",") + .EXAMPLE + Expand-NumberFormat percentage + + Returns "0.00%" + .EXAMPLE + Expand-NumberFormat Currency + + Returns the currency format specified in the local regional settings. This + may not be the same as Excel uses. The regional settings set the currency + symbol and then whether it is before or after the number and separated with + a space or not; for negative numbers the number may be wrapped in parentheses + or a - sign might appear before or after the number and symbol. + So this returns $#,##0.00;($#,##0.00) for English US, #,##0.00 €;€#,##0.00- + for French. (Note some Eurozone countries write €1,23 and others 1,23€ ) + In French the decimal point will be rendered as a "," and the thousand + separator as a space. + #> + [cmdletbinding()] + [OutputType([String])] + param ( + #the format string to Expand + $NumberFormat + ) + switch ($NumberFormat) { + "Currency" { + #https://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencynegativepattern(v=vs.110).aspx + $sign = [cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol + switch ([cultureinfo]::CurrentCulture.NumberFormat.CurrencyPositivePattern) { + 0 {$pos = "$Sign#,##0.00" ; break } + 1 {$pos = "#,##0.00$Sign" ; break } + 2 {$pos = "$Sign #,##0.00" ; break } + 3 {$pos = "#,##0.00 $Sign" ; break } + } + switch ([cultureinfo]::CurrentCulture.NumberFormat.CurrencyPositivePattern) { + 0 {return "$pos;($Sign#,##0.00)" } + 1 {return "$pos;-$Sign#,##0.00" } + 2 {return "$pos;$Sign-#,##0.00" } + 3 {return "$pos;$Sign#,##0.00-" } + 4 {return "$pos;(#,##0.00$Sign)" } + 5 {return "$pos;-#,##0.00$Sign" } + 6 {return "$pos;#,##0.00-$Sign" } + 7 {return "$pos;#,##0.00$Sign-" } + 8 {return "$pos;-#,##0.00 $Sign" } + 9 {return "$pos;-$Sign #,##0.00" } + 10 {return "$pos;#,##0.00 $Sign-" } + 11 {return "$pos;$Sign #,##0.00-" } + 12 {return "$pos;$Sign -#,##0.00" } + 13 {return "$pos;#,##0.00- $Sign" } + 14 {return "$pos;($Sign #,##0.00)" } + 15 {return "$pos;(#,##0.00 $Sign)" } + } + } + "Number" {return "0.00" } # format id 2 + "Percentage" {return "0.00%" } # format id 10 + "Scientific" {return "0.00E+00" } # format id 11 + "Fraction" {return "# ?/?" } # format id 12 + "Short Date" {return "mm-dd-yy" } # format id 14 localized on load by Excel. + "Short Time" {return "h:mm" } # format id 20 localized on load by Excel. + "Long Time" {return "h:mm:ss" } # format id 21 localized on load by Excel. + "Date-Time" {return "m/d/yy h:mm"} # format id 22 localized on load by Excel. + "Text" {return "@" } # format ID 49 + Default {return $NumberFormat} + } +} diff --git a/ExportedCommands/Export-Excel.ps1 b/ExportedCommands/Export-Excel.ps1 new file mode 100644 index 0000000..2659470 --- /dev/null +++ b/ExportedCommands/Export-Excel.ps1 @@ -0,0 +1,670 @@ +function Export-Excel { + [CmdletBinding(DefaultParameterSetName = 'Default')] + [OutputType([OfficeOpenXml.ExcelPackage])] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] + Param( + [Parameter(ParameterSetName = 'Default', Position = 0)] + [String]$Path, + [Parameter(Mandatory = $true, ParameterSetName = "Package")] + [OfficeOpenXml.ExcelPackage]$ExcelPackage, + [Parameter(ValueFromPipeline = $true)] + [Alias('TargetData')] + $InputObject, + [Switch]$Calculate, + [Switch]$Show, + [String]$WorksheetName = 'Sheet1', + [Alias("P")] + [String]$Password, + [switch]$ClearSheet, + [switch]$Append, + [String]$Title, + [OfficeOpenXml.Style.ExcelFillStyle]$TitleFillPattern = 'Solid', + [Switch]$TitleBold, + [Int]$TitleSize = 22, + $TitleBackgroundColor, + [Switch]$IncludePivotTable, + [String]$PivotTableName, + [String[]]$PivotRows, + [String[]]$PivotColumns, + $PivotData, + [String[]]$PivotFilter, + [Switch]$PivotDataToColumn, + [Hashtable]$PivotTableDefinition, + [Switch]$IncludePivotChart, + [OfficeOpenXml.Drawing.Chart.eChartType]$ChartType = 'Pie', + [Switch]$NoLegend, + [Switch]$ShowCategory, + [Switch]$ShowPercent, + [Switch]$AutoSize, + $MaxAutoSizeRows = 1000, + [Switch]$NoClobber, + [Switch]$FreezeTopRow, + [Switch]$FreezeFirstColumn, + [Switch]$FreezeTopRowFirstColumn, + [Int[]]$FreezePane, + [Switch]$AutoFilter, + [Switch]$BoldTopRow, + [Switch]$NoHeader, + [ValidateScript( { + if (-not $_) { throw 'RangeName is null or empty.' } + elseif ($_[0] -notmatch '[a-z]') { throw 'RangeName starts with an invalid character.' } + else { $true } + })] + [String]$RangeName, + [Alias('Table')] + $TableName, + [OfficeOpenXml.Table.TableStyles]$TableStyle = [OfficeOpenXml.Table.TableStyles]::Medium6, + [Switch]$Barchart, + [Switch]$PieChart, + [Switch]$LineChart , + [Switch]$ColumnChart , + [Object[]]$ExcelChartDefinition, + [String[]]$HideSheet, + [String[]]$UnHideSheet, + [Switch]$MoveToStart, + [Switch]$MoveToEnd, + $MoveBefore , + $MoveAfter , + [Switch]$KillExcel, + [Switch]$AutoNameRange, + [Int]$StartRow = 1, + [Int]$StartColumn = 1, + [alias('PT')] + [Switch]$PassThru, + [String]$Numberformat = 'General', + [string[]]$ExcludeProperty, + [Switch]$NoAliasOrScriptPropeties, + [Switch]$DisplayPropertySet, + [String[]]$NoNumberConversion, + [Object[]]$ConditionalFormat, + [Object[]]$ConditionalText, + [Object[]]$Style, + [ScriptBlock]$CellStyleSB, + #If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified + [switch]$Activate, + [Parameter(ParameterSetName = 'Default')] + [Switch]$Now, + [Switch]$ReturnRange, + #By default PivotTables have Totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected. + [ValidateSet("Both","Columns","Rows","None")] + [String]$PivotTotals = "Both", + #Included for compatibility - equivalent to -PivotTotals "None" + [Switch]$NoTotalsInPivot, + [Switch]$ReZip + ) + + begin { + $numberRegex = [Regex]'\d' + $isDataTypeValueType = $false + if ($NoClobber) {Write-Warning -Message "-NoClobber parameter is no longer used" } + #Open the file, get the worksheet, and decide where in the sheet we are writing, and if there is a number format to apply. + try { + $script:Header = $null + if ($Append -and $ClearSheet) {throw "You can't use -Append AND -ClearSheet." ; return} + #To force -Now not to format as a table, allow $false in -TableName to be "No table" + $TableName = if ($null -eq $TableName -or ($TableName -is [bool] -and $false -eq $TableName)) { $null } else {[String]$TableName} + if ($Now -or (-not $Path -and -not $ExcelPackage) ) { + if (-not $PSBoundParameters.ContainsKey("Path")) { $Path = [System.IO.Path]::GetTempFileName() -replace '\.tmp', '.xlsx' } + if (-not $PSBoundParameters.ContainsKey("Show")) { $Show = $true } + if (-not $PSBoundParameters.ContainsKey("AutoSize")) { $AutoSize = $true } + #"Now" option will create a table, unless something passed in TableName/Table Style. False in TableName will block autocreation + if (-not $PSBoundParameters.ContainsKey("TableName") -and + -not $PSBoundParameters.ContainsKey("TableStyle") -and + -not $AutoFilter) { + $TableName = 'Table1' + } + } + if ($ExcelPackage) { + $pkg = $ExcelPackage + $Path = $pkg.File + } + Else { $pkg = Open-ExcelPackage -Path $Path -Create -KillExcel:$KillExcel -Password:$Password} + } + catch {throw "Could not open Excel Package $path"} + try { + $params = @{WorksheetName=$WorksheetName} + foreach ($p in @("ClearSheet", "MoveToStart", "MoveToEnd", "MoveBefore", "MoveAfter", "Activate")) {if ($PSBoundParameters[$p]) {$params[$p] = $PSBoundParameters[$p]}} + $ws = $pkg | Add-WorkSheet @params + if ($ws.Name -ne $WorksheetName) { + Write-Warning -Message "The Worksheet name has been changed from $WorksheetName to $($ws.Name), this may cause errors later." + $WorksheetName = $ws.Name + } + } + catch {throw "Could not get worksheet $worksheetname"} + try { + if ($Append -and $ws.Dimension) { + #if there is a title or anything else above the header row, append needs to be combined wih a suitable startrow parameter + $headerRange = $ws.Dimension.Address -replace "\d+$", $StartRow + #using a slightly odd syntax otherwise header ends up as a 2D array + $ws.Cells[$headerRange].Value | ForEach-Object -Begin {$Script:header = @()} -Process {$Script:header += $_ } + #if we did not get AutoNameRange, but headers have ranges of the same name make autoNameRange True, otherwise make it false + if (-not $AutoNameRange) { + $AutoNameRange = $true ; foreach ($h in $header) {if ($ws.names.name -notcontains $h) {$AutoNameRange = $false} } + } + #if we did not get a Rangename but there is a Range which covers the active part of the sheet, set Rangename to that. + if (-not $RangeName -and $ws.names.where({$_.name[0] -match '[a-z]'})) { + $theRange = $ws.names.where({ + ($_.Name[0] -match '[a-z]' ) -and + ($_.Start.Row -eq $StartRow) -and + ($_.Start.Column -eq $StartColumn) -and + ($_.End.Row -eq $ws.Dimension.End.Row) -and + ($_.End.Column -eq $ws.Dimension.End.column) } , 'First', 1) + if ($theRange) {$rangename = $theRange.name} + } + + #if we did not get a table name but there is a table which covers the active part of the sheet, set table name to that, and don't do anything with autofilter + if ($null -eq $TableName -and $ws.Tables.Where({$_.address.address -eq $ws.dimension.address})) { + $TableName = $ws.Tables.Where({$_.address.address -eq $ws.dimension.address},'First', 1).Name + $AutoFilter = $false + } + #if we did not get $autofilter but a filter range is set and it covers the right area, set autofilter to true + elseif (-not $AutoFilter -and $ws.Names['_xlnm._FilterDatabase']) { + if ( ($ws.Names['_xlnm._FilterDatabase'].Start.Row -eq $StartRow) -and + ($ws.Names['_xlnm._FilterDatabase'].Start.Column -eq $StartColumn) -and + ($ws.Names['_xlnm._FilterDatabase'].End.Row -eq $ws.Dimension.End.Row) -and + ($ws.Names['_xlnm._FilterDatabase'].End.Column -eq $ws.Dimension.End.Column) ) {$AutoFilter = $true} + } + + $row = $ws.Dimension.End.Row + Write-Debug -Message ("Appending: headers are " + ($script:Header -join ", ") + " Start row is $row") + if ($Title) {Write-Warning -Message "-Title Parameter is ignored when appending."} + } + elseif ($Title) { + #Can only add a title if not appending! + $Row = $StartRow + $ws.Cells[$Row, $StartColumn].Value = $Title + $ws.Cells[$Row, $StartColumn].Style.Font.Size = $TitleSize + + if ($PSBoundParameters.ContainsKey("TitleBold")) { + #Set title to Bold face font if -TitleBold was specified. + #Otherwise the default will be unbolded. + $ws.Cells[$Row, $StartColumn].Style.Font.Bold = [boolean]$TitleBold + } + if ($TitleBackgroundColor ) { + if ($TitleBackgroundColor -is [string]) {$TitleBackgroundColor = [System.Drawing.Color]::$TitleBackgroundColor } + $ws.Cells[$Row, $StartColumn].Style.Fill.PatternType = $TitleFillPattern + $ws.Cells[$Row, $StartColumn].Style.Fill.BackgroundColor.SetColor($TitleBackgroundColor) + } + $Row ++ ; $startRow ++ + } + else { $Row = $StartRow } + $ColumnIndex = $StartColumn + $Numberformat = Expand-NumberFormat -NumberFormat $Numberformat + if ((-not $ws.Dimension) -and ($Numberformat -ne $ws.Cells.Style.Numberformat.Format)) { + $ws.Cells.Style.Numberformat.Format = $Numberformat + $setNumformat = $false + } + else { $setNumformat = ($Numberformat -ne $ws.Cells.Style.Numberformat.Format) } + } + catch {throw "Failed preparing to export to worksheet '$WorksheetName' to '$Path': $_"} + #region Special case -inputobject passed a dataTable object + <# If inputObject was passed via the pipeline it won't be visible until the process block, we will only see it here if it was passed as a parameter + if it is a data table don't do foreach on it (slow) - put the whole table in and set dates on date columns, + set things up for the end block, and skip the process block #> + if ($InputObject -is [System.Data.DataTable]) { + #don't leave caller with a renamed table, save the name and set it back later + $orginalTableName = $InputObject.TableName + if ($TableName) { + $InputObject.TableName = $TableName + } + while ($InputObject.TableName -in $pkg.Workbook.Worksheets.Tables.name) { + Write-Warning "Table name $($InputObject.TableName) is not unique, adding '_' to it " + $InputObject.TableName += "_" + } + if ($TableName -or $PSBoundParameters.ContainsKey("TableStyle")) { + $TableName = $null + $null = $ws.Cells[$row,$StartColumn].LoadFromDataTable($InputObject, (-not $noHeader),$TableStyle ) + } + else { + $null = $ws.Cells[$row,$StartColumn].LoadFromDataTable($InputObject, (-not $noHeader) ) + } + $InputObject.TableName = $orginalTableName + foreach ($c in $InputObject.Columns.where({$_.datatype -eq [datetime]})) { + Set-ExcelColumn -Worksheet $ws -Column ($c.Ordinal + $StartColumn) -NumberFormat 'Date-Time' + } + foreach ($c in $InputObject.Columns.where({$_.datatype -eq [timespan]})) { + Set-ExcelColumn -Worksheet $ws -Column ($c.Ordinal + $StartColumn) -NumberFormat '[h]:mm:ss' + } + $ColumnIndex += $InputObject.Columns.Count - 1 + if ($noHeader) {$row += $InputObject.Rows.Count -1 } + else {$row += $InputObject.Rows.Count } + $null = $PSBoundParameters.Remove('InputObject') + $firstTimeThru = $false + } + #endregion + else {$firstTimeThru = $true} + } + + process { if ($PSBoundParameters.ContainsKey("InputObject")) { + try { + if ($null -eq $InputObject) {$row += 1} + foreach ($TargetData in $InputObject) { + if ($firstTimeThru) { + $firstTimeThru = $false + $isDataTypeValueType = ($null -eq $TargetData) -or ($TargetData.GetType().name -match 'string|timespan|datetime|bool|byte|char|decimal|double|float|int|long|sbyte|short|uint|ulong|ushort|URI|ExcelHyperLink') + if ($isDataTypeValueType ) { + $script:Header = @(".") # dummy value to make sure we go through the "for each name in $header" + if (-not $Append) {$row -= 1} # By default row will be 1, it is incremented before inserting values (so it ends pointing at final row.); si first data row is 2 - move back up 1 if there is no header . + } + if ($null -ne $TargetData) {Write-Debug "DataTypeName is '$($TargetData.GetType().name)' isDataTypeValueType '$isDataTypeValueType'" } + } + #region Add headers - if we are appending, or we have been through here once already we will have the headers + if (-not $script:Header) { + if ($DisplayPropertySet -and $TargetData.psStandardmembers.DefaultDisplayPropertySet.ReferencedPropertyNames) { + $script:Header = $TargetData.psStandardmembers.DefaultDisplayPropertySet.ReferencedPropertyNames.Where( {$_ -notin $ExcludeProperty}) + } + else { + if ($NoAliasOrScriptPropeties) {$propType = "Property"} else {$propType = "*"} + $script:Header = $TargetData.PSObject.Properties.where( {$_.MemberType -like $propType}).Name + } + foreach ($exclusion in $ExcludeProperty) {$script:Header = $script:Header -notlike $exclusion} + if ($NoHeader) { + # Don't push the headers to the spreadsheet + $Row -= 1 + } + else { + $ColumnIndex = $StartColumn + foreach ($Name in $script:Header) { + $ws.Cells[$Row, $ColumnIndex].Value = $Name + Write-Verbose "Cell '$Row`:$ColumnIndex' add header '$Name'" + $ColumnIndex += 1 + } + } + } + #endregion + #region Add non header values + $Row += 1 + $ColumnIndex = $StartColumn + <# + For each item in the header OR for the Data item if this is a simple Type or data table : + If it is a date insert with one of Excel's built in formats - recognized as "Date and time to be localized" + if it is a timespan insert with a built in format for elapsed hours, minutes and seconds + if its any other numeric insert as is , setting format if need be. + Preserve URI, Insert a data table, convert non string objects to string. + For strings, check for fomula, URI or Number, before inserting as a string (ignore nulls) #> + foreach ($Name in $script:Header) { + if ($isDataTypeValueType) {$v = $TargetData} + else {$v = $TargetData.$Name} + try { + if ($v -is [DateTime]) { + $ws.Cells[$Row, $ColumnIndex].Value = $v + $ws.Cells[$Row, $ColumnIndex].Style.Numberformat.Format = 'm/d/yy h:mm' # This is not a custom format, but a preset recognized as date and localized. + } + elseif ($v -is [TimeSpan]) { + $ws.Cells[$Row, $ColumnIndex].Value = $v + $ws.Cells[$Row, $ColumnIndex].Style.Numberformat.Format = '[h]:mm:ss' + } + elseif ($v -is [System.ValueType]) { + $ws.Cells[$Row, $ColumnIndex].Value = $v + if ($setNumformat) {$ws.Cells[$Row, $ColumnIndex].Style.Numberformat.Format = $Numberformat } + } + elseif ($v -is [uri] ) { + $ws.Cells[$Row, $ColumnIndex].HyperLink = $v + $ws.Cells[$Row, $ColumnIndex].Style.Font.Color.SetColor([System.Drawing.Color]::Blue) + $ws.Cells[$Row, $ColumnIndex].Style.Font.UnderLine = $true + } + elseif ($v -isnot [String] ) { #Other objects or null. + if ($null -ne $v) { $ws.Cells[$Row, $ColumnIndex].Value = $v.toString()} + } + elseif ($v[0] -eq '=') { + $ws.Cells[$Row, $ColumnIndex].Formula = ($v -replace '^=','') + if ($setNumformat) {$ws.Cells[$Row, $ColumnIndex].Style.Numberformat.Format = $Numberformat } + } + elseif ( [System.Uri]::IsWellFormedUriString($v , [System.UriKind]::Absolute) ) { + if ($v -match "^xl://internal/") { + $referenceAddress = $v -replace "^xl://internal/" , "" + $display = $referenceAddress -replace "!A1$" , "" + $h = New-Object -TypeName OfficeOpenXml.ExcelHyperLink -ArgumentList $referenceAddress , $display + $ws.Cells[$Row, $ColumnIndex].HyperLink = $h + } + else {$ws.Cells[$Row, $ColumnIndex].HyperLink = $v } #$ws.Cells[$Row, $ColumnIndex].Value = $v.AbsoluteUri + $ws.Cells[$Row, $ColumnIndex].Style.Font.Color.SetColor([System.Drawing.Color]::Blue) + $ws.Cells[$Row, $ColumnIndex].Style.Font.UnderLine = $true + } + else { + $number = $null + if ( $numberRegex.IsMatch($v) -and # if it contains digit(s) - this syntax is quicker than -match for many items and cuts out slow checks for non numbers + $NoNumberConversion -ne '*' -and # and NoNumberConversion isn't specified + $NoNumberConversion -notcontains $Name -and + [Double]::TryParse($v, [System.Globalization.NumberStyles]::Any, [System.Globalization.NumberFormatInfo]::CurrentInfo, [Ref]$number) + ) { + $ws.Cells[$Row, $ColumnIndex].Value = $number + if ($setNumformat) {$ws.Cells[$Row, $ColumnIndex].Style.Numberformat.Format = $Numberformat } + } + else { + $ws.Cells[$Row, $ColumnIndex].Value = $v + } + + } + } + catch {Write-Warning -Message "Could not insert the '$Name' property at Row $Row, Column $ColumnIndex"} + $ColumnIndex += 1 + } + $ColumnIndex -= 1 # column index will be the last column whether isDataTypeValueType was true or false + #endregion + } + } + catch {throw "Failed exporting data to worksheet '$WorksheetName' to '$Path': $_" } + + }} + + end { + if ($firstTimeThru -and $ws.Dimension) { + $LastRow = $ws.Dimension.End.Row + $LastCol = $ws.Dimension.End.Column + $endAddress = $ws.Dimension.End.Address + } + else { + $LastRow = $Row + $LastCol = $ColumnIndex + $endAddress = [OfficeOpenXml.ExcelAddress]::GetAddress($LastRow , $LastCol) + } + $startAddress = [OfficeOpenXml.ExcelAddress]::GetAddress($StartRow, $StartColumn) + $dataRange = "{0}:{1}" -f $startAddress, $endAddress + + Write-Debug "Data Range '$dataRange'" + if ($AutoNameRange) { + try { + if (-not $script:header) { + # if there aren't any headers, use the the first row of data to name the ranges: this is the last point that headers will be used. + $headerRange = $ws.Dimension.Address -replace "\d+$", $StartRow + #using a slightly odd syntax otherwise header ends up as a 2D array + $ws.Cells[$headerRange].Value | ForEach-Object -Begin {$Script:header = @()} -Process {$Script:header += $_ } + if ($PSBoundParameters.ContainsKey($TargetData)) { #if Export was called with data that writes no header start the range at $startRow ($startRow is data) + $targetRow = $StartRow + } + else { $targetRow = $StartRow + 1 } #if Export was called without data to add names (assume $startRow is a header) or... + } # ... called with data that writes a header, then start the range at $startRow + 1 + else { $targetRow = $StartRow + 1 } + + #Dimension.start.row always seems to be one so we work out the target row + #, but start.column is the first populated one and .Columns is the count of populated ones. + # if we have 5 columns from 3 to 8, headers are numbered 0..4, so that is in the for loop and used for getting the name... + # but we have to add the start column on when referencing positions + foreach ($c in 0..($LastCol - $StartColumn)) { + $targetRangeName = @($script:Header)[$c] #Let Add-ExcelName fix (and warn about) bad names + Add-ExcelName -RangeName $targetRangeName -Range $ws.Cells[$targetRow, ($StartColumn + $c ), $LastRow, ($StartColumn + $c )] + try {#this test can throw with some names, surpress any error + if ([OfficeOpenXml.FormulaParsing.ExcelUtilities.ExcelAddressUtil]::IsValidAddress(($targetRangeName -replace '\W' , '_' ))) { + Write-Warning -Message "AutoNameRange: Property name '$targetRangeName' is also a valid Excel address and may cause issues. Consider renaming the property." + } + } + Catch { + Write-Warning -Message "AutoNameRange: Testing '$targetRangeName' caused an error. This should be harmless, but a change of property name may be needed.." + } + } + } + catch {Write-Warning -Message "Failed adding named ranges to worksheet '$WorksheetName': $_" } + } + #Empty string is not allowed as a name for ranges or tables. + if ($RangeName) { Add-ExcelName -Range $ws.Cells[$dataRange] -RangeName $RangeName} + + #Allow table to be inserted by specifying Name, or Style or both; only process autoFilter if there is no table (they clash). + if ($null -ne $TableName) { + Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $PSBoundParameters['TableName'] -TableStyle $TableStyle + } + elseif ($PSBoundParameters.ContainsKey('TableStyle')) { + Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName "" -TableStyle $TableStyle + } + elseif ($AutoFilter) { + try { + $ws.Cells[$dataRange].AutoFilter = $true + Write-Verbose -Message "Enabled autofilter. " + } + catch {Write-Warning -Message "Failed adding autofilter to worksheet '$WorksheetName': $_"} + } + + if ($PivotTableDefinition) { + foreach ($item in $PivotTableDefinition.GetEnumerator()) { + $params = $item.value + if ($Activate) {$params.Activate = $true } + if ($params.keys -notcontains 'SourceRange' -and + ($params.Keys -notcontains 'SourceWorkSheet' -or $params.SourceWorkSheet -eq $WorksheetName)) {$params.SourceRange = $dataRange} + if ($params.Keys -notcontains 'SourceWorkSheet') {$params.SourceWorkSheet = $ws } + if ($params.Keys -notcontains 'NoTotalsInPivot' -and $NoTotalsInPivot ) {$params.PivotTotals = 'None'} + if ($params.Keys -notcontains 'PivotTotals' -and $PivotTotals ) {$params.PivotTotals = $PivotTotals} + if ($params.Keys -notcontains 'PivotDataToColumn' -and $PivotDataToColumn) {$params.PivotDataToColumn = $true} + + Add-PivotTable -ExcelPackage $pkg -PivotTableName $item.key @Params + } + } + if ($IncludePivotTable -or $IncludePivotChart) { + $params = @{ + 'SourceRange' = $dataRange + } + if ($PivotTableName -and ($pkg.workbook.worksheets.tables.name -contains $PivotTableName)) { + Write-Warning -Message "The selected PivotTable name '$PivotTableName' is already used as a table name. Adding a suffix of 'Pivot'." + $PivotTableName += 'Pivot' + } + + if ($PivotTableName) {$params.PivotTableName = $PivotTableName} + else {$params.PivotTableName = $WorksheetName + 'PivotTable'} + if ($Activate) {$params.Activate = $true } + if ($PivotFilter) {$params.PivotFilter = $PivotFilter} + if ($PivotRows) {$params.PivotRows = $PivotRows} + if ($PivotColumns) {$Params.PivotColumns = $PivotColumns} + if ($PivotData) {$Params.PivotData = $PivotData} + if ($NoTotalsInPivot) {$params.PivotTotals = "None" } + Elseif ($PivotTotals) {$params.PivotTotals = $PivotTotals} + if ($PivotDataToColumn) {$params.PivotDataToColumn = $true} + if ($IncludePivotChart) { + $params.IncludePivotChart = $true + $Params.ChartType = $ChartType + if ($ShowCategory) {$params.ShowCategory = $true} + if ($ShowPercent) {$params.ShowPercent = $true} + if ($NoLegend) {$params.NoLegend = $true} + } + Add-PivotTable -ExcelPackage $pkg -SourceWorkSheet $ws @params + } + + try { + #Allow single switch or two seperate ones. + if ($FreezeTopRowFirstColumn -or ($FreezeTopRow -and $FreezeFirstColumn)) { + $ws.View.FreezePanes(2, 2) + Write-Verbose -Message "Froze top row and first column" + } + elseif ($FreezeTopRow) { + $ws.View.FreezePanes(2, 1) + Write-Verbose -Message "Froze top row" + } + elseif ($FreezeFirstColumn) { + $ws.View.FreezePanes(1, 2) + Write-Verbose -Message "Froze first column" + } + #Must be 1..maxrows or and array of 1..maxRows,1..MaxCols + if ($FreezePane) { + $freezeRow, $freezeColumn = $FreezePane + if (-not $freezeColumn -or $freezeColumn -eq 0) { + $freezeColumn = 1 + } + + if ($freezeRow -ge 1) { + $ws.View.FreezePanes($freezeRow, $freezeColumn) + Write-Verbose -Message "Froze panes at row $freezeRow and column $FreezeColumn" + } + } + } + catch {Write-Warning -Message "Failed adding Freezing the panes in worksheet '$WorksheetName': $_"} + + if ($PSBoundParameters.ContainsKey("BoldTopRow")) { #it sets bold as far as there are populated cells: for whole row could do $ws.row($x).style.font.bold = $true + try { + if ($Title) { + $range = $ws.Dimension.Address -replace '\d+', ($StartRow + 1) + } + else { + $range = $ws.Dimension.Address -replace '\d+', $StartRow + } + $ws.Cells[$range].Style.Font.Bold = [boolean]$BoldTopRow + Write-Verbose -Message "Set $range font style to bold." + } + catch {Write-Warning -Message "Failed setting the top row to bold in worksheet '$WorksheetName': $_"} + } + if ($AutoSize -and -not $env:NoAutoSize) { + try { + #Don't fit the all the columns in the sheet; if we are adding cells beside things with hidden columns, that unhides them + if ($MaxAutoSizeRows -and $MaxAutoSizeRows -lt $LastRow ) { + $AutosizeRange = [OfficeOpenXml.ExcelAddress]::GetAddress($startRow,$StartColumn, $MaxAutoSizeRows , $LastCol) + $ws.Cells[$AutosizeRange].AutoFitColumns() + } + else {$ws.Cells[$dataRange].AutoFitColumns() } + Write-Verbose -Message "Auto-sized columns" + } + catch { Write-Warning -Message "Failed autosizing columns of worksheet '$WorksheetName': $_"} + } + elseif ($AutoSize) {Write-Warning -Message "Auto-fitting columns is not available with this OS configuration." } + + foreach ($Sheet in $HideSheet) { + try { + $pkg.Workbook.WorkSheets.Where({$_.Name -like $sheet}) | ForEach-Object { + $_.Hidden = 'Hidden' + Write-verbose -Message "Sheet '$($_.Name)' Hidden." + } + } + catch {Write-Warning -Message "Failed hiding worksheet '$sheet': $_"} + } + foreach ($Sheet in $UnHideSheet) { + try { + $pkg.Workbook.WorkSheets.Where({$_.Name -like $sheet}) | ForEach-Object { + $_.Hidden = 'Visible' + Write-verbose -Message "Sheet '$($_.Name)' shown" + } + } + catch {Write-Warning -Message "Failed showing worksheet '$sheet': $_"} + } + if (-not $pkg.Workbook.Worksheets.Where({$_.Hidden -eq 'visible'})) { + Write-Verbose -Message "No Sheets were left visible, making $WorksheetName visible" + $ws.Hidden = 'Visible' + } + + foreach ($chartDef in $ExcelChartDefinition) { + if ($chartDef -is [System.Management.Automation.PSCustomObject]) { + $params = @{} + $chartDef.PSObject.Properties | ForEach-Object {if ( $null -ne $_.value) {$params[$_.name] = $_.value}} + Add-ExcelChart -Worksheet $ws @params + } + elseif ($chartDef -is [hashtable] -or $chartDef -is[System.Collections.Specialized.OrderedDictionary]) { + Add-ExcelChart -Worksheet $ws @chartDef + } + } + + if ($Calculate) { + try { [OfficeOpenXml.CalculationExtension]::Calculate($ws) } + catch { Write-Warning "One or more errors occured while calculating, save will continue, but there may be errors in the workbook. $_"} + } + + if ($Barchart -or $PieChart -or $LineChart -or $ColumnChart) { + if ($NoHeader) {$FirstDataRow = $startRow} + else {$FirstDataRow = $startRow + 1 } + $range = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, $startColumn, $FirstDataRow, $lastCol ) + $xCol = $ws.cells[$range] | Where-Object {$_.value -is [string] } | ForEach-Object {$_.start.column} | Sort-Object | Select-Object -first 1 + if (-not $xcol) { + $xcol = $StartColumn + $range = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, ($startColumn +1), $FirstDataRow, $lastCol ) + } + $yCol = $ws.cells[$range] | Where-Object {$_.value -is [valueType] -or $_.Formula } | ForEach-Object {$_.start.column} | Sort-Object | Select-Object -first 1 + if (-not ($xCol -and $ycol)) { Write-Warning -Message "Can't identify a string column and a number column to use as chart labels and data. "} + else { + $params = @{ + XRange = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, $xcol , $lastrow, $xcol) + YRange = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, $ycol , $lastrow, $ycol) + Title = '' + Column = ($lastCol +1) + Width = 800 + } + if ($ShowPercent) {$params["ShowPercent"] = $true} + if ($ShowCategory) {$params["ShowCategory"] = $true} + if ($NoLegend) {$params["NoLegend"] = $true} + if (-not $NoHeader) {$params["SeriesHeader"] = $ws.Cells[$startRow, $YCol].Value} + if ($ColumnChart) {$Params["chartType"] = "ColumnStacked" } + elseif ($Barchart) {$Params["chartType"] = "BarStacked" } + elseif ($PieChart) {$Params["chartType"] = "PieExploded3D" } + elseif ($LineChart) {$Params["chartType"] = "Line" } + + Add-ExcelChart -Worksheet $ws @params + } + } + + # It now doesn't matter if the conditional formating rules are passed in $conditionalText or $conditional format. + # Just one with an alias for compatiblity it will break things for people who are using both at once + foreach ($c in (@() + $ConditionalText + $ConditionalFormat) ) { + try { + #we can take an object with a .ConditionalType property made by New-ConditionalText or with a .Formatter Property made by New-ConditionalFormattingIconSet or a hash table + if ($c.ConditionalType) { + $cfParams = @{RuleType = $c.ConditionalType; ConditionValue = $c.Text ; + BackgroundColor = $c.BackgroundColor; BackgroundPattern = $c.PatternType ; + ForeGroundColor = $c.ConditionalTextColor} + if ($c.Range) {$cfParams.Range = $c.Range} + else {$cfParams.Range = $ws.Dimension.Address } + Add-ConditionalFormatting -WorkSheet $ws @cfParams + Write-Verbose -Message "Added conditional formatting to range $($c.range)" + } + elseif ($c.formatter) { + switch ($c.formatter) { + "ThreeIconSet" {Add-ConditionalFormatting -WorkSheet $ws -ThreeIconsSet $c.IconType -range $c.range -reverse:$c.reverse } + "FourIconSet" {Add-ConditionalFormatting -WorkSheet $ws -FourIconsSet $c.IconType -range $c.range -reverse:$c.reverse } + "FiveIconSet" {Add-ConditionalFormatting -WorkSheet $ws -FiveIconsSet $c.IconType -range $c.range -reverse:$c.reverse } + } + Write-Verbose -Message "Added conditional formatting to range $($c.range)" + } + elseif ($c -is [hashtable] -or $c -is[System.Collections.Specialized.OrderedDictionary]) { + if (-not $c.Range -or $c.Address) {$c.Address = $ws.Dimension.Address } + Add-ConditionalFormatting -WorkSheet $ws @c + } + } + catch {throw "Error applying conditional formatting to worksheet $_"} + } + foreach ($s in $Style) { + if (-not $s.Range) {$s["Range"] = $ws.Dimension.Address } + Set-ExcelRange -WorkSheet $ws @s + } + if ($CellStyleSB) { + try { + $TotalRows = $ws.Dimension.Rows + $LastColumn = $ws.Dimension.Address -replace "^.*:(\w*)\d+$" , '$1' + & $CellStyleSB $ws $TotalRows $LastColumn + } + catch {Write-Warning -Message "Failed processing CellStyleSB in worksheet '$WorksheetName': $_"} + } + + #Can only add password, may want to support -password $Null removing password. + if ($Password) { + try { + $ws.Protection.SetPassword($Password) + Write-Verbose -Message 'Set password on workbook' + } + + catch {throw "Failed setting password for worksheet '$WorksheetName': $_"} + } + + if ($PassThru) { $pkg } + else { + if ($ReturnRange) {$dataRange } + + if ($Password) { $pkg.Save($Password) } + else { $pkg.Save() } + Write-Verbose -Message "Saved workbook $($pkg.File)" + if ($ReZip) { + Write-Verbose -Message "Re-Zipping $($pkg.file) using .NET ZIP library" + try { + Add-Type -AssemblyName 'System.IO.Compression.Filesystem' -ErrorAction stop + } + catch { + Write-Error "The -ReZip parameter requires .NET Framework 4.5 or later to be installed. Recommend to install Powershell v4+" + continue + } + try { + $TempZipPath = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath ([System.IO.Path]::GetRandomFileName()) + $null = [io.compression.zipfile]::ExtractToDirectory($pkg.File, $TempZipPath) + Remove-Item $pkg.File -Force + $null = [io.compression.zipfile]::CreateFromDirectory($TempZipPath, $pkg.File) + } + catch {throw "Error resizipping $path : $_"} + } + + $pkg.Dispose() + + if ($Show) { Invoke-Item $Path } + } + + } +} diff --git a/ExportedCommands/Export-ExcelSheet.md b/ExportedCommands/Export-ExcelSheet.md new file mode 100644 index 0000000..765dea7 --- /dev/null +++ b/ExportedCommands/Export-ExcelSheet.md @@ -0,0 +1,138 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Export-ExcelSheet + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Export-ExcelSheet [-Path] [[-OutputPath] ] [[-SheetName] ] [[-Encoding] ] [[-Extension] ] [[-Delimiter] ] [] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -Delimiter +{{ Fill Delimiter Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: +Accepted values: ;, , + +Required: False +Position: 5 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Encoding +{{ Fill Encoding Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: +Accepted values: ASCII, BigEndianUniCode, Default, OEM, UniCode, UTF32, UTF7, UTF8 + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Extension +{{ Fill Extension Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: +Accepted values: .txt, .log, .csv + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OutputPath +{{ Fill OutputPath Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Path +{{ Fill Path Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SheetName +{{ Fill SheetName Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/Export-ExcelSheet.ps1 b/ExportedCommands/Export-ExcelSheet.ps1 similarity index 100% rename from Export-ExcelSheet.ps1 rename to ExportedCommands/Export-ExcelSheet.ps1 diff --git a/ExportedCommands/Export-MultipleExcelSheets.md b/ExportedCommands/Export-MultipleExcelSheets.md new file mode 100644 index 0000000..e30679b --- /dev/null +++ b/ExportedCommands/Export-MultipleExcelSheets.md @@ -0,0 +1,120 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Export-MultipleExcelSheets + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Export-MultipleExcelSheets [-Path] [-InfoMap] [[-Password] ] [-Show] [-AutoSize] [] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -AutoSize +{{ Fill AutoSize Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InfoMap +{{ Fill InfoMap Description }} + +```yaml +Type: Hashtable +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Password +{{ Fill Password Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Path +{{ Fill Path Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Show +{{ Fill Show Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/ExportedCommands/Export-MultipleExcelSheets.ps1 b/ExportedCommands/Export-MultipleExcelSheets.ps1 new file mode 100644 index 0000000..378ceb8 --- /dev/null +++ b/ExportedCommands/Export-MultipleExcelSheets.ps1 @@ -0,0 +1,27 @@ +function Export-MultipleExcelSheets { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] + param( + [Parameter(Mandatory = $true)] + $Path, + [Parameter(Mandatory = $true)] + [hashtable]$InfoMap, + [string]$Password, + [Switch]$Show, + [Switch]$AutoSize + ) + + $parameters = @{ } + $PSBoundParameters + $parameters.Remove("InfoMap") + $parameters.Remove("Show") + + $parameters.Path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path) + + foreach ($entry in $InfoMap.GetEnumerator()) { + Write-Progress -Activity "Exporting" -Status "$($entry.Key)" + $parameters.WorkSheetname = $entry.Key + + & $entry.Value | Export-Excel @parameters + } + + if ($Show) { Invoke-Item $Path } +} diff --git a/Export-StocksToExcel.ps1 b/ExportedCommands/Export-StocksToExcel.ps1 similarity index 100% rename from Export-StocksToExcel.ps1 rename to ExportedCommands/Export-StocksToExcel.ps1 diff --git a/ExportedCommands/Get-ExcelColumnName.md b/ExportedCommands/Get-ExcelColumnName.md new file mode 100644 index 0000000..85a891f --- /dev/null +++ b/ExportedCommands/Get-ExcelColumnName.md @@ -0,0 +1,60 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Get-ExcelColumnName + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Get-ExcelColumnName [[-columnNumber] ] [] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -columnNumber +{{ Fill columnNumber Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### System.Object + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/Get-ExcelColumnName.ps1 b/ExportedCommands/Get-ExcelColumnName.ps1 similarity index 100% rename from Get-ExcelColumnName.ps1 rename to ExportedCommands/Get-ExcelColumnName.ps1 diff --git a/Get-ExcelSheetInfo.ps1 b/ExportedCommands/Get-ExcelSheetInfo.ps1 similarity index 61% rename from Get-ExcelSheetInfo.ps1 rename to ExportedCommands/Get-ExcelSheetInfo.ps1 index edccf04..f4fb88a 100644 --- a/Get-ExcelSheetInfo.ps1 +++ b/ExportedCommands/Get-ExcelSheetInfo.ps1 @@ -1,22 +1,4 @@ Function Get-ExcelSheetInfo { - <# - .SYNOPSIS - Get worksheet names and their indices of an Excel workbook. - .DESCRIPTION - The Get-ExcelSheetInfo cmdlet gets worksheet names and their indices of an Excel workbook. - .PARAMETER Path - Specifies the path to the Excel file. This parameter is required. - .EXAMPLE - Get-ExcelSheetInfo .\Test.xlsx - - .NOTES - CHANGELOG - 2016/01/07 Added Created by Johan Akerstrom (https://github.com/CosmosKey) - - .LINK - https://github.com/dfinke/ImportExcel - #> - [CmdletBinding()] param( [Alias('FullName')] diff --git a/ExportedCommands/Get-ExcelWorkbookInfo.ps1 b/ExportedCommands/Get-ExcelWorkbookInfo.ps1 new file mode 100644 index 0000000..a064314 --- /dev/null +++ b/ExportedCommands/Get-ExcelWorkbookInfo.ps1 @@ -0,0 +1,27 @@ +Function Get-ExcelWorkbookInfo { + [CmdletBinding()] + Param ( + [Alias('FullName')] + [Parameter(ValueFromPipelineByPropertyName=$true, ValueFromPipeline=$true, Mandatory=$true)] + [String]$Path + ) + + Process { + Try { + $Path = (Resolve-Path $Path).ProviderPath + + $stream = New-Object -TypeName System.IO.FileStream -ArgumentList $Path,'Open','Read','ReadWrite' + $xl = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $stream + $workbook = $xl.Workbook + $workbook.Properties + + $stream.Close() + $stream.Dispose() + $xl.Dispose() + $xl = $null + } + Catch { + throw "Failed retrieving Excel workbook information for '$Path': $_" + } + } +} diff --git a/ExportedCommands/Get-HtmlTable.md b/ExportedCommands/Get-HtmlTable.md new file mode 100644 index 0000000..7fe2d1a --- /dev/null +++ b/ExportedCommands/Get-HtmlTable.md @@ -0,0 +1,121 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Get-HtmlTable + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Get-HtmlTable [-url] [[-tableIndex] ] [[-Header] ] [[-FirstDataRow] ] + [-UseDefaultCredentials] [] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -FirstDataRow +{{ Fill FirstDataRow Description }} + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Header +{{ Fill Header Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UseDefaultCredentials +{{ Fill UseDefaultCredentials Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -tableIndex +{{ Fill tableIndex Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -url +{{ Fill url Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/Get-HtmlTable.ps1 b/ExportedCommands/Get-HtmlTable.ps1 similarity index 100% rename from Get-HtmlTable.ps1 rename to ExportedCommands/Get-HtmlTable.ps1 diff --git a/ExportedCommands/Get-Range.md b/ExportedCommands/Get-Range.md new file mode 100644 index 0000000..9d37398 --- /dev/null +++ b/ExportedCommands/Get-Range.md @@ -0,0 +1,87 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Get-Range + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Get-Range [[-start] ] [[-stop] ] [[-step] ] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -start +{{ Fill start Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -step +{{ Fill step Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -stop +{{ Fill stop Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/Get-Range.ps1 b/ExportedCommands/Get-Range.ps1 similarity index 100% rename from Get-Range.ps1 rename to ExportedCommands/Get-Range.ps1 diff --git a/ExportedCommands/Get-XYRange.md b/ExportedCommands/Get-XYRange.md new file mode 100644 index 0000000..3d0af44 --- /dev/null +++ b/ExportedCommands/Get-XYRange.md @@ -0,0 +1,57 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Get-XYRange + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Get-XYRange [[-targetData] ] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -targetData +{{ Fill targetData Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/Get-XYRange.ps1 b/ExportedCommands/Get-XYRange.ps1 similarity index 100% rename from Get-XYRange.ps1 rename to ExportedCommands/Get-XYRange.ps1 diff --git a/ExportedCommands/Import-Excel.ps1 b/ExportedCommands/Import-Excel.ps1 new file mode 100644 index 0000000..0eae2e3 --- /dev/null +++ b/ExportedCommands/Import-Excel.ps1 @@ -0,0 +1,399 @@ + +function Import-Excel { + <# + .SYNOPSIS + Create custom objects from the rows in an Excel worksheet. + + .DESCRIPTION + The Import-Excel cmdlet creates custom objects from the rows in an Excel worksheet. Each row represents one object. All of this is possible without installing Microsoft Excel and by using the .NET library ‘EPPLus.dll’. + + By default, the property names of the objects are retrieved from the column headers. Because an object cannot have a blank property name, only columns with column headers will be imported. + + If the default behavior is not desired and you want to import the complete worksheet ‘as is’, the parameter ‘-NoHeader’ can be used. In case you want to provide your own property names, you can use the parameter ‘-HeaderName’. + + .PARAMETER Path + Specifies the path to the Excel file. + .PARAMETER ExcelPackage + Instead of specifying a path provides an Excel Package object (from Open-ExcelPackage) + Using this avoids re-reading the whole file when importing multiple parts of it. + To allow multiple read operations Import-Excel does NOT close the package, and you should use + Close-ExcelPackage -noSave to close it. + .PARAMETER WorksheetName + Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported. + + .PARAMETER DataOnly + Import only rows and columns that contain data, empty rows and empty columns are not imported. + + .PARAMETER HeaderName + Specifies custom property names to use, instead of the values defined in the column headers of the TopRow. + If you provide fewer header names than there are columns of data in the worksheet, then data will only be imported from that number of columns - the others will be ignored. + If you provide more header names than there are columns of data in the worksheet, it will result in blank properties being added to the objects returned. + + .PARAMETER NoHeader + Automatically generate property names (P1, P2, P3, ..) instead of the ones defined in the column headers of the TopRow. + This switch is best used when you want to import the complete worksheet ‘as is’ and are not concerned with the property names. + + .PARAMETER StartRow + The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. + When the parameters ‘-NoHeader’ and ‘-HeaderName’ are not provided, this row will contain the column headers that will be used as property names. When one of both parameters are provided, the property names are automatically created and this row will be treated as a regular row containing data. + + .PARAMETER EndRow + By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row. + + .PARAMETER StartColumn + The number of the first column to read data from (1 by default). + + .PARAMETER EndColumn + By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number. + + .PARAMETER AsText + Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. * is supported as a wildcard. + + .PARAMETER Password + Accepts a string that will be used to open a password protected Excel file. + + .EXAMPLE + 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. + + ---------------------------------------------- + | 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 + + 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 + Import 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, ..). + + ---------------------------------------------- + | 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 -NoHeader + + P1: First Name + P2: + P3: Address + + P1: Chuck + P2: Norris + P3: California + + P1: Jean-Claude + P2: Vandamme + P3: Brussels + + Notice that the column header (row 1) is imported as an object too. + + .EXAMPLE + Import data from an Excel worksheet. One object is created for each row. The property names of the objects consist of the names 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. + + ---------------------------------------------------------- + | 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 C:\> 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 : + + 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 blanc for all objects. + + .EXAMPLE + Import data from an Excel worksheet. One object is created for each row. The property names of the objects are automatically generated by using the switch ‘-NoHeader’ (P1, P@, P#, ..). The switch ‘-DataOnly’ will speed up the import because empty rows and empty columns are not imported. + + ---------------------------------------------------------- + | 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 C:\> 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 + + Notice that empty rows and empty columns are not imported. + + .EXAMPLE + 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. + + ---------------------------------------------------------- + | File: Movies.xlsx - Sheet: Actors | + ---------------------------------------------------------- + | A B C D | + |1 Chuck Norris California | + |2 | + |3 Jean-Claude Vandamme Brussels | + ---------------------------------------------------------- + + PS C:\> Import-Excel -Path 'C:\Movies.xlsx' -WorkSheetname Actors -DataOnly -HeaderName 'FirstName', 'SecondName', 'City' –StartRow 2 + + FirstName : Jean-Claude + SecondName: Vandamme + City : Brussels + + 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 + > + 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 pipe the data to the Write-SqlTableData 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. + + .LINK + https://github.com/dfinke/ImportExcel + + .NOTES + #> + + [CmdLetBinding()] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] + Param ( + [Alias('FullName')] + [Parameter(ParameterSetName = "PathA", Mandatory, ValueFromPipelineByPropertyName, ValueFromPipeline, Position = 0 )] + [Parameter(ParameterSetName = "PathB", Mandatory, ValueFromPipelineByPropertyName, ValueFromPipeline, Position = 0 )] + [Parameter(ParameterSetName = "PathC", Mandatory, ValueFromPipelineByPropertyName, ValueFromPipeline, Position = 0 )] + [String]$Path, + [Parameter(ParameterSetName = "PackageA", Mandatory)] + [Parameter(ParameterSetName = "PackageB", Mandatory)] + [Parameter(ParameterSetName = "PackageC", Mandatory)] + [OfficeOpenXml.ExcelPackage]$ExcelPackage, + [Alias('Sheet')] + [Parameter(Position = 1)] + [ValidateNotNullOrEmpty()] + [String]$WorksheetName, + [Parameter(ParameterSetName = 'PathB' , Mandatory)] + [Parameter(ParameterSetName = 'PackageB', Mandatory)] + [String[]]$HeaderName , + [Parameter(ParameterSetName = 'PathC' , Mandatory)] + [Parameter(ParameterSetName = 'PackageC', Mandatory)] + [Switch]$NoHeader , + [Alias('HeaderRow', 'TopRow')] + [ValidateRange(1, 9999)] + [Int]$StartRow = 1, + [Alias('StopRow', 'BottomRow')] + [Int]$EndRow , + [Alias('LeftColumn')] + [Int]$StartColumn = 1, + [Alias('RightColumn')] + [Int]$EndColumn , + [Switch]$DataOnly, + [string[]]$AsText, + [ValidateNotNullOrEmpty()] + [String]$Password + ) + begin { + $sw = [System.Diagnostics.Stopwatch]::StartNew() + + Function Get-PropertyNames { + <# + .SYNOPSIS + Create objects containing the column number and the column name for each of the different header types. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = "Name would be incorrect, and command is not exported")] + Param ( + [Parameter(Mandatory)] + [Int[]]$Columns, + [Parameter(Mandatory)] + [Int]$StartRow + ) + + Try { + if ($HeaderName) { + $i = 0 + foreach ($H in $HeaderName) { + $H | Select-Object @{N = 'Column'; E = { $Columns[$i] } }, @{N = 'Value'; E = { $H } } + $i++ + } + } + elseif ($NoHeader) { + $i = 0 + foreach ($C in $Columns) { + $i++ + $C | Select-Object @{N = 'Column'; E = { $_ } }, @{N = 'Value'; E = { 'P' + $i } } + } + } + + else { + if ($StartRow -lt 1) { + throw 'The top row can never be less than 1 when we need to retrieve headers from the worksheet.' ; return + } + + foreach ($C in $Columns) { + $Worksheet.Cells[$StartRow, $C] | Where-Object { $_.Value } | Select-Object @{N = 'Column'; E = { $C } }, Value + } + } + } + Catch { + throw "Failed creating property names: $_" ; return + } + } + } + + process { + if ($path) { + $extension = [System.IO.Path]::GetExtension($Path) + if ($extension -notmatch '.xlsx$|.xlsm$') { + throw "Import-Excel does not support reading this extension type $($extension)" + } + + $resolvedPath = (Resolve-Path $Path -ErrorAction SilentlyContinue) + if ($resolvedPath) { + $Path = $resolvedPath.ProviderPath + } + else { + throw "'$($Path)' file not found" + } + + $stream = New-Object -TypeName System.IO.FileStream -ArgumentList $Path, 'Open', 'Read', 'ReadWrite' + $ExcelPackage = New-Object -TypeName OfficeOpenXml.ExcelPackage + if ($Password) { $ExcelPackage.Load($stream, $Password) } + else { $ExcelPackage.Load($stream) } + } + try { + #Select worksheet + if (-not $WorksheetName) { $Worksheet = $ExcelPackage.Workbook.Worksheets[1] } + elseif (-not ($Worksheet = $ExcelPackage.Workbook.Worksheets[$WorkSheetName])) { + throw "Worksheet '$WorksheetName' not found, the workbook only contains the worksheets '$($ExcelPackage.Workbook.Worksheets)'. If you only wish to select the first worksheet, please remove the '-WorksheetName' parameter." ; return + } + + Write-Debug $sw.Elapsed.TotalMilliseconds + #region Get rows and columns + #If we are doing dataonly it is quicker to work out which rows to ignore before processing the cells. + if (-not $EndRow ) { $EndRow = $Worksheet.Dimension.End.Row } + if (-not $EndColumn) { $EndColumn = $Worksheet.Dimension.End.Column } + $endAddress = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R[$EndRow]C[$EndColumn]", 0, 0) + if ($DataOnly) { + #If we are using headers startrow will be the header-row so examine data from startRow + 1, + if ($NoHeader) { $range = "A" + ($StartRow ) + ":" + $endAddress } + else { $range = "A" + ($StartRow + 1 ) + ":" + $endAddress } + #We're going to look at every cell and build 2 hash tables holding rows & columns which contain data. + #Want to Avoid 'select unique' operations & large Sorts, becuse time time taken increases with square + #of number of items (PS uses heapsort at large size). Instead keep a list of what we have seen, + #using Hash tables: "we've seen it" is all we need, no need to worry about "seen it before" / "Seen it many times". + $colHash = @{ } + $rowHash = @{ } + foreach ($cell in $Worksheet.Cells[$range]) { + if ($null -ne $cell.Value ) { $colHash[$cell.Start.Column] = 1; $rowHash[$cell.Start.row] = 1 } + } + $rows = ( $StartRow..$EndRow ).Where( { $rowHash[$_] }) + $columns = ($StartColumn..$EndColumn).Where( { $colHash[$_] }) + } + else { + $Columns = $StartColumn .. $EndColumn ; if ($StartColumn -gt $EndColumn) { Write-Warning -Message "Selecting columns $StartColumn to $EndColumn might give odd results." } + if ($NoHeader) { $Rows = $StartRow..$EndRow ; if ($StartRow -gt $EndRow) { Write-Warning -Message "Selecting rows $StartRow to $EndRow might give odd results." } } + elseif ($HeaderName) { $Rows = $StartRow..$EndRow } + else { $Rows = (1 + $StartRow)..$EndRow } # ; if ($StartRow -ge $EndRow) { Write-Warning -Message "Selecting $StartRow as the header with data in $(1+$StartRow) to $EndRow might give odd results." } } + } + #endregion + #region Create property names + if ((-not $Columns) -or (-not ($PropertyNames = Get-PropertyNames -Columns $Columns -StartRow $StartRow))) { + throw "No column headers found on top row '$StartRow'. If column headers in the worksheet are not a requirement then please use the '-NoHeader' or '-HeaderName' parameter."; return + } + if ($Duplicates = $PropertyNames | Group-Object Value | Where-Object Count -GE 2) { + throw "Duplicate column headers found on row '$StartRow' in columns '$($Duplicates.Group.Column)'. Column headers must be unique, if this is not a requirement please use the '-NoHeader' or '-HeaderName' parameter."; return + } + #endregion + Write-Debug $sw.Elapsed.TotalMilliseconds + if (-not $Rows) { + Write-Warning "Worksheet '$WorksheetName' in workbook '$Path' contains no data in the rows after top row '$StartRow'" + } + else { + #region Create one object per row + if ($AsText) { + <#join items in AsText together with ~~~ . Escape any regex special characters... + # which turns * into \* make it .*. Convert ~~~ to $|^ and top and tail with ^%; + So if we get "Week", "[Time]" and "*date*" ; make the expression ^week$|^\[Time\]$|^.*Date.*$ + $make a regex for this which is case insensitive (option 1) and compiled (option 8) + #> + $TextColExpression = "^" + [regex]::Escape($AsText -join "~~~").replace("\*", ".*").replace("~~~", "$|^") + "$" + $TextColRegEx = New-Object -TypeName regex -ArgumentList $TextColExpression , 9 + } + foreach ($R in $Rows) { + #Disabled write-verbose for speed + # Write-Verbose "Import row '$R'" + $NewRow = [Ordered]@{ } + if ($TextColRegEx) { + foreach ($P in $PropertyNames) { + if ($TextColRegEx.IsMatch($P.Value)) { + $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Text + } + else { $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Value } + } + } + else { + foreach ($P in $PropertyNames) { + $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Value + # Write-Verbose "Import cell '$($Worksheet.Cells[$R, $P.Column].Address)' with property name '$($p.Value)' and value '$($Worksheet.Cells[$R, $P.Column].Value)'." + } + } + [PSCustomObject]$NewRow + } + #endregion + } + Write-Debug $sw.Elapsed.TotalMilliseconds + } + catch { throw "Failed importing the Excel workbook '$Path' with worksheet '$Worksheetname': $_"; return } + finally { + if ($Path) { $stream.close(); $ExcelPackage.Dispose() } + } + } +} diff --git a/ExportedCommands/Import-Html.md b/ExportedCommands/Import-Html.md new file mode 100644 index 0000000..91725a4 --- /dev/null +++ b/ExportedCommands/Import-Html.md @@ -0,0 +1,121 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Import-Html + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Import-Html [[-url] ] [[-index] ] [[-Header] ] [[-FirstDataRow] ] + [-UseDefaultCredentials] [] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -FirstDataRow +{{ Fill FirstDataRow Description }} + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Header +{{ Fill Header Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UseDefaultCredentials +{{ Fill UseDefaultCredentials Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -index +{{ Fill index Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -url +{{ Fill url Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/Import-Html.ps1 b/ExportedCommands/Import-Html.ps1 similarity index 100% rename from Import-Html.ps1 rename to ExportedCommands/Import-Html.ps1 diff --git a/ExportedCommands/Import-UPS.md b/ExportedCommands/Import-UPS.md new file mode 100644 index 0000000..625c903 --- /dev/null +++ b/ExportedCommands/Import-UPS.md @@ -0,0 +1,72 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Import-UPS + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Import-UPS [[-TrackingNumber] ] [-UseDefaultCredentials] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -TrackingNumber +{{ Fill TrackingNumber Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UseDefaultCredentials +{{ Fill UseDefaultCredentials Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/TrackingUtils.ps1 b/ExportedCommands/Import-UPS.ps1 similarity index 100% rename from TrackingUtils.ps1 rename to ExportedCommands/Import-UPS.ps1 diff --git a/ExportedCommands/Import-USPS.md b/ExportedCommands/Import-USPS.md new file mode 100644 index 0000000..48833fc --- /dev/null +++ b/ExportedCommands/Import-USPS.md @@ -0,0 +1,72 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Import-USPS + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Import-USPS [[-TrackingNumber] ] [-UseDefaultCredentials] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -TrackingNumber +{{ Fill TrackingNumber Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UseDefaultCredentials +{{ Fill UseDefaultCredentials Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/ExportedCommands/Import-USPS.ps1 b/ExportedCommands/Import-USPS.ps1 new file mode 100644 index 0000000..921fa71 --- /dev/null +++ b/ExportedCommands/Import-USPS.ps1 @@ -0,0 +1,9 @@ +function Import-USPS { + param( + $TrackingNumber, + [Switch]$UseDefaultCredentials + + ) + + Import-Html "https://tools.usps.com/go/TrackConfirmAction?qtc_tLabels1=$($TrackingNumber)" 0 -UseDefaultCredentials: $UseDefaultCredentials +} diff --git a/ExportedCommands/Invoke-Sum.md b/ExportedCommands/Invoke-Sum.md new file mode 100644 index 0000000..efbb46e --- /dev/null +++ b/ExportedCommands/Invoke-Sum.md @@ -0,0 +1,87 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Invoke-Sum + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Invoke-Sum [[-data] ] [[-dimension] ] [[-measure] ] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -data +{{ Fill data Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -dimension +{{ Fill dimension Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -measure +{{ Fill measure Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/Invoke-Sum.ps1 b/ExportedCommands/Invoke-Sum.ps1 similarity index 100% rename from Invoke-Sum.ps1 rename to ExportedCommands/Invoke-Sum.ps1 diff --git a/Join-Worksheet.ps1 b/ExportedCommands/Join-Worksheet.ps1 similarity index 52% rename from Join-Worksheet.ps1 rename to ExportedCommands/Join-Worksheet.ps1 index 955ceab..cb24d4e 100644 --- a/Join-Worksheet.ps1 +++ b/ExportedCommands/Join-Worksheet.ps1 @@ -1,134 +1,56 @@ function Join-Worksheet { - <# - .SYNOPSIS - Combines data on all the sheets in an Excel worksheet onto a single sheet. - .DESCRIPTION - Join-Worksheet can work in two main ways, either - Combining data which has the same layout from many pages into one, or - combining pages which have nothing in common. - In the former case the header row is copied from the first sheet and, - by default, each row of data is labelled with the name of the sheet it came from. - In the latter case -NoHeader is specified, and each copied block can have the - sheet it came from placed above it as a title. - .EXAMPLE - > - 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 the services running on four servers and exports each - to its own page in Test.xlsx. - $PtDef= creates a definition for a PivotTable. - The Join-Worksheet command uses the same file and merges the results into a sheet - named "Combined". It sets a column header of "Machinename", this column will - contain the name of the sheet the data was copied from; after copying the data - to the sheet "Combined", the other sheets will be hidden. - Join-Worksheet finishes by calling Export-Excel to AutoSize cells, freeze the - top row and make it bold and add thePivotTable. - - .EXAMPLE - > - PS> Get-WmiObject -Class 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. - #> [CmdletBinding(DefaultParameterSetName = 'Default')] param ( - # Path to a new or existing .XLSX file. [Parameter(ParameterSetName = "Default", Position = 0)] [Parameter(ParameterSetName = "Table" , Position = 0)] [String]$Path , - # An object representing an Excel Package - either from Open-Excel Package or specifying -PassThru to Export-Excel. [Parameter(Mandatory = $true, ParameterSetName = "PackageDefault")] [Parameter(Mandatory = $true, ParameterSetName = "PackageTable")] [OfficeOpenXml.ExcelPackage]$ExcelPackage, - # The name of a sheet within the workbook where the other sheets will be joined together - "Combined" by default. $WorkSheetName = 'Combined', - # If specified ,any pre-existing target for the joined data will be deleted and re-created; otherwise data will be appended on this sheet. [switch]$Clearsheet, - #Join-Worksheet assumes each sheet has identical headers and the headers should be copied to the target sheet, unless -NoHeader is specified. [switch]$NoHeader, - #If -NoHeader is NOT specified, then rows of data will be labeled with the name of the sheet they came from. FromLabel is the header for this column. If it is null or empty, the labels will be omitted. [string]$FromLabel = "From" , - #If specified, the copied blocks of data will have the name of the sheet they were copied from inserted above them as a title. [switch]$LabelBlocks, - #Sets the width of the Excel columns to display all the data in their cells. [Switch]$AutoSize, - #Freezes headers etc. in the top row. [Switch]$FreezeTopRow, - #Freezes titles etc. in the left column. [Switch]$FreezeFirstColumn, - #Freezes top row and left column (equivalent to Freeze pane 2,2 ). [Switch]$FreezeTopRowFirstColumn, - # Freezes panes at specified coordinates (in the form RowNumber , ColumnNumber). [Int[]]$FreezePane, - #Enables the Excel filter on the headers of the combined sheet. [Parameter(ParameterSetName = 'Default')] [Parameter(ParameterSetName = 'PackageDefault')] [Switch]$AutoFilter, - #Makes the top row boldface. [Switch]$BoldTopRow, - #If specified, hides the sheets that the data is copied from. [switch]$HideSource, - #Text of a title to be placed in Cell A1. [String]$Title, - #Sets the fill pattern for the title cell. [OfficeOpenXml.Style.ExcelFillStyle]$TitleFillPattern = 'Solid', - #Sets the cell background color for the title cell. $TitleBackgroundColor, - #Sets the title in boldface type. [Switch]$TitleBold, - #Sets the point size for the title. [Int]$TitleSize = 22, - #Hashtable(s) with Sheet PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values to specify a definition for one or morePivotTable(s). [Hashtable]$PivotTableDefinition, - #A hashtable containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-pivot] charts. [Object[]]$ExcelChartDefinition, - #One or more conditional formatting rules defined with New-ConditionalFormattingIconSet. [Object[]]$ConditionalFormat, - #Applies a Conditional formatting rule defined with New-ConditionalText. When specific conditions are met the format is applied [Object[]]$ConditionalText, - #Makes each column a named range. [switch]$AutoNameRange, - #Makes the data in the worksheet a named range. [ValidateScript( { if (-not $_) { throw 'RangeName is null or empty.' } elseif ($_[0] -notmatch '[a-z]') { throw 'RangeName starts with an invalid character.' } else { $true } - })] + })] [String]$RangeName, [ValidateScript( { if (-not $_) { throw 'Tablename is null or empty.' } elseif ($_[0] -notmatch '[a-z]') { throw 'Tablename starts with an invalid character.' } else { $true } - })] + })] [Parameter(ParameterSetName = 'Table' , Mandatory = $true)] [Parameter(ParameterSetName = 'PackageTable' , Mandatory = $true)] - # Makes the data in the worksheet a table with a name and applies a style to it. Name must not contain spaces. [String]$TableName, [Parameter(ParameterSetName = 'Table')] [Parameter(ParameterSetName = 'PackageTable')] - #Selects the style for the named table - defaults to "Medium6". [OfficeOpenXml.Table.TableStyles]$TableStyle = 'Medium6', - #If specified, returns the range of cells in the combined sheet, in the format "A1:Z100". [switch]$ReturnRange, - #Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first. [switch]$Show, - #If specified, an object representing the unsaved Excel package will be returned, it then needs to be saved. [switch]$PassThru ) #region get target worksheet, select it and move it to the end. diff --git a/ExportedCommands/Merge-MultipleSheets.ps1 b/ExportedCommands/Merge-MultipleSheets.ps1 new file mode 100644 index 0000000..14017dc --- /dev/null +++ b/ExportedCommands/Merge-MultipleSheets.ps1 @@ -0,0 +1,147 @@ +function Merge-MultipleSheets { + [cmdletbinding()] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification="False positives when initializing variable in begin block")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification="MultipleSheet would be incorrect")] + #[Alias("Merge-MulipleSheets")] #There was a spelling error in the first release. This was there to ensure things didn't break but intelisense gave the alias first. + param ( + [Parameter(Mandatory=$true,ValueFromPipeline=$true)] + $Path , + [int]$Startrow = 1, + + [String[]]$Headername, + + [switch]$NoHeader, + + $WorksheetName = "Sheet1", + [Alias('OutFile')] + $OutputFile = ".\temp.xlsx", + [Alias('OutSheet')] + $OutputSheetName = "Sheet1", + $Property = "*" , + $ExcludeProperty , + $Key = "Name" , + $KeyFontColor = [System.Drawing.Color]::Red, + $ChangeBackgroundColor = [System.Drawing.Color]::Orange, + $DeleteBackgroundColor = [System.Drawing.Color]::LightPink, + $AddBackgroundColor = [System.Drawing.Color]::Orange, + [switch]$HideRowNumbers , + [switch]$Passthru , + [Switch]$Show + ) + begin { $filestoProcess = @() } + process { $filestoProcess += $Path} + end { + if ($filestoProcess.Count -eq 1 -and $WorksheetName -match '\*') { + Write-Progress -Activity "Merging sheets" -CurrentOperation "Expanding * to names of sheets in $($filestoProcess[0]). " + $excel = Open-ExcelPackage -Path $filestoProcess + $WorksheetName = $excel.Workbook.Worksheets.Name.where({$_ -like $WorksheetName}) + Close-ExcelPackage -NoSave -ExcelPackage $excel + } + + #Merge identically named sheets in different work books; + if ($filestoProcess.Count -ge 2 -and $WorksheetName -is "string" ) { + Get-Variable -Name 'HeaderName','NoHeader','StartRow','Key','Property','ExcludeProperty','WorksheetName' -ErrorAction SilentlyContinue | + Where-Object {$_.Value} | ForEach-Object -Begin {$params= @{} } -Process {$params[$_.Name] = $_.Value} + + Write-Progress -Activity "Merging sheets" -CurrentOperation "comparing '$WorksheetName' in $($filestoProcess[-1]) against $($filestoProcess[0]). " + $merged = Merge-Worksheet @params -Referencefile $filestoProcess[0] -Differencefile $filestoProcess[-1] + $nextFileNo = 2 + while ($nextFileNo -lt $filestoProcess.count -and $merged) { + Write-Progress -Activity "Merging sheets" -CurrentOperation "comparing '$WorksheetName' in $($filestoProcess[-$nextFileNo]) against $($filestoProcess[0]). " + $merged = Merge-Worksheet @params -ReferenceObject $merged -Differencefile $filestoProcess[-$nextFileNo] + $nextFileNo ++ + + } + } + #Merge different sheets from one workbook + elseif ($filestoProcess.Count -eq 1 -and $WorksheetName.Count -ge 2 ) { + Get-Variable -Name 'HeaderName','NoHeader','StartRow','Key','Property','ExcludeProperty' -ErrorAction SilentlyContinue | + Where-Object {$_.Value} | ForEach-Object -Begin {$params= @{} } -Process {$params[$_.Name] = $_.Value} + + Write-Progress -Activity "Merging sheets" -CurrentOperation "Comparing $($WorksheetName[-1]) against $($WorksheetName[0]). " + $merged = Merge-Worksheet @params -Referencefile $filestoProcess[0] -Differencefile $filestoProcess[0] -WorksheetName $WorksheetName[0,-1] + $nextSheetNo = 2 + while ($nextSheetNo -lt $WorksheetName.count -and $merged) { + Write-Progress -Activity "Merging sheets" -CurrentOperation "Comparing $($WorksheetName[-$nextSheetNo]) against $($WorksheetName[0]). " + $merged = Merge-Worksheet @params -ReferenceObject $merged -Differencefile $filestoProcess[0] -WorksheetName $WorksheetName[-$nextSheetNo] -DiffPrefix $WorksheetName[-$nextSheetNo] + $nextSheetNo ++ + } + } + #We either need one Worksheet name and many files or one file and many sheets. + else { Write-Warning -Message "Need at least two files to process" ; return } + #if the process didn't return data then abandon now. + if (-not $merged) {Write-Warning -Message "The merge operation did not return any data."; return } + + $orderByProperties = $merged[0].psobject.properties.where({$_.name -match "row$"}).name + Write-Progress -Activity "Merging sheets" -CurrentOperation "creating output sheet '$OutputSheetName' in $OutputFile" + $excel = $merged | Sort-Object -Property $orderByProperties | + Export-Excel -Path $OutputFile -Worksheetname $OutputSheetName -ClearSheet -BoldTopRow -AutoFilter -PassThru + $sheet = $excel.Workbook.Worksheets[$OutputSheetName] + + #We will put in a conditional format for "if all the others are not flagged as 'same'" to mark rows where something is added, removed or changed + $sameChecks = @() + + #All the 'difference' columns in the sheet are labeled with the file they came from, 'reference' columns need their + #headers prefixed with the ref file name, $colnames is the basis of a regular expression to identify what should have $refPrefix appended + $colNames = @("^_Row$") + if ($key -ne "*") + {$colnames += "^$Key$"} + if ($filesToProcess.Count -ge 2) { + $refPrefix = (Split-Path -Path $filestoProcess[0] -Leaf) -replace "\.xlsx$"," " + } + else {$refPrefix = $WorksheetName[0] } + Write-Progress -Activity "Merging sheets" -CurrentOperation "applying formatting to sheet '$OutputSheetName' in $OutputFile" + #Find the column headings which are in the form "diffFile is"; which will hold 'Same', 'Added' or 'Changed' + foreach ($cell in $sheet.Cells[($sheet.Dimension.Address -replace "\d+$","1")].Where({$_.value -match "\sIS$"}) ) { + #Work leftwards across the headings applying conditional formatting which says + # 'Format this cell if the "IS" column has a value of ...' until you find a heading which doesn't have the prefix. + $prefix = $cell.value -replace "\sIS$","" + $columnNo = $cell.start.Column -1 + $cellAddr = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R1C$columnNo",1,$columnNo) + while ($sheet.cells[$cellAddr].value -match $prefix) { + $condFormattingParams = @{RuleType='Expression'; BackgroundPattern='Solid'; Worksheet=$sheet; StopIfTrue=$true; Range=$([OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R[1]C[$columnNo]:R[1048576]C[$columnNo]",0,0)) } + Add-ConditionalFormatting @condFormattingParams -ConditionValue ($cell.Address + '="Added"' ) -BackgroundColor $AddBackgroundColor + Add-ConditionalFormatting @condFormattingParams -ConditionValue ($cell.Address + '="Changed"') -BackgroundColor $ChangeBackgroundColor + Add-ConditionalFormatting @condFormattingParams -ConditionValue ($cell.Address + '="Removed"') -BackgroundColor $DeleteBackgroundColor + $columnNo -- + $cellAddr = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R1C$columnNo",1,$columnNo) + } + #build up a list of prefixes in $colnames - we'll use that to set headers on rows from the reference file; and build up the "if the 'is' cell isn't same" list + $colNames += $prefix + $sameChecks += (($cell.Address -replace "1","2") +'<>"Same"') + } + + #For all the columns which don't match one of the Diff-file prefixes or "_Row" or the 'Key' columnn name; add the reference file prefix to their header. + $nameRegex = $colNames -Join '|' + foreach ($cell in $sheet.Cells[($sheet.Dimension.Address -replace "\d+$","1")].Where({$_.value -Notmatch $nameRegex}) ) { + $cell.Value = $refPrefix + $cell.Value + $condFormattingParams = @{RuleType='Expression'; BackgroundPattern='Solid'; Worksheet=$sheet; StopIfTrue=$true; Range=[OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R[2]C[$($cell.start.column)]:R[1048576]C[$($cell.start.column)]",0,0)} + Add-ConditionalFormatting @condFormattingParams -ConditionValue ("OR(" +(($sameChecks -join ",") -replace '<>"Same"','="Added"' ) +")" ) -BackgroundColor $DeleteBackgroundColor + Add-ConditionalFormatting @condFormattingParams -ConditionValue ("AND(" +(($sameChecks -join ",") -replace '<>"Same"','="Changed"') +")" ) -BackgroundColor $ChangeBackgroundColor + } + #We've made a bunch of things wider so now is the time to autofit columns. Any hiding has to come AFTER this, because it unhides things + if ($env:NoAutoSize) {Write-Warning "Autofit is not available with this OS configuration."} + else {$sheet.Cells.AutoFitColumns()} + + #if we have a key field (we didn't concatenate all fields) use what we built up in $sameChecks to apply conditional formatting to it (Row no will be in column A, Key in Column B) + if ($Key -ne '*') { + Add-ConditionalFormatting -Worksheet $sheet -Range "B2:B1048576" -ForeGroundColor $KeyFontColor -BackgroundPattern 'None' -RuleType Expression -ConditionValue ("OR(" +($sameChecks -join ",") +")" ) + $sheet.view.FreezePanes(2, 3) + } + else {$sheet.view.FreezePanes(2, 2) } + #Go back over the headings to find and hide the "is" columns; + foreach ($cell in $sheet.Cells[($sheet.Dimension.Address -replace "\d+$","1")].Where({$_.value -match "\sIS$"}) ) { + $sheet.Column($cell.start.Column).HIDDEN = $true + } + + #If specified, look over the headings for "row" and hide the columns which say "this was in row such-and-such" + if ($HideRowNumbers) { + foreach ($cell in $sheet.Cells[($sheet.Dimension.Address -replace "\d+$","1")].Where({$_.value -match "Row$"}) ) { + $sheet.Column($cell.start.Column).HIDDEN = $true + } + } + if ($Passthru) {$excel} + else {Close-ExcelPackage -ExcelPackage $excel -Show:$Show} + Write-Progress -Activity "Merging sheets" -Completed + } + } diff --git a/ExportedCommands/Merge-Worksheet.ps1 b/ExportedCommands/Merge-Worksheet.ps1 new file mode 100644 index 0000000..0674f65 --- /dev/null +++ b/ExportedCommands/Merge-Worksheet.ps1 @@ -0,0 +1,263 @@ +function Merge-Worksheet { + [cmdletbinding(SupportsShouldProcess=$true)] + Param( + [parameter(ParameterSetName='A',Mandatory=$true,Position=0)] #A = Compare two files default headers + [parameter(ParameterSetName='B',Mandatory=$true,Position=0)] #B = Compare two files user supplied headers + [parameter(ParameterSetName='C',Mandatory=$true,Position=0)] #C = Compare two files headers P1, P2, P3 etc + $Referencefile , + + [parameter(ParameterSetName='A',Mandatory=$true,Position=1)] + [parameter(ParameterSetName='B',Mandatory=$true,Position=1)] + [parameter(ParameterSetName='C',Mandatory=$true,Position=1)] + [parameter(ParameterSetName='E',Mandatory=$true,Position=1)] #D Compare two objects; E = Compare one object one file that uses default headers + [parameter(ParameterSetName='F',Mandatory=$true,Position=1)] #F = Compare one object one file that uses user supplied headers + [parameter(ParameterSetName='G',Mandatory=$true,Position=1)] #G Compare one object one file that uses headers P1, P2, P3 etc + $Differencefile , + + [parameter(ParameterSetName='A',Position=2)] #Applies to all sets EXCEPT D which is two objects (no sheets) + [parameter(ParameterSetName='B',Position=2)] + [parameter(ParameterSetName='C',Position=2)] + [parameter(ParameterSetName='E',Position=2)] + [parameter(ParameterSetName='F',Position=2)] + [parameter(ParameterSetName='G',Position=2)] + $WorksheetName = "Sheet1", + + [parameter(ParameterSetName='A')] #Applies to all sets EXCEPT D which is two objects (no sheets, so no start row ) + [parameter(ParameterSetName='B')] + [parameter(ParameterSetName='C')] + [parameter(ParameterSetName='E')] + [parameter(ParameterSetName='F')] + [parameter(ParameterSetName='G')] + [int]$Startrow = 1, + + [Parameter(ParameterSetName='B',Mandatory=$true)] #Compare object + sheet or 2 sheets with user supplied headers + [Parameter(ParameterSetName='F',Mandatory=$true)] + [String[]]$Headername, + + [Parameter(ParameterSetName='C',Mandatory=$true)] #Compare object + sheet or 2 sheets with headers of P1, P2, P3 ... + [Parameter(ParameterSetName='G',Mandatory=$true)] + [switch]$NoHeader, + + [parameter(ParameterSetName='D',Mandatory=$true)] + [parameter(ParameterSetName='E',Mandatory=$true)] + [parameter(ParameterSetName='F',Mandatory=$true)] + [parameter(ParameterSetName='G',Mandatory=$true)] + [Alias('RefObject')] + $ReferenceObject , + [parameter(ParameterSetName='D',Mandatory=$true,Position=1)] + [Alias('DiffObject')] + $DifferenceObject , + [parameter(ParameterSetName='D',Position=2)] + [parameter(ParameterSetName='E',Position=2)] + [parameter(ParameterSetName='F',Position=2)] + [parameter(ParameterSetName='G',Position=2)] + $DiffPrefix = "=>" , + [parameter(Position=3)] + [Alias('OutFile')] + $OutputFile , + [parameter(Position=4)] + [Alias('OutSheet')] + $OutputSheetName = "Sheet1", + $Property = "*" , + $ExcludeProperty , + $Key = "Name" , + $KeyFontColor = [System.Drawing.Color]::DarkRed , + $ChangeBackgroundColor = [System.Drawing.Color]::Orange, + $DeleteBackgroundColor = [System.Drawing.Color]::LightPink, + $AddBackgroundColor = [System.Drawing.Color]::PaleGreen, + [switch]$HideEqual , + [switch]$Passthru , + [Switch]$Show + ) + + #region Read Excel data + if ($Differencefile -is [System.IO.FileInfo]) {$Differencefile = $Differencefile.FullName} + if ($Referencefile -is [System.IO.FileInfo]) {$Referencefile = $Referencefile.FullName} + if ($Referencefile -and $Differencefile) { + #if the filenames don't resolve, give up now. + try { $oneFile = ((Resolve-Path -Path $Referencefile -ErrorAction Stop).path -eq (Resolve-Path -Path $Differencefile -ErrorAction Stop).path)} + Catch { Write-Warning -Message "Could not Resolve the filenames." ; return } + + #If we have one file , we must have two different Worksheet names. If we have two files $WorksheetName can be a single string or two strings. + if ($onefile -and ( ($WorksheetName.count -ne 2) -or $WorksheetName[0] -eq $WorksheetName[1] ) ) { + Write-Warning -Message "If both the Reference and difference file are the same then Worksheet name must provide 2 different names" + return + } + if ($WorksheetName.count -eq 2) {$Worksheet2 = $DiffPrefix = $WorksheetName[1] ; $Worksheet1 = $WorksheetName[0] ; } + elseif ($WorksheetName -is [string]) {$Worksheet2 = $Worksheet1 = $WorksheetName ; + $DiffPrefix = (Split-Path -Path $Differencefile -Leaf) -replace "\.xlsx$","" } + else {Write-Warning -Message "You must provide either a single Worksheet name or two names." ; return } + + $params= @{ ErrorAction = [System.Management.Automation.ActionPreference]::Stop } + foreach ($p in @("HeaderName","NoHeader","StartRow")) {if ($PSBoundParameters[$p]) {$params[$p] = $PSBoundParameters[$p]}} + try { + $ReferenceObject = Import-Excel -Path $Referencefile -WorksheetName $Worksheet1 @params + $DifferenceObject = Import-Excel -Path $Differencefile -WorksheetName $Worksheet2 @Params + } + Catch {Write-Warning -Message "Could not read the Worksheet from $Referencefile::$Worksheet1 and/or $Differencefile::$Worksheet2." ; return } + if ($NoHeader) {$firstDataRow = $Startrow } else {$firstDataRow = $Startrow + 1} + } + elseif ( $Differencefile) { + if ($WorksheetName -isnot [string]) {Write-Warning -Message "You must provide a single Worksheet name." ; return } + $params = @{WorksheetName=$WorksheetName; Path=$Differencefile; ErrorAction=[System.Management.Automation.ActionPreference]::Stop } + foreach ($p in @("HeaderName","NoHeader","StartRow")) {if ($PSBoundParameters[$p]) {$params[$p] = $PSBoundParameters[$p]}} + try {$DifferenceObject = Import-Excel @Params } + Catch {Write-Warning -Message "Could not read the Worksheet '$WorksheetName' from $Differencefile::$WorksheetName." ; return } + if ($DiffPrefix -eq "=>" ) { + $DiffPrefix = (Split-Path -Path $Differencefile -Leaf) -replace "\.xlsx$","" + } + if ($NoHeader) {$firstDataRow = $Startrow } else {$firstDataRow = $Startrow + 1} + } + else { $firstDataRow = 1 } + #endregion + + #region Set lists of properties and row numbers + #Make a list of properties/headings using the Property (default "*") and ExcludeProperty parameters + $propList = @() + $DifferenceObject = $DifferenceObject | Update-FirstObjectProperties + $headings = $DifferenceObject[0].psobject.Properties.Name # This preserves the sequence - using get-member would sort them alphabetically! There may be extra properties in + if ($NoHeader -and "Name" -eq $Key) {$Key = "p1"} + if ($headings -notcontains $Key -and + ('*' -ne $Key)) {Write-Warning -Message "You need to specify one of the headings in the sheet '$Worksheet1' as a key." ; return } + foreach ($p in $Property) { $propList += ($headings.where({$_ -like $p}) )} + foreach ($p in $ExcludeProperty) { $propList = $propList.where({$_ -notlike $p}) } + if (($propList -notcontains $Key) -and + ('*' -ne $Key)) { $propList += $Key} #If $key isn't one of the headings we will have bailed by now + $propList = $propList | Select-Object -Unique #so, prolist must contain at least $key if nothing else + + #If key is "*" we treat it differently , and we will create a script property which concatenates all the Properties in $Proplist + $ConCatblock = [scriptblock]::Create( ($proplist | ForEach-Object {'$this."' + $_ + '"'}) -join " + ") + + #Build the list of the properties to output, in order. + $diffpart = @() + $refpart = @() + foreach ($p in $proplist.Where({$key -ne $_}) ) {$refPart += $p ; $diffPart += "$DiffPrefix $p" } + $lastRefColNo = $proplist.count + $FirstDiffColNo = $lastRefColNo + 1 + + if ($key -ne '*') { + $outputProps = @($key) + $refpart + $diffpart + #If we are using a single column as the key, don't duplicate it, so the last difference column will be A if there is one property, C if there are two, E if there are 3 + $lastDiffColNo = (2 * $proplist.count) - 1 + } + else { + $outputProps = @( ) + $refpart + $diffpart + #If we not using a single column as a key all columns are duplicated so, the Last difference column will be B if there is one property, D if there are two, F if there are 3 + $lastDiffColNo = (2 * $proplist.count ) + } + + #Add RowNumber to every row + #If one sheet has extra rows we can get a single "==" result from compare, with the row from the reference sheet, but + #the row in the other sheet might be different so we will look up the row number from the key field - build a hash table for that here + #If we have "*" as the key ad the script property to concatenate the [selected] properties. + + $Rowhash = @{} + $rowNo = $firstDataRow + foreach ($row in $ReferenceObject) { + if ($null -eq $row._row) {Add-Member -InputObject $row -MemberType NoteProperty -Value ($rowNo ++) -Name "_Row" } + else {$rowNo++ } + if ($Key -eq '*' ) {Add-Member -InputObject $row -MemberType ScriptProperty -Value $ConCatblock -Name "_All" } + } + $rowNo = $firstDataRow + foreach ($row in $DifferenceObject) { + Add-Member -InputObject $row -MemberType NoteProperty -Value $rowNo -Name "$DiffPrefix Row" -Force + if ($Key -eq '*' ) { + Add-Member -InputObject $row -MemberType ScriptProperty -Value $ConCatblock -Name "_All" + $Rowhash[$row._All] = $rowNo + } + else {$Rowhash[$row.$key] = $rowNo } + $rowNo ++ + } + if ($DifferenceObject.count -gt $Rowhash.Keys.Count) { + Write-Warning -Message "Difference object has $($DifferenceObject.Count) rows; but only $($Rowhash.keys.count) unique keys" + } + if ($Key -eq '*') {$key = "_ALL"} + #endregion + #We need to know all the properties we've met on the objects we've diffed + $eDiffProps = [ordered]@{} + #When we do a compare object changes will result in two rows so we group them and join them together. + $expandedDiff = Compare-Object -ReferenceObject $ReferenceObject -DifferenceObject $DifferenceObject -Property $propList -PassThru -IncludeEqual | + Group-Object -Property $key | ForEach-Object { + #The value of the key column is the name of the Group. + $keyval = $_.name + #we're going to create a custom object from a hash table. + $hash = [ordered]@{} + foreach ($result in $_.Group) { + if ($result.SideIndicator -ne "=>") {$hash["_Row"] = $result._Row } + elseif (-not $hash["$DiffPrefix Row"]) {$hash["_Row"] = "" } + #if we have already set the side, this must be the second record, so set side to indicate "changed"; if we got two "Same" indicators we may have a classh of keys + if ($hash.Side) { + if ($hash.Side -eq $result.SideIndicator) {Write-Warning -Message "'$keyval' may be a duplicate."} + $hash.Side = "<>" + } + else {$hash["Side"] = $result.SideIndicator} + switch ($hash.side) { + '==' { $hash["$DiffPrefix is"] = 'Same' } + '=>' { $hash["$DiffPrefix is"] = 'Added' } + '<>' { if (-not $hash["_Row"]) { + $hash["$DiffPrefix is"] = 'Added' + } + else { + $hash["$DiffPrefix is"] = 'Changed' + } + } + '<=' { $hash["$DiffPrefix is"] = 'Removed'} + } + #find the number of the row in the the "difference" object which has this key. If it is the object is only in the reference this will be blank. + $hash["$DiffPrefix Row"] = $Rowhash[$keyval] + $hash[$key] = $keyval + #Create FieldName and/or =>FieldName columns + foreach ($p in $result.psobject.Properties.name.where({$_ -ne $key -and $_ -ne "SideIndicator" -and $_ -ne "$DiffPrefix Row" })) { + if ($result.SideIndicator -eq "==" -and $p -in $propList) + {$hash[("$p")] = $hash[("$DiffPrefix $p")] = $result.$P} + elseif ($result.SideIndicator -eq "==" -or $result.SideIndicator -eq "<=") + {$hash[("$p")] = $result.$P} + elseif ($result.SideIndicator -eq "=>") { $hash[("$DiffPrefix $p")] = $result.$P} + } + } + + foreach ($k in $hash.keys) {$eDiffProps[$k] = $true} + [Pscustomobject]$hash + } | Sort-Object -Property "_row" + + #Already sorted by reference row number, fill in any blanks in the difference-row column. + for ($i = 1; $i -lt $expandedDiff.Count; $i++) {if (-not $expandedDiff[$i]."$DiffPrefix Row") {$expandedDiff[$i]."$DiffPrefix Row" = $expandedDiff[$i-1]."$DiffPrefix Row" } } + + #Now re-Sort by difference row number, and fill in any blanks in the reference-row column. + $expandedDiff = $expandedDiff | Sort-Object -Property "$DiffPrefix Row" + for ($i = 1; $i -lt $expandedDiff.Count; $i++) {if (-not $expandedDiff[$i]."_Row") {$expandedDiff[$i]."_Row" = $expandedDiff[$i-1]."_Row" } } + + $AllProps = @("_Row") + $OutputProps + $eDiffProps.keys.where({$_ -notin ($outputProps + @("_row","side","SideIndicator","_ALL" ))}) + + if ($PassThru -or -not $OutputFile) {return ($expandedDiff | Select-Object -Property $allprops | Sort-Object -Property "_row", "$DiffPrefix Row" ) } + elseif ($PSCmdlet.ShouldProcess($OutputFile,"Write Output to Excel file")) { + $expandedDiff = $expandedDiff | Sort-Object -Property "_row", "$DiffPrefix Row" + $xl = $expandedDiff | Select-Object -Property $OutputProps | Update-FirstObjectProperties | + Export-Excel -Path $OutputFile -Worksheetname $OutputSheetName -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -PassThru + $ws = $xl.Workbook.Worksheets[$OutputSheetName] + for ($i = 0; $i -lt $expandedDiff.Count; $i++ ) { + if ( $expandedDiff[$i].side -ne "==" ) { + Set-ExcelRange -Worksheet $ws -Range ("A" + ($i + 2 )) -FontColor $KeyFontColor + } + elseif ( $HideEqual ) {$ws.row($i+2).hidden = $true } + if ( $expandedDiff[$i].side -eq "<>" ) { + $range = $ws.Dimension -replace "\d+", ($i + 2 ) + Set-ExcelRange -Worksheet $ws -Range $range -BackgroundColor $ChangeBackgroundColor + } + elseif ( $expandedDiff[$i].side -eq "<=" ) { + $rangeR1C1 = "R[{0}]C[1]:R[{0}]C[{1}]" -f ($i + 2 ) , $lastRefColNo + $range = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1($rangeR1C1,0,0) + Set-ExcelRange -Worksheet $ws -Range $range -BackgroundColor $DeleteBackgroundColor + } + elseif ( $expandedDiff[$i].side -eq "=>" ) { + if ($propList.count -gt 1) { + $rangeR1C1 = "R[{0}]C[{1}]:R[{0}]C[{2}]" -f ($i + 2 ) , $FirstDiffColNo , $lastDiffColNo + $range = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1($rangeR1C1,0,0) + Set-ExcelRange -Worksheet $ws -Range $range -BackgroundColor $AddBackgroundColor + } + Set-ExcelRange -Worksheet $ws -Range ("A" + ($i + 2 )) -BackgroundColor $AddBackgroundColor + } + } + Close-ExcelPackage -ExcelPackage $xl -Show:$Show + } +} diff --git a/New-ConditionalFormattingIconSet.ps1 b/ExportedCommands/New-ConditionalFormattingIconSet.ps1 similarity index 58% rename from New-ConditionalFormattingIconSet.ps1 rename to ExportedCommands/New-ConditionalFormattingIconSet.ps1 index acd7547..18ff937 100644 --- a/New-ConditionalFormattingIconSet.ps1 +++ b/ExportedCommands/New-ConditionalFormattingIconSet.ps1 @@ -1,32 +1,4 @@ function New-ConditionalFormattingIconSet { - <# - .SYNOPSIS - Creates an object which describes a conditional formatting rule a for 3,4 or 5 icon set. - .DESCRIPTION - Export-Excel takes a -ConditionalFormat parameter which can hold one or more descriptions for conditional formats; - this command builds the defintion of a Conditional formatting rule for an icon set. - .PARAMETER Range - The range of cells that the conditional format applies to. - .PARAMETER ConditionalFormat - The type of rule: one of "ThreeIconSet","FourIconSet" or "FiveIconSet" - .PARAMETER IconType - The name of an iconSet - different icons are available depending on whether 3,4 or 5 icon set is selected. - .PARAMETER Reverse - Use the icons in the reverse order. - .Example - $cfRange = [OfficeOpenXml.ExcelAddress]::new($topRow, $column, $lastDataRow, $column) - $cfdef = New-ConditionalFormattingIconSet -Range $cfrange -ConditionalFormat ThreeIconSet -IconType Arrows - Export-Excel -ExcelPackage $excel -ConditionalFormat $cfdef -show - - The first line creates a range - one column wide in the column $column, running - from $topRow to $lastDataRow. - The second line creates a definition object using this range - and the third uses Export-Excel with an open package to apply the format and - save and open the file. - .Link - Add-Add-ConditionalFormatting - New-ConditionalText - #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system State')] param( [Parameter(Mandatory=$true)] diff --git a/ExportedCommands/New-ConditionalText.ps1 b/ExportedCommands/New-ConditionalText.ps1 new file mode 100644 index 0000000..a5b6743 --- /dev/null +++ b/ExportedCommands/New-ConditionalText.ps1 @@ -0,0 +1,41 @@ +function New-ConditionalText { + [cmdletbinding()] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system State')] + param( + #[Parameter(Mandatory=$true)] + [Alias("ConditionValue")] + $Text, + [Alias("ForeGroundColor")] + $ConditionalTextColor=[System.Drawing.Color]::DarkRed, + $BackgroundColor=[System.Drawing.Color]::LightPink, + [String]$Range, + [OfficeOpenXml.Style.ExcelFillStyle]$PatternType=[OfficeOpenXml.Style.ExcelFillStyle]::Solid, + [ValidateSet( + "LessThan", "LessThanOrEqual", "GreaterThan", "GreaterThanOrEqual", + "Equal", "NotEqual", + "Top", "TopPercent", "Bottom", "BottomPercent", + "ContainsText", "NotContainsText", "BeginsWith", "EndsWith", + "ContainsBlanks", "NotContainsBlanks", "ContainsErrors", "NotContainsErrors", + "DuplicateValues", "UniqueValues", + "Tomorrow", "Today", "Yesterday", "Last7Days", + "NextWeek", "ThisWeek", "LastWeek", + "NextMonth", "ThisMonth", "LastMonth", + "AboveAverage", "AboveOrEqualAverage", "BelowAverage", "BelowOrEqualAverage" + )] + [Alias("RuleType")] + $ConditionalType="ContainsText" + ) + + $obj = [PSCustomObject]@{ + Text = $Text + ConditionalTextColor = $ConditionalTextColor + ConditionalType = $ConditionalType + PatternType = $PatternType + Range = $Range + BackgroundColor = $BackgroundColor + } + + $obj.pstypenames.Clear() + $obj.pstypenames.Add("ConditionalText") + $obj +} \ No newline at end of file diff --git a/ExportedCommands/New-ExcelChartDefinition.ps1 b/ExportedCommands/New-ExcelChartDefinition.ps1 new file mode 100644 index 0000000..e657d84 --- /dev/null +++ b/ExportedCommands/New-ExcelChartDefinition.ps1 @@ -0,0 +1,88 @@ +function New-ExcelChartDefinition { + [Alias("New-ExcelChart")] #This was the former name. The new name reflects that we are defining a chart, not making one in the workbook. + [cmdletbinding()] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Does not change system State')] + param( + $Title = "Chart Title", + $Header, + [OfficeOpenXml.Drawing.Chart.eChartType]$ChartType = "ColumnStacked", + [OfficeOpenXml.Drawing.Chart.eTrendLine[]]$ChartTrendLine, + $XRange, + $YRange, + $Width = 500, + $Height = 350, + $Row = 0, + $RowOffSetPixels = 10, + $Column = 6, + $ColumnOffSetPixels = 5, + [OfficeOpenXml.Drawing.Chart.eLegendPosition]$LegendPosition, + $LegendSize, + [Switch]$LegendBold, + [Switch]$NoLegend, + [Switch]$ShowCategory, + [Switch]$ShowPercent, + $SeriesHeader, + [Switch]$TitleBold, + [Int]$TitleSize , + [String]$XAxisTitleText, + [Switch]$XAxisTitleBold, + $XAxisTitleSize , + [string]$XAxisNumberformat, + $XMajorUnit, + $XMinorUnit, + $XMaxValue, + $XMinValue, + [OfficeOpenXml.Drawing.Chart.eAxisPosition]$XAxisPosition , + [String]$YAxisTitleText, + [Switch]$YAxisTitleBold, + $YAxisTitleSize, + [string]$YAxisNumberformat, + $YMajorUnit, + $YMinorUnit, + $YMaxValue, + $YMinValue, + [OfficeOpenXml.Drawing.Chart.eAxisPosition]$YAxisPosition + ) + if ( $Header ) { Write-Warning "The header parameter is ignored." } #Nothing was done with it when creating a chart. + #might be able to do [PSCustomObject]$PsboundParameters, the defaults here match those in Add-Excel Chart + [PSCustomObject]@{ + Title = $Title + ChartType = $ChartType + ChartTrendLine = $ChartTrendLine + XRange = $XRange + YRange = $YRange + Width = $Width + Height = $Height + Row = $Row + RowOffSetPixels = $RowOffSetPixels + Column = $Column + ColumnOffSetPixels = $ColumnOffSetPixels + LegendPosition = $LegendPosition + LegendSize = $LegendSize + Legendbold = $LegendBold + NoLegend = $NoLegend -as [Boolean] + ShowCategory = $ShowCategory -as [Boolean] + ShowPercent = $ShowPercent -as [Boolean] + SeriesHeader = $SeriesHeader + TitleBold = $TitleBold -as [Boolean] + TitleSize = $TitleSize + XAxisTitleText = $XAxisTitleText + XAxisTitleBold = $XAxisTitleBold -as [Boolean] + XAxisTitleSize = $XAxisTitleSize + XAxisNumberformat = $XAxisNumberformat + XMajorUnit = $XMajorUnit + XMinorUnit = $XMinorUnit + XMaxValue = $XMaxValue + XMinValue = $XMinValue + XAxisPosition = $XAxisPosition + YAxisTitleText = $YAxisTitleText + YAxisTitleBold = $YAxisTitleBold -as [Boolean] + YAxisTitleSize = $YAxisTitleSize + YAxisNumberformat = $YAxisNumberformat + YMajorUnit = $YMajorUnit + YMinorUnit = $YMinorUnit + YMaxValue = $YMaxValue + YMinValue = $YMinValue + YAxisPosition = $YAxisPosition + } +} diff --git a/ExportedCommands/New-ExcelStyle.md b/ExportedCommands/New-ExcelStyle.md new file mode 100644 index 0000000..a71b355 --- /dev/null +++ b/ExportedCommands/New-ExcelStyle.md @@ -0,0 +1,570 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# New-ExcelStyle + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +New-ExcelStyle [[-Range] ] [[-NumberFormat] ] [[-BorderAround] ] + [[-BorderColor] ] [[-BorderBottom] ] [[-BorderTop] ] + [[-BorderLeft] ] [[-BorderRight] ] [[-FontColor] ] + [[-Value] ] [[-Formula] ] [-ArrayFormula] [-ResetFont] [-Bold] [-Italic] [-Underline] + [[-UnderLineType] ] [-StrikeThru] [[-FontShift] ] + [[-FontName] ] [[-FontSize] ] [[-BackgroundColor] ] + [[-BackgroundPattern] ] [[-PatternColor] ] [-WrapText] + [[-HorizontalAlignment] ] [[-VerticalAlignment] ] + [[-TextRotation] ] [-AutoSize] [[-Width] ] [[-Height] ] [-Hidden] [-Locked] [-Merge] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -ArrayFormula +{{ Fill ArrayFormula Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AutoSize +{{ Fill AutoSize Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: AutoFit + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BackgroundColor +{{ Fill BackgroundColor Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 15 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BackgroundPattern +{{ Fill BackgroundPattern Description }} + +```yaml +Type: ExcelFillStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Solid, DarkGray, MediumGray, LightGray, Gray125, Gray0625, DarkVertical, DarkHorizontal, DarkDown, DarkUp, DarkGrid, DarkTrellis, LightVertical, LightHorizontal, LightDown, LightUp, LightGrid, LightTrellis + +Required: False +Position: 16 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Bold +{{ Fill Bold Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderAround +{{ Fill BorderAround Description }} + +```yaml +Type: ExcelBorderStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Hair, Dotted, DashDot, Thin, DashDotDot, Dashed, MediumDashDotDot, MediumDashed, MediumDashDot, Thick, Medium, Double + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderBottom +{{ Fill BorderBottom Description }} + +```yaml +Type: ExcelBorderStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Hair, Dotted, DashDot, Thin, DashDotDot, Dashed, MediumDashDotDot, MediumDashed, MediumDashDot, Thick, Medium, Double + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderColor +{{ Fill BorderColor Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderLeft +{{ Fill BorderLeft Description }} + +```yaml +Type: ExcelBorderStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Hair, Dotted, DashDot, Thin, DashDotDot, Dashed, MediumDashDotDot, MediumDashed, MediumDashDot, Thick, Medium, Double + +Required: False +Position: 6 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderRight +{{ Fill BorderRight Description }} + +```yaml +Type: ExcelBorderStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Hair, Dotted, DashDot, Thin, DashDotDot, Dashed, MediumDashDotDot, MediumDashed, MediumDashDot, Thick, Medium, Double + +Required: False +Position: 7 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderTop +{{ Fill BorderTop Description }} + +```yaml +Type: ExcelBorderStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Hair, Dotted, DashDot, Thin, DashDotDot, Dashed, MediumDashDotDot, MediumDashed, MediumDashDot, Thick, Medium, Double + +Required: False +Position: 5 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FontColor +{{ Fill FontColor Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: ForegroundColor + +Required: False +Position: 8 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FontName +{{ Fill FontName Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 13 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FontShift +{{ Fill FontShift Description }} + +```yaml +Type: ExcelVerticalAlignmentFont +Parameter Sets: (All) +Aliases: +Accepted values: None, Baseline, Subscript, Superscript + +Required: False +Position: 12 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FontSize +{{ Fill FontSize Description }} + +```yaml +Type: Single +Parameter Sets: (All) +Aliases: + +Required: False +Position: 14 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Formula +{{ Fill Formula Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 10 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Height +{{ Fill Height Description }} + +```yaml +Type: Single +Parameter Sets: (All) +Aliases: + +Required: False +Position: 22 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Hidden +{{ Fill Hidden Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HorizontalAlignment +{{ Fill HorizontalAlignment Description }} + +```yaml +Type: ExcelHorizontalAlignment +Parameter Sets: (All) +Aliases: +Accepted values: General, Left, Center, CenterContinuous, Right, Fill, Distributed, Justify + +Required: False +Position: 18 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Italic +{{ Fill Italic Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Locked +{{ Fill Locked Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Merge +{{ Fill Merge Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NumberFormat +{{ Fill NumberFormat Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: NFormat + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PatternColor +{{ Fill PatternColor Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: PatternColour + +Required: False +Position: 17 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Range +{{ Fill Range Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: Address + +Required: False +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResetFont +{{ Fill ResetFont Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StrikeThru +{{ Fill StrikeThru Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TextRotation +{{ Fill TextRotation Description }} + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 20 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UnderLineType +{{ Fill UnderLineType Description }} + +```yaml +Type: ExcelUnderLineType +Parameter Sets: (All) +Aliases: +Accepted values: None, Single, Double, SingleAccounting, DoubleAccounting + +Required: False +Position: 11 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Underline +{{ Fill Underline Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Value +{{ Fill Value Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 9 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -VerticalAlignment +{{ Fill VerticalAlignment Description }} + +```yaml +Type: ExcelVerticalAlignment +Parameter Sets: (All) +Aliases: +Accepted values: Top, Center, Bottom, Distributed, Justify + +Required: False +Position: 19 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Width +{{ Fill Width Description }} + +```yaml +Type: Single +Parameter Sets: (All) +Aliases: + +Required: False +Position: 21 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WrapText +{{ Fill WrapText Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/ExportedCommands/New-ExcelStyle.ps1 b/ExportedCommands/New-ExcelStyle.ps1 new file mode 100644 index 0000000..f15b48f --- /dev/null +++ b/ExportedCommands/New-ExcelStyle.ps1 @@ -0,0 +1,45 @@ +function New-ExcelStyle { + param ( + [Alias("Address")] + $Range , + [Alias("NFormat")] + $NumberFormat, + [OfficeOpenXml.Style.ExcelBorderStyle]$BorderAround, + $BorderColor=[System.Drawing.Color]::Black, + [OfficeOpenXml.Style.ExcelBorderStyle]$BorderBottom, + [OfficeOpenXml.Style.ExcelBorderStyle]$BorderTop, + [OfficeOpenXml.Style.ExcelBorderStyle]$BorderLeft, + [OfficeOpenXml.Style.ExcelBorderStyle]$BorderRight, + [Alias('ForegroundColor')] + $FontColor, + $Value, + $Formula, + [Switch]$ArrayFormula, + [Switch]$ResetFont, + [Switch]$Bold, + [Switch]$Italic, + [Switch]$Underline, + [OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single, + [Switch]$StrikeThru, + [OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift, + [String]$FontName, + [float]$FontSize, + $BackgroundColor, + [OfficeOpenXml.Style.ExcelFillStyle]$BackgroundPattern = [OfficeOpenXml.Style.ExcelFillStyle]::Solid , + [Alias("PatternColour")] + $PatternColor, + [Switch]$WrapText, + [OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment, + [OfficeOpenXml.Style.ExcelVerticalAlignment]$VerticalAlignment, + [ValidateRange(-90, 90)] + [int]$TextRotation , + [Alias("AutoFit")] + [Switch]$AutoSize, + [float]$Width, + [float]$Height, + [Switch]$Hidden, + [Switch]$Locked, + [Switch]$Merge + ) + $PSBoundParameters +} \ No newline at end of file diff --git a/ExportedCommands/New-PSItem.md b/ExportedCommands/New-PSItem.md new file mode 100644 index 0000000..d2d8cac --- /dev/null +++ b/ExportedCommands/New-PSItem.md @@ -0,0 +1,42 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# New-PSItem + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +New-PSItem +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/New-PSItem.ps1 b/ExportedCommands/New-PSItem.ps1 similarity index 100% rename from New-PSItem.ps1 rename to ExportedCommands/New-PSItem.ps1 diff --git a/ExportedCommands/New-PivotTableDefinition.ps1 b/ExportedCommands/New-PivotTableDefinition.ps1 new file mode 100644 index 0000000..ce813c7 --- /dev/null +++ b/ExportedCommands/New-PivotTableDefinition.ps1 @@ -0,0 +1,72 @@ + +function New-PivotTableDefinition { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system State')] + param( + [Parameter(Mandatory)] + [Alias("PivtoTableName")]#Previous typo - use alias to avoid breaking scripts + $PivotTableName, + $SourceWorkSheet, + $SourceRange, + $PivotRows, + [hashtable]$PivotData, + $PivotColumns, + $PivotFilter, + [Switch]$PivotDataToColumn, + [ValidateSet("Both", "Columns", "Rows", "None")] + [String]$PivotTotals = "Both", + [Switch]$NoTotalsInPivot, + [String]$GroupDateRow, + [OfficeOpenXml.Table.PivotTable.eDateGroupBy[]]$GroupDatePart, + [String]$GroupNumericRow, + [double]$GroupNumericMin = 0 , + [double]$GroupNumericMax = [Double]::MaxValue , + [double]$GroupNumericInterval = 100 , + [string]$PivotNumberFormat, + [OfficeOpenXml.Table.TableStyles]$PivotTableStyle, + [Parameter(ParameterSetName = 'ChartbyDef', Mandatory = $true, ValueFromPipelineByPropertyName = $true)] + $PivotChartDefinition, + [Parameter(ParameterSetName = 'ChartbyParams')] + [Switch]$IncludePivotChart, + [Parameter(ParameterSetName = 'ChartbyParams')] + [String]$ChartTitle, + [Parameter(ParameterSetName = 'ChartbyParams')] + [int]$ChartHeight = 400 , + [Parameter(ParameterSetName = 'ChartbyParams')] + [int]$ChartWidth = 600, + [Parameter(ParameterSetName = 'ChartbyParams')] + [Int]$ChartRow = 0 , + [Parameter(ParameterSetName = 'ChartbyParams')] + [Int]$ChartColumn = 4, + [Parameter(ParameterSetName = 'ChartbyParams')] + [Int]$ChartRowOffSetPixels = 0 , + [Parameter(ParameterSetName = 'ChartbyParams')] + [Int]$ChartColumnOffSetPixels = 0, + [Parameter(ParameterSetName = 'ChartbyParams')] + [OfficeOpenXml.Drawing.Chart.eChartType]$ChartType = 'Pie', + [Parameter(ParameterSetName = 'ChartbyParams')] + [Switch]$NoLegend, + [Parameter(ParameterSetName = 'ChartbyParams')] + [Switch]$ShowCategory, + [Parameter(ParameterSetName = 'ChartbyParams')] + [Switch]$ShowPercent, + [switch]$Activate + ) + $validDataFuntions = [system.enum]::GetNames([OfficeOpenXml.Table.PivotTable.DataFieldFunctions]) + + if ($PivotData.values.Where( {$_ -notin $validDataFuntions}) ) { + Write-Warning -Message ("Pivot data functions might not be valid, they should be one of " + ($validDataFuntions -join ", ") + ".") + } + + $parameters = @{} + $PSBoundParameters + if ($NoTotalsInPivot) { + $parameters.Remove('NoTotalsInPivot') + $parameters["PivotTotals"] = "None" + } + $parameters.Remove('PivotTableName') + if ($PivotChartDefinition) { + $parameters.PivotChartDefinition.XRange = $null + $parameters.PivotChartDefinition.YRange = $null + $parameters.PivotChartDefinition.SeriesHeader = $null + } + @{$PivotTableName = $parameters} +} diff --git a/ExportedCommands/Open-ExcelPackage.ps1 b/ExportedCommands/Open-ExcelPackage.ps1 new file mode 100644 index 0000000..4277ba5 --- /dev/null +++ b/ExportedCommands/Open-ExcelPackage.ps1 @@ -0,0 +1,44 @@ +Function Open-ExcelPackage { + [CmdLetBinding()] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")] + [OutputType([OfficeOpenXml.ExcelPackage])] + Param ( + #The path to the file to open. + [Parameter(Mandatory=$true)]$Path, + #If specified, any running instances of Excel will be terminated before opening the file. + [switch]$KillExcel, + #The password for a protected worksheet, as a [normal] string (not a secure string). + [String]$Password, + #By default Open-ExcelPackage will only opens an existing file; -Create instructs it to create a new file if required. + [switch]$Create + ) + + if($KillExcel) { + Get-Process -Name "excel" -ErrorAction Ignore | Stop-Process + while (Get-Process -Name "excel" -ErrorAction Ignore) {} + } + + $Path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path) + #If -Create was not specified only open the file if it exists already (send a warning if it doesn't exist). + if ($Create -and -not (Test-Path -Path $path)) { + #Create the directory if required. + $targetPath = Split-Path -Parent -Path $Path + if (!(Test-Path -Path $targetPath)) { + Write-Debug "Base path $($targetPath) does not exist, creating" + $null = New-item -ItemType Directory -Path $targetPath -ErrorAction Ignore + } + New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Path + } + elseif (Test-Path -Path $path) { + if ($Password) {$pkgobj = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Path , $Password } + else {$pkgobj = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Path } + if ($pkgobj) { + foreach ($w in $pkgobj.Workbook.Worksheets) { + $sb = [scriptblock]::Create(('$this.workbook.Worksheets["{0}"]' -f $w.name)) + Add-Member -InputObject $pkgobj -MemberType ScriptProperty -Name $w.name -Value $sb + } + return $pkgobj + } + } + else {Write-Warning "Could not find $path" } + } diff --git a/RemoveWorksheet.ps1 b/ExportedCommands/Remove-WorkSheet.ps1 similarity index 53% rename from RemoveWorksheet.ps1 rename to ExportedCommands/Remove-WorkSheet.ps1 index 1e919c5..2d465e1 100644 --- a/RemoveWorksheet.ps1 +++ b/ExportedCommands/Remove-WorkSheet.ps1 @@ -1,21 +1,4 @@ Function Remove-WorkSheet { - <# - .SYNOPSIS - Removes one or more worksheets from one or more workbooks - .EXAMPLE - C:\> Remove-WorkSheet -Path Test1.xlsx -WorksheetName Sheet1 - Removes the worksheet named 'Sheet1' from 'Test1.xlsx' - - C:\> Remove-WorkSheet -Path Test1.xlsx -WorksheetName Sheet1,Target1 - Removes the worksheet named 'Sheet1' and 'Target1' from 'Test1.xlsx' - - C:\> Remove-WorkSheet -Path Test1.xlsx -WorksheetName Sheet1,Target1 -Show - Removes the worksheets and then launches the xlsx in Excel - - C:\> dir c:\reports\*.xlsx | Remove-WorkSheet - Removes 'Sheet1' from all the xlsx files in the c:\reports directory - - #> [cmdletbinding(SupportsShouldProcess=$true)] param( # [Parameter(ValueFromPipelineByPropertyName)] diff --git a/ExportedCommands/Select-Worksheet.ps1 b/ExportedCommands/Select-Worksheet.ps1 new file mode 100644 index 0000000..0385876 --- /dev/null +++ b/ExportedCommands/Select-Worksheet.ps1 @@ -0,0 +1,24 @@ +function Select-Worksheet { + param ( + [Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Package', Position = 0)] + [OfficeOpenXml.ExcelPackage]$ExcelPackage, + [Parameter(Mandatory = $true, ParameterSetName = 'Workbook')] + [OfficeOpenXml.ExcelWorkbook]$ExcelWorkbook, + [Parameter(ParameterSetName='Package')] + [Parameter(ParameterSetName='Workbook')] + [string]$WorksheetName, + [Parameter(ParameterSetName='Sheet',Mandatory=$true)] + [OfficeOpenXml.ExcelWorksheet]$ExcelWorksheet + ) + #if we were given a package, use its workbook + if ($ExcelPackage -and -not $ExcelWorkbook) {$ExcelWorkbook = $ExcelPackage.Workbook} + #if we now have workbook, get the worksheet; if we were given a sheet get the workbook + if ($ExcelWorkbook -and $WorksheetName) {$ExcelWorksheet = $ExcelWorkbook.Worksheets[$WorksheetName]} + elseif ($ExcelWorksheet -and -not $ExcelWorkbook) {$ExcelWorkbook = $ExcelWorksheet.Workbook ; } + #if we didn't get to a worksheet give up. If we did set all works sheets to not selected and then the one we want to selected. + if (-not $ExcelWorksheet) {Write-Warning -Message "The worksheet $WorksheetName was not found." ; return } + else { + foreach ($w in $ExcelWorkbook.Worksheets) {$w.View.TabSelected = $false} + $ExcelWorksheet.View.TabSelected = $true + } +} diff --git a/Send-SQLDataToExcel.ps1 b/ExportedCommands/Send-SQLDataToExcel.ps1 similarity index 51% rename from Send-SQLDataToExcel.ps1 rename to ExportedCommands/Send-SQLDataToExcel.ps1 index c7c3555..0ba3169 100644 --- a/Send-SQLDataToExcel.ps1 +++ b/ExportedCommands/Send-SQLDataToExcel.ps1 @@ -1,96 +1,4 @@ Function Send-SQLDataToExcel { - <# - .SYNOPSIS - Inserts a DataTable - returned by a SQL query - into an ExcelSheet - .DESCRIPTION - This command takes a SQL statement and run it against a database connection; for the connection it accepts either - * an object representing a session with a SQL server or ODBC database, or - * a connection string to make a session (if -MSSQLServer is specified it uses the SQL Native client, - and -Connection can be a server name instead of a detailed connection string. Without this switch it uses ODBC) - The command takes all the parameters of Export-Excel, except for -InputObject (alias TargetData); after - fetching the data it calls Export-Excel with the data as the value of InputParameter and whichever of - Export-Excel's parameters it was passed; for details of these parameters see the help for Export-Excel. - .PARAMETER Session - An active ODBC Connection or SQL connection object representing a session with a database which will be queried to get the data . - .PARAMETER Connection - A database connection string to be used to create a database session; either - * A Data source name written in the form DSN=ODBC_Data_Source_Name, or - * A full ODBC or SQL Native Client Connection string, or - * The name of a SQL server. - .PARAMETER MSSQLServer - Specifies the connection string is for SQL server, not ODBC. - .PARAMETER SQL - The SQL query to run against the session which was passed in -Session or set up from -Connection. - .PARAMETER Database - Switches to a specific database on a SQL server. - .PARAMETER QueryTimeout - Override the default query time of 30 seconds. - .PARAMETER DataTable - A System.Data.DataTable object containing the data to be inserted into the spreadsheet without running a query. - This remains supported to avoid breaking older scripts, but if you have a DataTable object you can pass the it - into Export-Excel using -InputObject. - .PARAMETER Force - If specified Export-Excel will be called with parameters specified, even if there is no data to send - .EXAMPLE - C:\> Send-SQLDataToExcel -MsSQLserver -Connection localhost -SQL "select name,type,type_desc from [master].[sys].[all_objects]" -Path .\temp.xlsx -WorkSheetname master -AutoSize -FreezeTopRow -AutoFilter -BoldTopRow - - Connects to the local SQL server and selects 3 columns from [Sys].[all_objects] and exports then to a sheet named master with some basic header management - .EXAMPLE - C:\> $dbPath = 'C:\Users\James\Documents\Database1.accdb' - C:\> $Connection = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=$dbPath;" - C:\> $SQL="SELECT top 25 Name,Length From TestData ORDER BY Length DESC" - - C:\> 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 - C:\> $dbPath = 'C:\users\James\Documents\f1Results.xlsx' - C:\> $Connection = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};Dbq=$dbPath;" - C:\> $SQL="SELECT top 25 DriverName, Count(RaceDate) as Races, Count(Win) as Wins, Count(Pole) as Poles, Count(FastestLap) as Fastlaps " + - " FROM Results GROUP BY DriverName ORDER BY (count(win)) DESC" - - C:\> 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 - C:\> $dbPath = 'C:\users\James\Documents\f1Results.xlsx' - C:\> $SQL = "SELECT top 25 DriverName, Count(RaceDate) as Races, Count(Win) as Wins, Count(Pole) as Poles, Count(FastestLap) as Fastlaps " + - " FROM Results GROUP BY DriverName ORDER BY (count(win)) DESC" - C:\> $null = Get-SQL -Session F1 -excel -Connection $dbPath -sql $sql -OutputVariable Table - - C:\> Send-SQLDataToExcel -DataTable $Table -Path ".\demo3.xlsx" -WorkSheetname Gpwinners -autosize -TableName winners -TableStyle Light6 -show - - This uses Get-SQL (at least V1.1 - download from the PowerShell gallery with Install-Module -Name GetSQL - - note the function is Get-SQL the module is GetSQL without the "-" ) - Get-SQL simplify 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 - C:\> Export-Excel -inputObject $Table -Path ".\demo3.xlsx" -WorkSheetname Gpwinners -autosize -TableName winners -TableStyle Light6 -show - This is quicker than using - C:\> Get-SQL | export-excel -ExcludeProperty rowerror,rowstate,table,itemarray,haserrors - (the F1 results database is available from https://1drv.ms/x/s!AhfYu7-CJv4ehNdZWxJE9LMAX_N5sg ) - .EXAMPLE - C:\> $SQL = "SELECT top 25 DriverName, Count(Win) as Wins FROM Results GROUP BY DriverName ORDER BY (count(win)) DESC" - C:\> 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 - C:\> 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 - - .Link - Export-Excel - #> [CmdletBinding(DefaultParameterSetName="none")] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '', Justification="Allowed to use DBSessions Global variable from GETSQL Module")] diff --git a/ExportedCommands/Set-CellStyle.md b/ExportedCommands/Set-CellStyle.md new file mode 100644 index 0000000..c312af2 --- /dev/null +++ b/ExportedCommands/Set-CellStyle.md @@ -0,0 +1,119 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Set-CellStyle + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Set-CellStyle [[-WorkSheet] ] [[-Row] ] [[-LastColumn] ] [[-Pattern] ] + [[-Color] ] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -Color +{{ Fill Color Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LastColumn +{{ Fill LastColumn Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Pattern +{{ Fill Pattern Description }} + +```yaml +Type: ExcelFillStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Solid, DarkGray, MediumGray, LightGray, Gray125, Gray0625, DarkVertical, DarkHorizontal, DarkDown, DarkUp, DarkGrid, DarkTrellis, LightVertical, LightHorizontal, LightDown, LightUp, LightGrid, LightTrellis + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Row +{{ Fill Row Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WorkSheet +{{ Fill WorkSheet Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/Set-CellStyle.ps1 b/ExportedCommands/Set-CellStyle.ps1 similarity index 100% rename from Set-CellStyle.ps1 rename to ExportedCommands/Set-CellStyle.ps1 diff --git a/Set-Column.ps1 b/ExportedCommands/Set-ExcelColumn.ps1 similarity index 57% rename from Set-Column.ps1 rename to ExportedCommands/Set-ExcelColumn.ps1 index 05543a5..2d080a1 100644 --- a/Set-Column.ps1 +++ b/ExportedCommands/Set-ExcelColumn.ps1 @@ -1,131 +1,50 @@ Function Set-ExcelColumn { - <# - .SYNOPSIS - Adds or modifies a column in an Excel worksheet, filling values, setting formatting and/or creating named ranges. - .DESCRIPTION - Set-ExcelColumn can take a value which is either a string containing a - value or formula or a scriptblock which evaluates to a string, - and optionally a column number and fills that value down the column. - A column heading can be specified, and the column can be made a named range. - The column can be formatted in the same operation. - .EXAMPLE - Set-ExcelColumn -Worksheet $ws -Column 5 -NumberFormat 'Currency' - - $ws contains a worksheet object - and column "E" is set to use the - local currency format. Intelisense will complete the names of predefined - number formats. You can see how currency is interpreted on the - local computer with the command - Expand-NumberFormat currency - .EXAMPLE - Set-ExcelColumn -Worksheet $ws -Heading "WinsToFastLaps" -Value {"=E$row/C$row"} -Column 7 -AutoSize -AutoNameRange - - Here, $WS already contains a worksheet which 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 prevent - Variables merging into other parts of the string, use the back tick "$columnName`4" will - be "G4" - withouth the backtick the string will look for a variable named "columnName4" - - .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 a script block which - outputs a string beginning "https..." and ending with the value of - the cell at column B in the current row. - When given a valid URI, Set-ExcelColumn makes it a hyperlink. - The column will be autosized to fit the links. - .EXAMPLE - 4..6 | Set-ExcelColumn -Worksheet $ws -AutoNameRange - - Again $ws contains a worksheet. Here columns 4 to 6 are made into - named ranges, row 1 is used for the range name - and the rest of the column becomes the range. - #> [cmdletbinding()] [Alias("Set-Column")] [OutputType([OfficeOpenXml.ExcelColumn],[String])] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system state')] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification="Variables created for script block which may be passed as a parameter, but not used in the script")] Param ( - #If specifying the worksheet by name, the ExcelPackage object which contains the worksheet also needs to be passed. [Parameter(ParameterSetName="Package",Mandatory=$true)] [OfficeOpenXml.ExcelPackage]$ExcelPackage, - #The sheet to update can be given as a name or an Excel Worksheet object - this sets it by name. [Parameter(ParameterSetName="Package")] [String]$Worksheetname = "Sheet1", - #This passes the worksheet object instead of passing a sheet name and an Excelpackage object. [Parameter(ParameterSetName="sheet",Mandatory=$true)] [OfficeOpenXml.ExcelWorksheet]$Worksheet, - #Column to fill down - the first column is 1. 0 will be interpreted as first empty column. [Parameter(ValueFromPipeline=$true)] [ValidateRange(0,16384)] $Column = 0 , - #First row to fill data in. [ValidateRange(1,1048576)] [Int]$StartRow , - #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. $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. [Alias("NFormat")] $NumberFormat, - #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. $FontColor, - #Make text bold; use -Bold:$false to remove bold. [Switch]$Bold, - #Make text italic; use -Italic:$false to remove italic. [Switch]$Italic, - #Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. [Switch]$Underline, - #Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". [OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single, - #Strike through text; use -StrikeThru:$false to remove strike through. [Switch]$StrikeThru, - #Subscript or Superscript (or None). [OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift, - #Font to use - Excel defaults to Calibri. [String]$FontName, - #Point size for the text. [float]$FontSize, - #Change background color. $BackgroundColor, - #Background pattern - "Solid" by default. [OfficeOpenXml.Style.ExcelFillStyle]$BackgroundPattern = [OfficeOpenXml.Style.ExcelFillStyle]::Solid , - #Secondary color for background pattern. [Alias("PatternColour")] $PatternColor, - #Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. [Switch]$WrapText, - #Position cell contents to Left, Right, Center etc. Default is "General". [OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment, - #Position cell contents to Top, Bottom or Center. [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 , - #Attempt to auto-fit cells to the width their contents. [Alias("AutoFit")] [Switch]$AutoSize, - #Set cells to a fixed width, ignored if -AutoSize is specified. [float]$Width, - #Set the inserted data to be a named range. [Switch]$AutoNameRange, - #Hide the column. [Switch]$Hide, - #If specified, returns the range of cells which were affected. [Switch]$Specified, - #If specified, return an object representing the Column, to allow further work to be done on it. [Switch]$PassThru ) diff --git a/ExportedCommands/Set-ExcelRange.ps1 b/ExportedCommands/Set-ExcelRange.ps1 new file mode 100644 index 0000000..49ca0d0 --- /dev/null +++ b/ExportedCommands/Set-ExcelRange.ps1 @@ -0,0 +1,199 @@ +function Set-ExcelRange { + [cmdletbinding()] + [Alias("Set-Format")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system state')] + Param ( + [Parameter(ValueFromPipeline = $true,Position=0)] + [Alias("Address")] + $Range , + [OfficeOpenXml.ExcelWorksheet]$WorkSheet , + [Alias("NFormat")] + $NumberFormat, + [OfficeOpenXml.Style.ExcelBorderStyle]$BorderAround, + $BorderColor=[System.Drawing.Color]::Black, + [OfficeOpenXml.Style.ExcelBorderStyle]$BorderBottom, + [OfficeOpenXml.Style.ExcelBorderStyle]$BorderTop, + [OfficeOpenXml.Style.ExcelBorderStyle]$BorderLeft, + [OfficeOpenXml.Style.ExcelBorderStyle]$BorderRight, + [Alias('ForegroundColor')] + $FontColor, + $Value, + $Formula, + [Switch]$ArrayFormula, + [Switch]$ResetFont, + [Switch]$Bold, + [Switch]$Italic, + [Switch]$Underline, + [OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single, + [Switch]$StrikeThru, + [OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift, + [String]$FontName, + [float]$FontSize, + $BackgroundColor, + [OfficeOpenXml.Style.ExcelFillStyle]$BackgroundPattern = [OfficeOpenXml.Style.ExcelFillStyle]::Solid , + [Alias("PatternColour")] + $PatternColor, + [Switch]$WrapText, + [OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment, + [OfficeOpenXml.Style.ExcelVerticalAlignment]$VerticalAlignment, + [ValidateRange(-90, 90)] + [int]$TextRotation , + [Alias("AutoFit")] + [Switch]$AutoSize, + [float]$Width, + [float]$Height, + [Switch]$Hidden, + [Switch]$Locked, + [Switch]$Merge + ) + process { + if ($Range -is [Array]) { + $null = $PSBoundParameters.Remove("Range") + $Range | Set-ExcelRange @PSBoundParameters + } + else { + #We should accept, a worksheet and a name of a range or a cell address; a table; the address of a table; a named range; a row, a column or .Cells[ ] + if ($Range -is [OfficeOpenXml.Table.ExcelTable]) {$Range = $Range.Address} + elseif ($WorkSheet -and ($Range -is [string] -or $Range -is [OfficeOpenXml.ExcelAddress])) { + $Range = $WorkSheet.Cells[$Range] + } + elseif ($Range -is [string]) {Write-Warning -Message "The range pararameter you have specified also needs a worksheet parameter." ;return} + #else we assume $Range is a range. + if ($ClearAll) { + $Range.Clear() + } + if ($ResetFont) { + $Range.Style.Font.Color.SetColor( ([System.Drawing.Color]::Black)) + $Range.Style.Font.Bold = $false + $Range.Style.Font.Italic = $false + $Range.Style.Font.UnderLine = $false + $Range.Style.Font.Strike = $false + $Range.Style.Font.VerticalAlign = [OfficeOpenXml.Style.ExcelVerticalAlignmentFont]::None + } + if ($PSBoundParameters.ContainsKey('Underline')) { + $Range.Style.Font.UnderLine = [boolean]$Underline + $Range.Style.Font.UnderLineType = $UnderLineType + } + if ($PSBoundParameters.ContainsKey('Bold')) { + $Range.Style.Font.Bold = [boolean]$bold + } + if ($PSBoundParameters.ContainsKey('Italic')) { + $Range.Style.Font.Italic = [boolean]$italic + } + if ($PSBoundParameters.ContainsKey('StrikeThru')) { + $Range.Style.Font.Strike = [boolean]$StrikeThru + } + if ($PSBoundParameters.ContainsKey('FontSize')){ + $Range.Style.Font.Size = $FontSize + } + if ($PSBoundParameters.ContainsKey('FontName')){ + $Range.Style.Font.Name = $FontName + } + if ($PSBoundParameters.ContainsKey('FontShift')){ + $Range.Style.Font.VerticalAlign = $FontShift + } + if ($PSBoundParameters.ContainsKey('FontColor')){ + if ($FontColor -is [string]) {$FontColor = [System.Drawing.Color]::$FontColor } + $Range.Style.Font.Color.SetColor( $FontColor) + } + if ($PSBoundParameters.ContainsKey('TextRotation')) { + $Range.Style.TextRotation = $TextRotation + } + if ($PSBoundParameters.ContainsKey('WrapText')) { + $Range.Style.WrapText = [boolean]$WrapText + } + if ($PSBoundParameters.ContainsKey('HorizontalAlignment')) { + $Range.Style.HorizontalAlignment = $HorizontalAlignment + } + if ($PSBoundParameters.ContainsKey('VerticalAlignment')) { + $Range.Style.VerticalAlignment = $VerticalAlignment + } + if ($PSBoundParameters.ContainsKey('Merge')) { + $Range.Merge = [boolean]$Merge + } + if ($PSBoundParameters.ContainsKey('Value')) { + if ($Value -match '^=') {$PSBoundParameters["Formula"] = $Value -replace '^=','' } + else { + $Range.Value = $Value + if ($Value -is [datetime]) { $Range.Style.Numberformat.Format = 'm/d/yy h:mm' }# This is not a custom format, but a preset recognized as date and localized. It might be overwritten in a moment + if ($Value -is [timespan]) { $Range.Style.Numberformat.Format = '[h]:mm:ss' } + } + } + if ($PSBoundParameters.ContainsKey('Formula')) { + if ($ArrayFormula) {$Range.CreateArrayFormula(($Formula -replace '^=','')) } + else {$Range.Formula = ($Formula -replace '^=','') } + } + if ($PSBoundParameters.ContainsKey('NumberFormat')) { + $Range.Style.Numberformat.Format = (Expand-NumberFormat $NumberFormat) + } + if ($BorderColor -is [string]) {$BorderColor = [System.Drawing.Color]::$BorderColor } + if ($PSBoundParameters.ContainsKey('BorderAround')) { + $Range.Style.Border.BorderAround($BorderAround, $BorderColor) + } + if ($PSBoundParameters.ContainsKey('BorderBottom')) { + $Range.Style.Border.Bottom.Style=$BorderBottom + $Range.Style.Border.Bottom.Color.SetColor($BorderColor) + } + if ($PSBoundParameters.ContainsKey('BorderTop')) { + $Range.Style.Border.Top.Style=$BorderTop + $Range.Style.Border.Top.Color.SetColor($BorderColor) + } + if ($PSBoundParameters.ContainsKey('BorderLeft')) { + $Range.Style.Border.Left.Style=$BorderLeft + $Range.Style.Border.Left.Color.SetColor($BorderColor) + } + if ($PSBoundParameters.ContainsKey('BorderRight')) { + $Range.Style.Border.Right.Style=$BorderRight + $Range.Style.Border.Right.Color.SetColor($BorderColor) + } + if ($PSBoundParameters.ContainsKey('BackgroundColor')) { + $Range.Style.Fill.PatternType = $BackgroundPattern + if ($BackgroundColor -is [string]) {$BackgroundColor = [System.Drawing.Color]::$BackgroundColor } + $Range.Style.Fill.BackgroundColor.SetColor($BackgroundColor) + if ($PatternColor) { + if ($PatternColor -is [string]) {$PatternColor = [System.Drawing.Color]::$PatternColor } + $Range.Style.Fill.PatternColor.SetColor( $PatternColor) + } + } + if ($PSBoundParameters.ContainsKey('Height')) { + if ($Range -is [OfficeOpenXml.ExcelRow] ) {$Range.Height = $Height } + elseif ($Range -is [OfficeOpenXml.ExcelRange] ) { + ($Range.Start.Row)..($Range.Start.Row + $Range.Rows) | + ForEach-Object {$Range.WorkSheet.Row($_).Height = $Height } + } + else {Write-Warning -Message ("Can set the height of a row or a range but not a {0} object" -f ($Range.GetType().name)) } + } + if ($Autosize -and -not $env:NoAutoSize) { + try { + if ($Range -is [OfficeOpenXml.ExcelColumn]) {$Range.AutoFit() } + elseif ($Range -is [OfficeOpenXml.ExcelRange] ) { + $Range.AutoFitColumns() + + } + else {Write-Warning -Message ("Can autofit a column or a range but not a {0} object" -f ($Range.GetType().name)) } + } + catch {Write-Warning -Message "Failed autosizing columns of worksheet '$WorksheetName': $_"} + } + elseif ($AutoSize) {Write-Warning -Message "Auto-fitting columns is not available with this OS configuration." } + elseif ($PSBoundParameters.ContainsKey('Width')) { + if ($Range -is [OfficeOpenXml.ExcelColumn]) {$Range.Width = $Width} + elseif ($Range -is [OfficeOpenXml.ExcelRange] ) { + ($Range.Start.Column)..($Range.Start.Column + $Range.Columns - 1) | + ForEach-Object { + #$ws.Column($_).Width = $Width + $Range.Worksheet.Column($_).Width = $Width + } + } + else {Write-Warning -Message ("Can set the width of a column or a range but not a {0} object" -f ($Range.GetType().name)) } + } + if ($PSBoundParameters.ContainsKey('Hidden')) { + if ($Range -is [OfficeOpenXml.ExcelRow] -or + $Range -is [OfficeOpenXml.ExcelColumn] ) {$Range.Hidden = [boolean]$Hidden} + else {Write-Warning -Message ("Can hide a row or a column but not a {0} object" -f ($Range.GetType().name)) } + } + if ($PSBoundParameters.ContainsKey('Locked')) { + $Range.Style.Locked=$Locked + } + } + } +} diff --git a/Set-Row.ps1 b/ExportedCommands/Set-ExcelRow.ps1 similarity index 64% rename from Set-Row.ps1 rename to ExportedCommands/Set-ExcelRow.ps1 index 0b3115b..67ef805 100644 --- a/Set-Row.ps1 +++ b/ExportedCommands/Set-ExcelRow.ps1 @@ -1,119 +1,52 @@ Function Set-ExcelRow { - <# - .Synopsis - Fills values into a [new] row in an Excel spreadsheet, and sets row formats. - .Description - Set-ExcelRow accepts either a Worksheet object or an ExcelPackage object - returned by Export-Excel and the name of a sheet, and inserts the chosen - contents into a row of the sheet. The contents can be a constant, - like "42", a formula or a script block which is converted into a - constant or a formula. - The first cell of the row can optionally be given a heading. - .Example - Set-ExcelRow -Worksheet $ws -Heading Total -Value {"=sum($columnName`2:$columnName$endrow)" } - - $Ws contains a worksheet object, and no Row number is specified so - Set-ExcelRow will select the next row after the end of the data in - the sheet. The first cell in the row will contain "Total", and - each of the other cells will contain - =Sum(xx2:xx99) - where xx is the column name, and 99 is the last row of data. - Note the use of `2 to Prevent 2 becoming part of the variable "ColumnName" - The script block can use $Worksheet, $Row, $Column (number), - $ColumnName (letter), $StartRow/Column and $EndRow/Column. - .Example - Set-ExcelRow -Worksheet $ws -Heading Total -HeadingBold -Value {"=sum($columnName`2:$columnName$endrow)" } -NumberFormat 'Currency' -StartColumn 2 -Bold -BorderTop Double -BorderBottom Thin - - This builds on the previous example, but this time the label "Total" - appears in column 2 and the formula fills from column 3 onwards. - The formula and heading are set in bold face, and the formula is - formatted for the local currency, and given a double line border - above and single line border below. - #> [cmdletbinding()] [Alias("Set-Row")] [OutputType([OfficeOpenXml.ExcelRow],[String])] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system state')] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification="Variables created for script block which may be passed as a parameter, but not used in the script")] Param ( - #An Excel package object - e.g. from Export-Excel -PassThru - requires a sheet name. [Parameter(ParameterSetName="Package",Mandatory=$true)] [OfficeOpenXml.ExcelPackage]$ExcelPackage, - #The name of the sheet to update in the package. [Parameter(ParameterSetName="Package")] $Worksheetname = "Sheet1", - #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. [Parameter(ValueFromPipeline = $true)] $Row = 0 , - #Position in the row to start from. [int]$StartColumn, - #Value, Formula or ScriptBlock to fill in. A ScriptBlock can use $worksheet, $row, $Column [number], $ColumnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn. $Value, - #Optional row-heading. $Heading , - #Set the heading in bold type. [Switch]$HeadingBold, - #Change the font-size of the heading. [Int]$HeadingSize , - #Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc. [Alias("NFormat")] $NumberFormat, - #Style of border to draw around the row. [OfficeOpenXml.Style.ExcelBorderStyle]$BorderAround, - #Color of the border. $BorderColor=[System.Drawing.Color]::Black, - #Style for the bottom border. [OfficeOpenXml.Style.ExcelBorderStyle]$BorderBottom, - #Style for the top border. [OfficeOpenXml.Style.ExcelBorderStyle]$BorderTop, - #Style for the left border. [OfficeOpenXml.Style.ExcelBorderStyle]$BorderLeft, - #Style for the right border. [OfficeOpenXml.Style.ExcelBorderStyle]$BorderRight, - #Color for the text - if none specified it will be left as it it is. $FontColor, - #Make text bold; use -Bold:$false to remove bold. [Switch]$Bold, - #Make text italic; use -Italic:$false to remove italic. [Switch]$Italic, - #Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. [Switch]$Underline, - #Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". [OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single, - #Strike through text; use -StrikeThru:$false to remove strike through. [Switch]$StrikeThru, - #Subscript or Superscript (or none). [OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift, - #Font to use - Excel defaults to Calibri. [String]$FontName, - #Point size for the text. [float]$FontSize, - #Change background color. $BackgroundColor, - #Background pattern - solid by default. [OfficeOpenXml.Style.ExcelFillStyle]$BackgroundPattern = [OfficeOpenXml.Style.ExcelFillStyle]::Solid , - #Secondary color for background pattern. [Alias("PatternColour")] $PatternColor, - #Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. [Switch]$WrapText, - #Position cell contents to Left, Right, Center etc. default is 'General'. [OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment, - #Position cell contents to Top, Bottom or Center. [OfficeOpenXml.Style.ExcelVerticalAlignment]$VerticalAlignment, - #Degrees to rotate text. Up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise. [ValidateRange(-90, 90)] [int]$TextRotation , - #Set cells to a fixed height. [float]$Height, - #Hide the row. [Switch]$Hide, - #If sepecified, returns the range of cells which were affected. [Switch]$ReturnRange, - #If Specified, return a row object to allow further work to be done. [Switch]$PassThru ) begin { diff --git a/ExportedCommands/Set-WorkSheetProtection.md b/ExportedCommands/Set-WorkSheetProtection.md new file mode 100644 index 0000000..ec1c389 --- /dev/null +++ b/ExportedCommands/Set-WorkSheetProtection.md @@ -0,0 +1,349 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Set-WorkSheetProtection + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Set-WorkSheetProtection [-WorkSheet] [-IsProtected] [-AllowAll] [-BlockSelectLockedCells] + [-BlockSelectUnlockedCells] [-AllowFormatCells] [-AllowFormatColumns] [-AllowFormatRows] [-AllowInsertColumns] + [-AllowInsertRows] [-AllowInsertHyperlinks] [-AllowDeleteColumns] [-AllowDeleteRows] [-AllowSort] + [-AllowAutoFilter] [-AllowPivotTables] [-BlockEditObject] [-BlockEditScenarios] [[-LockAddress] ] + [[-UnLockAddress] ] [] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -AllowAll +{{ Fill AllowAll Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AllowAutoFilter +{{ Fill AllowAutoFilter Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AllowDeleteColumns +{{ Fill AllowDeleteColumns Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AllowDeleteRows +{{ Fill AllowDeleteRows Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AllowFormatCells +{{ Fill AllowFormatCells Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AllowFormatColumns +{{ Fill AllowFormatColumns Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AllowFormatRows +{{ Fill AllowFormatRows Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AllowInsertColumns +{{ Fill AllowInsertColumns Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AllowInsertHyperlinks +{{ Fill AllowInsertHyperlinks Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AllowInsertRows +{{ Fill AllowInsertRows Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AllowPivotTables +{{ Fill AllowPivotTables Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AllowSort +{{ Fill AllowSort Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BlockEditObject +{{ Fill BlockEditObject Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BlockEditScenarios +{{ Fill BlockEditScenarios Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BlockSelectLockedCells +{{ Fill BlockSelectLockedCells Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BlockSelectUnlockedCells +{{ Fill BlockSelectUnlockedCells Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -IsProtected +{{ Fill IsProtected Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LockAddress +{{ Fill LockAddress Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UnLockAddress +{{ Fill UnLockAddress Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WorkSheet +{{ Fill WorkSheet Description }} + +```yaml +Type: ExcelWorksheet +Parameter Sets: (All) +Aliases: + +Required: True +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/Set-WorkSheetProtection.ps1 b/ExportedCommands/Set-WorkSheetProtection.ps1 similarity index 51% rename from Set-WorkSheetProtection.ps1 rename to ExportedCommands/Set-WorkSheetProtection.ps1 index 1b46560..e17f3c7 100644 --- a/Set-WorkSheetProtection.ps1 +++ b/ExportedCommands/Set-WorkSheetProtection.ps1 @@ -1,56 +1,27 @@ Function Set-WorkSheetProtection { [Cmdletbinding()] - <# - .Synopsis - Sets protection on the worksheet - .Description - - .Example - Set-WorkSheetProtection -WorkSheet $planSheet -IsProtected -AllowAll -AllowInsertColumns:$false -AllowDeleteColumns:$false -UnLockAddress "A:N" - Turns on protection for the worksheet in $planSheet, checks all the allow boxes except Insert and Delete columns and unlocks columns A-N - #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system state')] param ( - #The worksheet where protection is to be applied. [Parameter(Mandatory=$true)] [OfficeOpenXml.ExcelWorksheet]$WorkSheet , - #Value of the "Protect Worksheet and Contents of locked cells" check box. Initially FALSE. use -IsProtected:$false to turn off it it has been switched on [switch]$IsProtected, - #If provided sets all the ALLOW options to true or false and then allows them to be changed individually [switch]$AllowAll, - #Opposite of the value in the 'Select locked cells' check box. Set to allow when Protect is first enabled [switch]$BlockSelectLockedCells, - #Opposite of the value in the 'Select unlocked cells' check box. Set to allow when Protect is first enabled [switch]$BlockSelectUnlockedCells, - #Value of the 'Format Cells' check box. Set to block when Protect is first enabled [switch]$AllowFormatCells, - #Value of the 'Format Columns' check box. Set to block when Protect is first enabled [switch]$AllowFormatColumns, - #Value of the 'Format Rows' check box. Set to block when Protect is first enabled [switch]$AllowFormatRows, - #Value of the 'Insert Columns' check box. Set to block when Protect is first enabled [switch]$AllowInsertColumns, - #Value of the 'Insert Columns' check box. Set to block when Protect is first enabled [switch]$AllowInsertRows, - #Value of the 'Insert Hyperlinks' check box. Set to block when Protect is first enabled [switch]$AllowInsertHyperlinks, - #Value of the 'Delete Columns' check box. Set to block when Protect is first enabled [switch]$AllowDeleteColumns, - #Value of the 'Delete Rows' check box. Set to block when Protect is first enabled [switch]$AllowDeleteRows, - #Value of the 'Sort' check box. Set to block when Protect is first enabled [switch]$AllowSort, - #Value of the 'Use AutoFilter' check box. Set to block when Protect is first enabled [switch]$AllowAutoFilter, - #Value of the 'Use PivotTable and PivotChart' check box. Set to block when Protect is first enabled [switch]$AllowPivotTables, - ##Opposite of the value in the 'Edit objects' check box. Set to allow when Protect is first enabled [switch]$BlockEditObject, - ##Opposite of the value in the 'Edit Scenarios' check box. Set to allow when Protect is first enabled [switch]$BlockEditScenarios, - #Address range for cells to lock in the form "A:Z" or "1:10" or "A1:Z10". If No range is specified, the whole sheet is locked by default. [string]$LockAddress, - #Address range for cells to Unlock in the form "A:Z" or "1:10" or "A1:Z10" [string]$UnLockAddress ) diff --git a/ExportedCommands/Update-FirstObjectProperties.ps1 b/ExportedCommands/Update-FirstObjectProperties.ps1 new file mode 100644 index 0000000..c859576 --- /dev/null +++ b/ExportedCommands/Update-FirstObjectProperties.ps1 @@ -0,0 +1,23 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Scope='Function', Target='Update*', Justification='Does not change system state')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Scope='Function', Target='Update*', Justification='Property would be incorrect')] + +param() + +Function Update-FirstObjectProperties { + + Try { + $Union = @() + $Input | ForEach-Object { + If ($Union.Count) { + $_ | Get-Member | Where-Object {-not ($Union[0] | Get-Member $_.Name)} | ForEach-Object { + $Union[0] | Add-Member -MemberType NoteProperty -Name $_.Name -Value $Null + } + } + $Union += $_ + } + $Union + } + Catch { + throw "Failed updating the properties of the first object: $_" + } +} \ No newline at end of file diff --git a/Get-ExcelWorkbookInfo.ps1 b/Get-ExcelWorkbookInfo.ps1 deleted file mode 100644 index ab4c845..0000000 --- a/Get-ExcelWorkbookInfo.ps1 +++ /dev/null @@ -1,65 +0,0 @@ -Function Get-ExcelWorkbookInfo { - <# - .SYNOPSIS - Retrieve information of an Excel workbook. - .DESCRIPTION - The Get-ExcelWorkbookInfo cmdlet retrieves information (LastModifiedBy, LastPrinted, Created, Modified, ...) fron an Excel workbook. These are the same details that are visible in Windows Explorer when right clicking the Excel file, selecting Properties and check the Details tabpage. - .PARAMETER Path - Specifies the path to the Excel file. This parameter is required. - .EXAMPLE - 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 - - .NOTES - CHANGELOG - 2016/01/07 Added Created by Johan Akerstrom (https://github.com/CosmosKey) - - .LINK - https://github.com/dfinke/ImportExcel - #> - - [CmdletBinding()] - Param ( - [Alias('FullName')] - [Parameter(ValueFromPipelineByPropertyName=$true, ValueFromPipeline=$true, Mandatory=$true)] - [String]$Path - ) - - Process { - Try { - $Path = (Resolve-Path $Path).ProviderPath - - $stream = New-Object -TypeName System.IO.FileStream -ArgumentList $Path,'Open','Read','ReadWrite' - $xl = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $stream - $workbook = $xl.Workbook - $workbook.Properties - - $stream.Close() - $stream.Dispose() - $xl.Dispose() - $xl = $null - } - Catch { - throw "Failed retrieving Excel workbook information for '$Path': $_" - } - } -} diff --git a/ImportExcel.psd1 b/ImportExcel.psd1 index a74ca84..c602500 100644 --- a/ImportExcel.psd1 +++ b/ImportExcel.psd1 @@ -73,7 +73,7 @@ Check out the How To Videos https://www.youtube.com/watch?v=U3Ne_yX4tYo&list=PL5 'Close-ExcelPackage', 'ColumnChart', 'Compare-WorkSheet', - 'Convert-XlRangeToImage', + 'Convert-ExcelRangeToImage', 'ConvertFrom-ExcelData', 'ConvertFrom-ExcelSheet', 'ConvertFrom-ExcelToSQLInsert', @@ -107,7 +107,6 @@ Check out the How To Videos https://www.youtube.com/watch?v=U3Ne_yX4tYo&list=PL5 'New-PivotTableDefinition', 'New-Plot', 'New-PSItem', - 'NumberFormatCompletion', 'Open-ExcelPackage', 'PieChart', 'Pivot', @@ -135,6 +134,7 @@ Check out the How To Videos https://www.youtube.com/watch?v=U3Ne_yX4tYo&list=PL5 # Aliases to export from this module AliasesToExport = @( + 'Convert-XlRangeToImage' 'New-ExcelChart', 'Set-Column', 'Set-Format', diff --git a/ImportExcel.psm1 b/ImportExcel.psm1 index 5331493..6bc76f5 100644 --- a/ImportExcel.psm1 +++ b/ImportExcel.psm1 @@ -1,65 +1,9 @@ #region import everything we need Add-Type -Path "$($PSScriptRoot)\EPPlus.dll" -. $PSScriptRoot\AddConditionalFormatting.ps1 -. $PSScriptRoot\AddDataValidation.ps1 -. $PSScriptRoot\Charting.ps1 -. $PSScriptRoot\ColorCompletion.ps1 -. $PSScriptRoot\Compare-WorkSheet.ps1 -. $PSScriptRoot\ConvertExcelToImageFile.ps1 -. $PSScriptRoot\ConvertFromExcelData.ps1 -. $PSScriptRoot\ConvertFromExcelToSQLInsert.ps1 -. $PSScriptRoot\ConvertToExcelXlsx.ps1 -. $PSScriptRoot\Copy-ExcelWorkSheet.ps1 -. $PSScriptRoot\Export-Excel.ps1 -. $PSScriptRoot\Export-ExcelSheet.ps1 -. $PSScriptRoot\Export-StocksToExcel.ps1 -. $PSScriptRoot\Get-ExcelColumnName.ps1 -. $PSScriptRoot\Get-ExcelSheetInfo.ps1 -. $PSScriptRoot\Get-ExcelWorkbookInfo.ps1 -. $PSScriptRoot\Get-HtmlTable.ps1 -. $PSScriptRoot\Get-Range.ps1 -. $PSScriptRoot\Get-XYRange.ps1 -. $PSScriptRoot\Import-Html.ps1 -. $PSScriptRoot\InferData.ps1 -. $PSScriptRoot\Invoke-Sum.ps1 -. $PSScriptRoot\Join-Worksheet.ps1 -. $PSScriptRoot\Merge-Worksheet.ps1 -. $PSScriptRoot\New-ConditionalFormattingIconSet.ps1 -. $PSScriptRoot\New-ConditionalText.ps1 -. $PSScriptRoot\New-ExcelChart.ps1 -. $PSScriptRoot\New-PSItem.ps1 -. $PSScriptRoot\Open-ExcelPackage.ps1 -. $PSScriptRoot\Pivot.ps1 -. $PSScriptRoot\PivotTable.ps1 -#. $PSScriptRoot\Plot.ps1 -. $PSScriptRoot\RemoveWorksheet.ps1 -. $PSScriptRoot\Send-SQLDataToExcel.ps1 -. $PSScriptRoot\Set-CellStyle.ps1 -. $PSScriptRoot\Set-Column.ps1 -. $PSScriptRoot\Set-Row.ps1 -. $PSScriptRoot\Set-WorkSheetProtection.ps1 -. $PSScriptRoot\SetFormat.ps1 -. $PSScriptRoot\TrackingUtils.ps1 -. $PSScriptRoot\Update-FirstObjectProperties.ps1 +try {[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")} +catch {Write-Warning -Message "System.Drawing could not be loaded. Color and font look-ups may not be available."} -New-Alias -Name Use-ExcelData -Value "ConvertFrom-ExcelData" -Force - -if ($PSVersionTable.PSVersion.Major -ge 5) { - . $PSScriptRoot\Plot.ps1 - - Function New-Plot { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'New-Plot does not change system state')] - Param() - - [PSPlot]::new() - } - -} -else { - Write-Warning 'PowerShell 5 is required for plot.ps1' - Write-Warning 'PowerShell Excel is ready, except for that functionality' -} if (($IsLinux -or $IsMacOS) -or $env:NoAutoSize) { $ExcelPackage = [OfficeOpenXml.ExcelPackage]::new() $Cells = ($ExcelPackage | Add-WorkSheet).Cells['A1'] @@ -83,509 +27,30 @@ if (($IsLinux -or $IsMacOS) -or $env:NoAutoSize) { $ExcelPackage | Close-ExcelPackage -NoSave } } + +Get-ChildItem -Path "$PSScriptRoot\ExportedCommands\*.ps1" | ForEach-Object {. $_.FullName} + +. $PSScriptRoot\Charting.ps1 +. $PSScriptRoot\Export-StocksToExcel.ps1 +. $PSScriptRoot\InferData.ps1 +. $PSScriptRoot\Pivot.ps1 + + +if ($PSVersionTable.PSVersion.Major -ge 5) { + . $PSScriptRoot\Plot.ps1 + + Function New-Plot { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'New-Plot does not change system state')] + Param() + + [PSPlot]::new() + } + +} +else { + Write-Warning 'PowerShell 5 is required for plot.ps1' + Write-Warning 'PowerShell Excel is ready, except for that functionality' +} #endregion -function Import-Excel { - <# - .SYNOPSIS - Create custom objects from the rows in an Excel worksheet. - .DESCRIPTION - The Import-Excel cmdlet creates custom objects from the rows in an Excel worksheet. Each row represents one object. All of this is possible without installing Microsoft Excel and by using the .NET library ‘EPPLus.dll’. - - By default, the property names of the objects are retrieved from the column headers. Because an object cannot have a blank property name, only columns with column headers will be imported. - - If the default behavior is not desired and you want to import the complete worksheet ‘as is’, the parameter ‘-NoHeader’ can be used. In case you want to provide your own property names, you can use the parameter ‘-HeaderName’. - - .PARAMETER Path - Specifies the path to the Excel file. - .PARAMETER ExcelPackage - Instead of specifying a path provides an Excel Package object (from Open-ExcelPackage) - Using this avoids re-reading the whole file when importing multiple parts of it. - To allow multiple read operations Import-Excel does NOT close the package, and you should use - Close-ExcelPackage -noSave to close it. - .PARAMETER WorksheetName - Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported. - - .PARAMETER DataOnly - Import only rows and columns that contain data, empty rows and empty columns are not imported. - - .PARAMETER HeaderName - Specifies custom property names to use, instead of the values defined in the column headers of the TopRow. - If you provide fewer header names than there are columns of data in the worksheet, then data will only be imported from that number of columns - the others will be ignored. - If you provide more header names than there are columns of data in the worksheet, it will result in blank properties being added to the objects returned. - - .PARAMETER NoHeader - Automatically generate property names (P1, P2, P3, ..) instead of the ones defined in the column headers of the TopRow. - This switch is best used when you want to import the complete worksheet ‘as is’ and are not concerned with the property names. - - .PARAMETER StartRow - The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. - When the parameters ‘-NoHeader’ and ‘-HeaderName’ are not provided, this row will contain the column headers that will be used as property names. When one of both parameters are provided, the property names are automatically created and this row will be treated as a regular row containing data. - - .PARAMETER EndRow - By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row. - - .PARAMETER StartColumn - The number of the first column to read data from (1 by default). - - .PARAMETER EndColumn - By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number. - - .PARAMETER AsText - Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. * is supported as a wildcard. - - .PARAMETER Password - Accepts a string that will be used to open a password protected Excel file. - - .EXAMPLE - 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. - - ---------------------------------------------- - | 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 - - 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 - Import 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, ..). - - ---------------------------------------------- - | 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 -NoHeader - - P1: First Name - P2: - P3: Address - - P1: Chuck - P2: Norris - P3: California - - P1: Jean-Claude - P2: Vandamme - P3: Brussels - - Notice that the column header (row 1) is imported as an object too. - - .EXAMPLE - Import data from an Excel worksheet. One object is created for each row. The property names of the objects consist of the names 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. - - ---------------------------------------------------------- - | 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 C:\> 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 : - - 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 blanc for all objects. - - .EXAMPLE - Import data from an Excel worksheet. One object is created for each row. The property names of the objects are automatically generated by using the switch ‘-NoHeader’ (P1, P@, P#, ..). The switch ‘-DataOnly’ will speed up the import because empty rows and empty columns are not imported. - - ---------------------------------------------------------- - | 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 C:\> 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 - - Notice that empty rows and empty columns are not imported. - - .EXAMPLE - 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. - - ---------------------------------------------------------- - | File: Movies.xlsx - Sheet: Actors | - ---------------------------------------------------------- - | A B C D | - |1 Chuck Norris California | - |2 | - |3 Jean-Claude Vandamme Brussels | - ---------------------------------------------------------- - - PS C:\> Import-Excel -Path 'C:\Movies.xlsx' -WorkSheetname Actors -DataOnly -HeaderName 'FirstName', 'SecondName', 'City' –StartRow 2 - - FirstName : Jean-Claude - SecondName: Vandamme - City : Brussels - - 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 - > - 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 pipe the data to the Write-SqlTableData 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. - - .LINK - https://github.com/dfinke/ImportExcel - - .NOTES - #> - - [CmdLetBinding()] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] - Param ( - [Alias('FullName')] - [Parameter(ParameterSetName = "PathA", Mandatory, ValueFromPipelineByPropertyName, ValueFromPipeline, Position = 0 )] - [Parameter(ParameterSetName = "PathB", Mandatory, ValueFromPipelineByPropertyName, ValueFromPipeline, Position = 0 )] - [Parameter(ParameterSetName = "PathC", Mandatory, ValueFromPipelineByPropertyName, ValueFromPipeline, Position = 0 )] - [String]$Path, - [Parameter(ParameterSetName = "PackageA", Mandatory)] - [Parameter(ParameterSetName = "PackageB", Mandatory)] - [Parameter(ParameterSetName = "PackageC", Mandatory)] - [OfficeOpenXml.ExcelPackage]$ExcelPackage, - [Alias('Sheet')] - [Parameter(Position = 1)] - [ValidateNotNullOrEmpty()] - [String]$WorksheetName, - [Parameter(ParameterSetName = 'PathB' , Mandatory)] - [Parameter(ParameterSetName = 'PackageB', Mandatory)] - [String[]]$HeaderName , - [Parameter(ParameterSetName = 'PathC' , Mandatory)] - [Parameter(ParameterSetName = 'PackageC', Mandatory)] - [Switch]$NoHeader , - [Alias('HeaderRow', 'TopRow')] - [ValidateRange(1, 9999)] - [Int]$StartRow = 1, - [Alias('StopRow', 'BottomRow')] - [Int]$EndRow , - [Alias('LeftColumn')] - [Int]$StartColumn = 1, - [Alias('RightColumn')] - [Int]$EndColumn , - [Switch]$DataOnly, - [string[]]$AsText, - [ValidateNotNullOrEmpty()] - [String]$Password - ) - begin { - $sw = [System.Diagnostics.Stopwatch]::StartNew() - - Function Get-PropertyNames { - <# - .SYNOPSIS - Create objects containing the column number and the column name for each of the different header types. - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = "Name would be incorrect, and command is not exported")] - Param ( - [Parameter(Mandatory)] - [Int[]]$Columns, - [Parameter(Mandatory)] - [Int]$StartRow - ) - - Try { - if ($HeaderName) { - $i = 0 - foreach ($H in $HeaderName) { - $H | Select-Object @{N = 'Column'; E = { $Columns[$i] } }, @{N = 'Value'; E = { $H } } - $i++ - } - } - elseif ($NoHeader) { - $i = 0 - foreach ($C in $Columns) { - $i++ - $C | Select-Object @{N = 'Column'; E = { $_ } }, @{N = 'Value'; E = { 'P' + $i } } - } - } - - else { - if ($StartRow -lt 1) { - throw 'The top row can never be less than 1 when we need to retrieve headers from the worksheet.' ; return - } - - foreach ($C in $Columns) { - $Worksheet.Cells[$StartRow, $C] | Where-Object { $_.Value } | Select-Object @{N = 'Column'; E = { $C } }, Value - } - } - } - Catch { - throw "Failed creating property names: $_" ; return - } - } - } - - process { - if ($path) { - $extension = [System.IO.Path]::GetExtension($Path) - if ($extension -notmatch '.xlsx$|.xlsm$') { - throw "Import-Excel does not support reading this extension type $($extension)" - } - - $resolvedPath = (Resolve-Path $Path -ErrorAction SilentlyContinue) - if ($resolvedPath) { - $Path = $resolvedPath.ProviderPath - } - else { - throw "'$($Path)' file not found" - } - - $stream = New-Object -TypeName System.IO.FileStream -ArgumentList $Path, 'Open', 'Read', 'ReadWrite' - $ExcelPackage = New-Object -TypeName OfficeOpenXml.ExcelPackage - if ($Password) { $ExcelPackage.Load($stream, $Password) } - else { $ExcelPackage.Load($stream) } - } - try { - #Select worksheet - if (-not $WorksheetName) { $Worksheet = $ExcelPackage.Workbook.Worksheets[1] } - elseif (-not ($Worksheet = $ExcelPackage.Workbook.Worksheets[$WorkSheetName])) { - throw "Worksheet '$WorksheetName' not found, the workbook only contains the worksheets '$($ExcelPackage.Workbook.Worksheets)'. If you only wish to select the first worksheet, please remove the '-WorksheetName' parameter." ; return - } - - Write-Debug $sw.Elapsed.TotalMilliseconds - #region Get rows and columns - #If we are doing dataonly it is quicker to work out which rows to ignore before processing the cells. - if (-not $EndRow ) { $EndRow = $Worksheet.Dimension.End.Row } - if (-not $EndColumn) { $EndColumn = $Worksheet.Dimension.End.Column } - $endAddress = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R[$EndRow]C[$EndColumn]", 0, 0) - if ($DataOnly) { - #If we are using headers startrow will be the header-row so examine data from startRow + 1, - if ($NoHeader) { $range = "A" + ($StartRow ) + ":" + $endAddress } - else { $range = "A" + ($StartRow + 1 ) + ":" + $endAddress } - #We're going to look at every cell and build 2 hash tables holding rows & columns which contain data. - #Want to Avoid 'select unique' operations & large Sorts, becuse time time taken increases with square - #of number of items (PS uses heapsort at large size). Instead keep a list of what we have seen, - #using Hash tables: "we've seen it" is all we need, no need to worry about "seen it before" / "Seen it many times". - $colHash = @{ } - $rowHash = @{ } - foreach ($cell in $Worksheet.Cells[$range]) { - if ($null -ne $cell.Value ) { $colHash[$cell.Start.Column] = 1; $rowHash[$cell.Start.row] = 1 } - } - $rows = ( $StartRow..$EndRow ).Where( { $rowHash[$_] }) - $columns = ($StartColumn..$EndColumn).Where( { $colHash[$_] }) - } - else { - $Columns = $StartColumn .. $EndColumn ; if ($StartColumn -gt $EndColumn) { Write-Warning -Message "Selecting columns $StartColumn to $EndColumn might give odd results." } - if ($NoHeader) { $Rows = $StartRow..$EndRow ; if ($StartRow -gt $EndRow) { Write-Warning -Message "Selecting rows $StartRow to $EndRow might give odd results." } } - elseif ($HeaderName) { $Rows = $StartRow..$EndRow } - else { $Rows = (1 + $StartRow)..$EndRow } # ; if ($StartRow -ge $EndRow) { Write-Warning -Message "Selecting $StartRow as the header with data in $(1+$StartRow) to $EndRow might give odd results." } } - } - #endregion - #region Create property names - if ((-not $Columns) -or (-not ($PropertyNames = Get-PropertyNames -Columns $Columns -StartRow $StartRow))) { - throw "No column headers found on top row '$StartRow'. If column headers in the worksheet are not a requirement then please use the '-NoHeader' or '-HeaderName' parameter."; return - } - if ($Duplicates = $PropertyNames | Group-Object Value | Where-Object Count -GE 2) { - throw "Duplicate column headers found on row '$StartRow' in columns '$($Duplicates.Group.Column)'. Column headers must be unique, if this is not a requirement please use the '-NoHeader' or '-HeaderName' parameter."; return - } - #endregion - Write-Debug $sw.Elapsed.TotalMilliseconds - if (-not $Rows) { - Write-Warning "Worksheet '$WorksheetName' in workbook '$Path' contains no data in the rows after top row '$StartRow'" - } - else { - #region Create one object per row - if ($AsText) { - <#join items in AsText together with ~~~ . Escape any regex special characters... - # which turns * into \* make it .*. Convert ~~~ to $|^ and top and tail with ^%; - So if we get "Week", "[Time]" and "*date*" ; make the expression ^week$|^\[Time\]$|^.*Date.*$ - $make a regex for this which is case insensitive (option 1) and compiled (option 8) - #> - $TextColExpression = "^" + [regex]::Escape($AsText -join "~~~").replace("\*", ".*").replace("~~~", "$|^") + "$" - $TextColRegEx = New-Object -TypeName regex -ArgumentList $TextColExpression , 9 - } - foreach ($R in $Rows) { - #Disabled write-verbose for speed - # Write-Verbose "Import row '$R'" - $NewRow = [Ordered]@{ } - if ($TextColRegEx) { - foreach ($P in $PropertyNames) { - if ($TextColRegEx.IsMatch($P.Value)) { - $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Text - } - else { $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Value } - } - } - else { - foreach ($P in $PropertyNames) { - $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Value - # Write-Verbose "Import cell '$($Worksheet.Cells[$R, $P.Column].Address)' with property name '$($p.Value)' and value '$($Worksheet.Cells[$R, $P.Column].Value)'." - } - } - [PSCustomObject]$NewRow - } - #endregion - } - Write-Debug $sw.Elapsed.TotalMilliseconds - } - catch { throw "Failed importing the Excel workbook '$Path' with worksheet '$Worksheetname': $_"; return } - finally { - if ($Path) { $stream.close(); $ExcelPackage.Dispose() } - } - } -} - -function ConvertFrom-ExcelSheet { - <# - .Synopsis - Reads an Excel file an converts the data to a delimited text file. - - .Example - ConvertFrom-ExcelSheet .\TestSheets.xlsx .\data - Reads each sheet in TestSheets.xlsx and outputs it to the data directory as the sheet name with the extension .txt. - - .Example - ConvertFrom-ExcelSheet .\TestSheets.xlsx .\data sheet?0 - Reads and outputs sheets like Sheet10 and Sheet20 form TestSheets.xlsx and outputs it to the data directory as the sheet name with the extension .txt. - #> - - [CmdletBinding()] - param - ( - [Alias("FullName")] - [Parameter(Mandatory = $true)] - [String] - $Path, - [String] - $OutputPath = '.\', - [String] - $SheetName = "*", - [ValidateSet('ASCII', 'BigEndianUniCode', 'Default', 'OEM', 'UniCode', 'UTF32', 'UTF7', 'UTF8')] - [string] - $Encoding = 'UTF8', - [ValidateSet('.txt', '.log', '.csv')] - [string] - $Extension = '.csv', - [ValidateSet(';', ',')] - [string] - $Delimiter = ';' - ) - - $Path = (Resolve-Path $Path).Path - $Stream = New-Object -TypeName System.IO.FileStream -ArgumentList $Path, "Open", "Read", "ReadWrite" - $xl = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Stream - $workbook = $xl.Workbook - - $targetSheets = $workbook.Worksheets | Where-Object { $_.Name -like $SheetName } - - $params = @{ } + $PSBoundParameters - $params.Remove("OutputPath") - $params.Remove("SheetName") - $params.Remove('Extension') - $params.NoTypeInformation = $true - - Foreach ($sheet in $targetSheets) { - Write-Verbose "Exporting sheet: $($sheet.Name)" - - $params.Path = "$OutputPath\$($Sheet.Name)$Extension" - - Import-Excel $Path -Sheet $($sheet.Name) | Export-Csv @params - } - - $Stream.Close() - $Stream.Dispose() - $xl.Dispose() -} - -function Export-MultipleExcelSheets { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] - param( - [Parameter(Mandatory = $true)] - $Path, - [Parameter(Mandatory = $true)] - [hashtable]$InfoMap, - [string]$Password, - [Switch]$Show, - [Switch]$AutoSize - ) - - $parameters = @{ } + $PSBoundParameters - $parameters.Remove("InfoMap") - $parameters.Remove("Show") - - $parameters.Path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path) - - foreach ($entry in $InfoMap.GetEnumerator()) { - Write-Progress -Activity "Exporting" -Status "$($entry.Key)" - $parameters.WorkSheetname = $entry.Key - - & $entry.Value | Export-Excel @parameters - } - - if ($Show) { Invoke-Item $Path } -} - -Function WorksheetArgumentCompleter { - param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) - $xlPath = $fakeBoundParameter['Path'] - if (Test-Path -Path $xlPath) { - $xlpkg = Open-ExcelPackage -ReadOnly -Path $xlPath - $WorksheetNames = $xlPkg.Workbook.Worksheets.Name - Close-ExcelPackage -nosave -ExcelPackage $xlpkg - $WorksheetNames.where( { $_ -like "*$wordToComplete*" }) | foreach-object { - New-Object -TypeName System.Management.Automation.CompletionResult -ArgumentList "'$_'", - $_ , ([System.Management.Automation.CompletionResultType]::ParameterValue) , $_ - } - } -} -If (Get-Command -ErrorAction SilentlyContinue -name Register-ArgumentCompleter) { - Register-ArgumentCompleter -CommandName 'Import-Excel' -ParameterName 'WorksheetName' -ScriptBlock $Function:WorksheetArgumentCompleter -} +. $PSScriptRoot\ArgumentCompletion.ps1 \ No newline at end of file diff --git a/InferData.ps1 b/InferData/InferData.ps1 similarity index 100% rename from InferData.ps1 rename to InferData/InferData.ps1 diff --git a/InferData/Invoke-AllTests.md b/InferData/Invoke-AllTests.md new file mode 100644 index 0000000..efe8455 --- /dev/null +++ b/InferData/Invoke-AllTests.md @@ -0,0 +1,87 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Invoke-AllTests + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Invoke-AllTests [[-target] ] [-OnlyPassing] [-FirstOne] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -FirstOne +{{ Fill FirstOne Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OnlyPassing +{{ Fill OnlyPassing Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -target +{{ Fill target Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/InferData/Test-Boolean.md b/InferData/Test-Boolean.md new file mode 100644 index 0000000..fe57b1f --- /dev/null +++ b/InferData/Test-Boolean.md @@ -0,0 +1,57 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Test-Boolean + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Test-Boolean [[-p] ] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -p +{{ Fill p Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/InferData/Test-Date.md b/InferData/Test-Date.md new file mode 100644 index 0000000..74c8d35 --- /dev/null +++ b/InferData/Test-Date.md @@ -0,0 +1,57 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Test-Date + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Test-Date [[-p] ] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -p +{{ Fill p Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/InferData/Test-Integer.md b/InferData/Test-Integer.md new file mode 100644 index 0000000..33ae133 --- /dev/null +++ b/InferData/Test-Integer.md @@ -0,0 +1,57 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Test-Integer + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Test-Integer [[-p] ] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -p +{{ Fill p Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/InferData/Test-Number.md b/InferData/Test-Number.md new file mode 100644 index 0000000..0df805d --- /dev/null +++ b/InferData/Test-Number.md @@ -0,0 +1,57 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Test-Number + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Test-Number [[-p] ] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -p +{{ Fill p Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/InferData/Test-String.md b/InferData/Test-String.md new file mode 100644 index 0000000..73c4f19 --- /dev/null +++ b/InferData/Test-String.md @@ -0,0 +1,57 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Test-String + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Test-String [[-p] ] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -p +{{ Fill p Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/Merge-Worksheet.ps1 b/Merge-Worksheet.ps1 deleted file mode 100644 index 331c339..0000000 --- a/Merge-Worksheet.ps1 +++ /dev/null @@ -1,539 +0,0 @@ -Function Merge-Worksheet { - <# - .Synopsis - Merges two Worksheets (or other objects) into a single Worksheet with differences marked up. - .Description - The Compare-Worksheet command takes two Worksheets and marks differences in the source document, and optionally outputs a grid showing the changes. - By contrast the Merge-Worksheet command takes the Worksheets and combines them into a single sheet showing the old and new data side by side. - Although it is designed to work with Excel data it can work with arrays of any kind of object; so it can be a merge *of* Worksheets, or a merge *to* a Worksheet. - .Example - Merge-Worksheet "Server54.xlsx" "Server55.xlsx" -WorksheetName services -OutputFile Services.xlsx -OutputSheetName 54-55 -show - The workbooks contain audit information for two servers, one sheet contains - a list of services. This command creates a worksheet named "54-55" in a - workbook named "services.xlsx" which shows all the services and their - differences, and opens the new workbook in Excel. - .Example - Merge-Worksheet "Server54.xlsx" "Server55.xlsx" -WorksheetName services -OutputFile Services.xlsx -OutputSheetName 54-55 -HideEqual -AddBackgroundColor LightBlue -show - This modifies the previous command to hide the equal rows in the output - sheet and changes the color used to mark rows added to the second file. - .Example - 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 - Merge-Worksheet -RefO (dir .\ImportExcel\4.0.7) -DiffO (dir .\ImportExcel\4.0.8) -Pr Length | Out-GridView - This time no file is written and the results - which include all properties, - not just length, are output and sent to Out-Gridview. This version uses - aliases to shorten the parameters, (OutputFileName can be "outFile" and - the Sheet can be"OutSheet"; DifferenceObject & ReferenceObject can be - DiffObject & RefObject respectively). - #> - [cmdletbinding(SupportsShouldProcess=$true)] - Param( - #First Excel file to compare. You can compare two Excel files or two other objects or a reference obhct against a difference file, but not a reference file against an object. - [parameter(ParameterSetName='A',Mandatory=$true,Position=0)] #A = Compare two files default headers - [parameter(ParameterSetName='B',Mandatory=$true,Position=0)] #B = Compare two files user supplied headers - [parameter(ParameterSetName='C',Mandatory=$true,Position=0)] #C = Compare two files headers P1, P2, P3 etc - $Referencefile , - - #Second Excel file to compare. - [parameter(ParameterSetName='A',Mandatory=$true,Position=1)] - [parameter(ParameterSetName='B',Mandatory=$true,Position=1)] - [parameter(ParameterSetName='C',Mandatory=$true,Position=1)] - [parameter(ParameterSetName='E',Mandatory=$true,Position=1)] #D Compare two objects; E = Compare one object one file that uses default headers - [parameter(ParameterSetName='F',Mandatory=$true,Position=1)] #F = Compare one object one file that uses user supplied headers - [parameter(ParameterSetName='G',Mandatory=$true,Position=1)] #G Compare one object one file that uses headers P1, P2, P3 etc - $Differencefile , - - #Name(s) of Worksheets to compare. - [parameter(ParameterSetName='A',Position=2)] #Applies to all sets EXCEPT D which is two objects (no sheets) - [parameter(ParameterSetName='B',Position=2)] - [parameter(ParameterSetName='C',Position=2)] - [parameter(ParameterSetName='E',Position=2)] - [parameter(ParameterSetName='F',Position=2)] - [parameter(ParameterSetName='G',Position=2)] - $WorksheetName = "Sheet1", - - #The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. - [parameter(ParameterSetName='A')] #Applies to all sets EXCEPT D which is two objects (no sheets, so no start row ) - [parameter(ParameterSetName='B')] - [parameter(ParameterSetName='C')] - [parameter(ParameterSetName='E')] - [parameter(ParameterSetName='F')] - [parameter(ParameterSetName='G')] - [int]$Startrow = 1, - - #Specifies custom property names to use, instead of the values defined in the column headers of the Start ROw. - [Parameter(ParameterSetName='B',Mandatory=$true)] #Compare object + sheet or 2 sheets with user supplied headers - [Parameter(ParameterSetName='F',Mandatory=$true)] - [String[]]$Headername, - - #Automatically generate property names (P1, P2, P3, ..) instead of using the values the top row of the sheet. - [Parameter(ParameterSetName='C',Mandatory=$true)] #Compare object + sheet or 2 sheets with headers of P1, P2, P3 ... - [Parameter(ParameterSetName='G',Mandatory=$true)] - [switch]$NoHeader, - - #Reference object to compare if a Worksheet is NOT being used. Reference object can combine with a difference sheet or difference object - [parameter(ParameterSetName='D',Mandatory=$true)] - [parameter(ParameterSetName='E',Mandatory=$true)] - [parameter(ParameterSetName='F',Mandatory=$true)] - [parameter(ParameterSetName='G',Mandatory=$true)] - [Alias('RefObject')] - $ReferenceObject , - #Difference object to compare if a Worksheet is NOT being used for either half. Can't have a reference sheet and difference object. - [parameter(ParameterSetName='D',Mandatory=$true,Position=1)] - [Alias('DiffObject')] - $DifferenceObject , - [parameter(ParameterSetName='D',Position=2)] - [parameter(ParameterSetName='E',Position=2)] - [parameter(ParameterSetName='F',Position=2)] - [parameter(ParameterSetName='G',Position=2)] - #If there isn't a filename to use to label data from the "Difference" side, DiffPrefix is used, it defaults to "=>" - $DiffPrefix = "=>" , - #File to hold merged data. - [parameter(Position=3)] - [Alias('OutFile')] - $OutputFile , - #Name of Worksheet to output - if none specified will use the reference Worksheet name. - [parameter(Position=4)] - [Alias('OutSheet')] - $OutputSheetName = "Sheet1", - #Properties to include in the DIFF - supports wildcards, default is "*". - $Property = "*" , - #Properties to exclude from the the search - supports wildcards. - $ExcludeProperty , - #Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name". - $Key = "Name" , - #Sets the font color for the "key" field; this means you can filter by color to get only changed rows. - $KeyFontColor = [System.Drawing.Color]::DarkRed , - #Sets the background color for changed rows. - $ChangeBackgroundColor = [System.Drawing.Color]::Orange, - #Sets the background color for rows in the reference but deleted from the difference sheet. - $DeleteBackgroundColor = [System.Drawing.Color]::LightPink, - #Sets the background color for rows not in the reference but added to the difference sheet. - $AddBackgroundColor = [System.Drawing.Color]::PaleGreen, - #if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows. - [switch]$HideEqual , - #If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline). - [switch]$Passthru , - #If specified, opens the output workbook. - [Switch]$Show - ) - - #region Read Excel data - if ($Differencefile -is [System.IO.FileInfo]) {$Differencefile = $Differencefile.FullName} - if ($Referencefile -is [System.IO.FileInfo]) {$Referencefile = $Referencefile.FullName} - if ($Referencefile -and $Differencefile) { - #if the filenames don't resolve, give up now. - try { $oneFile = ((Resolve-Path -Path $Referencefile -ErrorAction Stop).path -eq (Resolve-Path -Path $Differencefile -ErrorAction Stop).path)} - Catch { Write-Warning -Message "Could not Resolve the filenames." ; return } - - #If we have one file , we must have two different Worksheet names. If we have two files $WorksheetName can be a single string or two strings. - if ($onefile -and ( ($WorksheetName.count -ne 2) -or $WorksheetName[0] -eq $WorksheetName[1] ) ) { - Write-Warning -Message "If both the Reference and difference file are the same then Worksheet name must provide 2 different names" - return - } - if ($WorksheetName.count -eq 2) {$Worksheet2 = $DiffPrefix = $WorksheetName[1] ; $Worksheet1 = $WorksheetName[0] ; } - elseif ($WorksheetName -is [string]) {$Worksheet2 = $Worksheet1 = $WorksheetName ; - $DiffPrefix = (Split-Path -Path $Differencefile -Leaf) -replace "\.xlsx$","" } - else {Write-Warning -Message "You must provide either a single Worksheet name or two names." ; return } - - $params= @{ ErrorAction = [System.Management.Automation.ActionPreference]::Stop } - foreach ($p in @("HeaderName","NoHeader","StartRow")) {if ($PSBoundParameters[$p]) {$params[$p] = $PSBoundParameters[$p]}} - try { - $ReferenceObject = Import-Excel -Path $Referencefile -WorksheetName $Worksheet1 @params - $DifferenceObject = Import-Excel -Path $Differencefile -WorksheetName $Worksheet2 @Params - } - Catch {Write-Warning -Message "Could not read the Worksheet from $Referencefile::$Worksheet1 and/or $Differencefile::$Worksheet2." ; return } - if ($NoHeader) {$firstDataRow = $Startrow } else {$firstDataRow = $Startrow + 1} - } - elseif ( $Differencefile) { - if ($WorksheetName -isnot [string]) {Write-Warning -Message "You must provide a single Worksheet name." ; return } - $params = @{WorksheetName=$WorksheetName; Path=$Differencefile; ErrorAction=[System.Management.Automation.ActionPreference]::Stop } - foreach ($p in @("HeaderName","NoHeader","StartRow")) {if ($PSBoundParameters[$p]) {$params[$p] = $PSBoundParameters[$p]}} - try {$DifferenceObject = Import-Excel @Params } - Catch {Write-Warning -Message "Could not read the Worksheet '$WorksheetName' from $Differencefile::$WorksheetName." ; return } - if ($DiffPrefix -eq "=>" ) { - $DiffPrefix = (Split-Path -Path $Differencefile -Leaf) -replace "\.xlsx$","" - } - if ($NoHeader) {$firstDataRow = $Startrow } else {$firstDataRow = $Startrow + 1} - } - else { $firstDataRow = 1 } - #endregion - - #region Set lists of properties and row numbers - #Make a list of properties/headings using the Property (default "*") and ExcludeProperty parameters - $propList = @() - $DifferenceObject = $DifferenceObject | Update-FirstObjectProperties - $headings = $DifferenceObject[0].psobject.Properties.Name # This preserves the sequence - using get-member would sort them alphabetically! There may be extra properties in - if ($NoHeader -and "Name" -eq $Key) {$Key = "p1"} - if ($headings -notcontains $Key -and - ('*' -ne $Key)) {Write-Warning -Message "You need to specify one of the headings in the sheet '$Worksheet1' as a key." ; return } - foreach ($p in $Property) { $propList += ($headings.where({$_ -like $p}) )} - foreach ($p in $ExcludeProperty) { $propList = $propList.where({$_ -notlike $p}) } - if (($propList -notcontains $Key) -and - ('*' -ne $Key)) { $propList += $Key} #If $key isn't one of the headings we will have bailed by now - $propList = $propList | Select-Object -Unique #so, prolist must contain at least $key if nothing else - - #If key is "*" we treat it differently , and we will create a script property which concatenates all the Properties in $Proplist - $ConCatblock = [scriptblock]::Create( ($proplist | ForEach-Object {'$this."' + $_ + '"'}) -join " + ") - - #Build the list of the properties to output, in order. - $diffpart = @() - $refpart = @() - foreach ($p in $proplist.Where({$key -ne $_}) ) {$refPart += $p ; $diffPart += "$DiffPrefix $p" } - $lastRefColNo = $proplist.count - $FirstDiffColNo = $lastRefColNo + 1 - - if ($key -ne '*') { - $outputProps = @($key) + $refpart + $diffpart - #If we are using a single column as the key, don't duplicate it, so the last difference column will be A if there is one property, C if there are two, E if there are 3 - $lastDiffColNo = (2 * $proplist.count) - 1 - } - else { - $outputProps = @( ) + $refpart + $diffpart - #If we not using a single column as a key all columns are duplicated so, the Last difference column will be B if there is one property, D if there are two, F if there are 3 - $lastDiffColNo = (2 * $proplist.count ) - } - - #Add RowNumber to every row - #If one sheet has extra rows we can get a single "==" result from compare, with the row from the reference sheet, but - #the row in the other sheet might be different so we will look up the row number from the key field - build a hash table for that here - #If we have "*" as the key ad the script property to concatenate the [selected] properties. - - $Rowhash = @{} - $rowNo = $firstDataRow - foreach ($row in $ReferenceObject) { - if ($null -eq $row._row) {Add-Member -InputObject $row -MemberType NoteProperty -Value ($rowNo ++) -Name "_Row" } - else {$rowNo++ } - if ($Key -eq '*' ) {Add-Member -InputObject $row -MemberType ScriptProperty -Value $ConCatblock -Name "_All" } - } - $rowNo = $firstDataRow - foreach ($row in $DifferenceObject) { - Add-Member -InputObject $row -MemberType NoteProperty -Value $rowNo -Name "$DiffPrefix Row" -Force - if ($Key -eq '*' ) { - Add-Member -InputObject $row -MemberType ScriptProperty -Value $ConCatblock -Name "_All" - $Rowhash[$row._All] = $rowNo - } - else {$Rowhash[$row.$key] = $rowNo } - $rowNo ++ - } - if ($DifferenceObject.count -gt $Rowhash.Keys.Count) { - Write-Warning -Message "Difference object has $($DifferenceObject.Count) rows; but only $($Rowhash.keys.count) unique keys" - } - if ($Key -eq '*') {$key = "_ALL"} - #endregion - #We need to know all the properties we've met on the objects we've diffed - $eDiffProps = [ordered]@{} - #When we do a compare object changes will result in two rows so we group them and join them together. - $expandedDiff = Compare-Object -ReferenceObject $ReferenceObject -DifferenceObject $DifferenceObject -Property $propList -PassThru -IncludeEqual | - Group-Object -Property $key | ForEach-Object { - #The value of the key column is the name of the Group. - $keyval = $_.name - #we're going to create a custom object from a hash table. - $hash = [ordered]@{} - foreach ($result in $_.Group) { - if ($result.SideIndicator -ne "=>") {$hash["_Row"] = $result._Row } - elseif (-not $hash["$DiffPrefix Row"]) {$hash["_Row"] = "" } - #if we have already set the side, this must be the second record, so set side to indicate "changed"; if we got two "Same" indicators we may have a classh of keys - if ($hash.Side) { - if ($hash.Side -eq $result.SideIndicator) {Write-Warning -Message "'$keyval' may be a duplicate."} - $hash.Side = "<>" - } - else {$hash["Side"] = $result.SideIndicator} - switch ($hash.side) { - '==' { $hash["$DiffPrefix is"] = 'Same' } - '=>' { $hash["$DiffPrefix is"] = 'Added' } - '<>' { if (-not $hash["_Row"]) { - $hash["$DiffPrefix is"] = 'Added' - } - else { - $hash["$DiffPrefix is"] = 'Changed' - } - } - '<=' { $hash["$DiffPrefix is"] = 'Removed'} - } - #find the number of the row in the the "difference" object which has this key. If it is the object is only in the reference this will be blank. - $hash["$DiffPrefix Row"] = $Rowhash[$keyval] - $hash[$key] = $keyval - #Create FieldName and/or =>FieldName columns - foreach ($p in $result.psobject.Properties.name.where({$_ -ne $key -and $_ -ne "SideIndicator" -and $_ -ne "$DiffPrefix Row" })) { - if ($result.SideIndicator -eq "==" -and $p -in $propList) - {$hash[("$p")] = $hash[("$DiffPrefix $p")] = $result.$P} - elseif ($result.SideIndicator -eq "==" -or $result.SideIndicator -eq "<=") - {$hash[("$p")] = $result.$P} - elseif ($result.SideIndicator -eq "=>") { $hash[("$DiffPrefix $p")] = $result.$P} - } - } - - foreach ($k in $hash.keys) {$eDiffProps[$k] = $true} - [Pscustomobject]$hash - } | Sort-Object -Property "_row" - - #Already sorted by reference row number, fill in any blanks in the difference-row column. - for ($i = 1; $i -lt $expandedDiff.Count; $i++) {if (-not $expandedDiff[$i]."$DiffPrefix Row") {$expandedDiff[$i]."$DiffPrefix Row" = $expandedDiff[$i-1]."$DiffPrefix Row" } } - - #Now re-Sort by difference row number, and fill in any blanks in the reference-row column. - $expandedDiff = $expandedDiff | Sort-Object -Property "$DiffPrefix Row" - for ($i = 1; $i -lt $expandedDiff.Count; $i++) {if (-not $expandedDiff[$i]."_Row") {$expandedDiff[$i]."_Row" = $expandedDiff[$i-1]."_Row" } } - - $AllProps = @("_Row") + $OutputProps + $eDiffProps.keys.where({$_ -notin ($outputProps + @("_row","side","SideIndicator","_ALL" ))}) - - if ($PassThru -or -not $OutputFile) {return ($expandedDiff | Select-Object -Property $allprops | Sort-Object -Property "_row", "$DiffPrefix Row" ) } - elseif ($PSCmdlet.ShouldProcess($OutputFile,"Write Output to Excel file")) { - $expandedDiff = $expandedDiff | Sort-Object -Property "_row", "$DiffPrefix Row" - $xl = $expandedDiff | Select-Object -Property $OutputProps | Update-FirstObjectProperties | - Export-Excel -Path $OutputFile -Worksheetname $OutputSheetName -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -PassThru - $ws = $xl.Workbook.Worksheets[$OutputSheetName] - for ($i = 0; $i -lt $expandedDiff.Count; $i++ ) { - if ( $expandedDiff[$i].side -ne "==" ) { - Set-ExcelRange -Worksheet $ws -Range ("A" + ($i + 2 )) -FontColor $KeyFontColor - } - elseif ( $HideEqual ) {$ws.row($i+2).hidden = $true } - if ( $expandedDiff[$i].side -eq "<>" ) { - $range = $ws.Dimension -replace "\d+", ($i + 2 ) - Set-ExcelRange -Worksheet $ws -Range $range -BackgroundColor $ChangeBackgroundColor - } - elseif ( $expandedDiff[$i].side -eq "<=" ) { - $rangeR1C1 = "R[{0}]C[1]:R[{0}]C[{1}]" -f ($i + 2 ) , $lastRefColNo - $range = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1($rangeR1C1,0,0) - Set-ExcelRange -Worksheet $ws -Range $range -BackgroundColor $DeleteBackgroundColor - } - elseif ( $expandedDiff[$i].side -eq "=>" ) { - if ($propList.count -gt 1) { - $rangeR1C1 = "R[{0}]C[{1}]:R[{0}]C[{2}]" -f ($i + 2 ) , $FirstDiffColNo , $lastDiffColNo - $range = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1($rangeR1C1,0,0) - Set-ExcelRange -Worksheet $ws -Range $range -BackgroundColor $AddBackgroundColor - } - Set-ExcelRange -Worksheet $ws -Range ("A" + ($i + 2 )) -BackgroundColor $AddBackgroundColor - } - } - Close-ExcelPackage -ExcelPackage $xl -Show:$Show - } -} - -Function Merge-MultipleSheets { - <# - .Synopsis - Merges Worksheets into a single Worksheet with differences marked up. - .Description - The Merge Worksheet command combines two sheets. Merge-MultipleSheets is - designed to merge more than two. So if asked to merge sheets A,B,C which - contain Services, with a Name, Displayname and Start mode, where "Name" is - treated as the key, Merge-MultipleSheets calls Merge-Worksheet to merge - "Name", "Displayname" and "Startmode" from sheets A and C; the result has - column headings "_Row", "Name", "DisplayName", "Startmode", "C-DisplayName", - "C-StartMode", "C-Is" and "C-Row". - Merge-MultipleSheets then calls Merge-Worksheet again passing it the - intermediate result and sheet B, comparing "Name", "Displayname" and - "Start mode" columns on each side, and gets a result with columns "_Row", - "Name", "DisplayName", "Startmode", "B-DisplayName", "B-StartMode", "B-Is", - "B-Row", "C-DisplayName", "C-StartMode", "C-Is" and "C-Row". Any columns on - the "reference" side which are not used in the comparison are added on the - right, which is why we compare the sheets in reverse order. - - The "Is" columns hold "Same", "Added", "Removed" or "Changed" and is used for - conditional formatting in the output sheet (these columns are hidden by default), - and when the data is written to Excel the "reference" columns, in this case - "DisplayName" and "Start" are renamed to reflect their source, so become - "A-DisplayName" and "A-Start". - - Conditional formatting is also applied to the Key column ("Name" in this - case) so the view can be filtered to rows with changes by filtering this - column on color. - - Note: the processing order can affect what is seen as a change. For example - if there is an extra item in sheet B in the example above, Sheet C will be - processed and that row and will not be seen to be missing. When sheet B is - processed it is marked as an addition, and the conditional formatting marks - the entries from sheet A to show that a values were added in at least one - sheet. However if Sheet B is the reference sheet, A and C will be seen to - have an item removed; and if B is processed before C, the extra item is - known when C is processed and so C is considered to be missing that item. - .Example - dir Server*.xlsx | Merge-MulipleSheets -WorksheetName Services -OutputFile Test2.xlsx -OutputSheetName Services -Show - Here we are auditing servers and each one has a workbook in the current - directory which contains a "Services" Worksheet (the result of - Get-WmiObject -Class win32_service | Select-Object -Property Name, Displayname, Startmode) - No key is specified so the key is assumed to be the "Name" column. - The files are merged and the result is opened on completion. - .Example - dir Serv*.xlsx | Merge-MulipleSheets -WorksheetName Software -Key "*" -ExcludeProperty Install* -OutputFile Test2.xlsx -OutputSheetName Software -Show - The server audit files in the previous example also have "Software" worksheet, - but no single field on that sheet works as a key. Specifying "*" for the key - produces a compound key using all non-excluded fields (and the installation - date and file location are excluded). - .Example - Merge-MulipleSheets -Path hotfixes.xlsx -WorksheetName Serv* -Key hotfixid -OutputFile test2.xlsx -OutputSheetName hotfixes -HideRowNumbers -Show - This time all the servers have written their hotfix information to their own - worksheets in a shared Excel workbook named "Hotfixes.xlsx" (the information was - obtained by running Get-Hotfix | Sort-Object -Property description,hotfixid | Select-Object -Property Description,HotfixID) - This ignores any sheets which are not named "Serv*", and uses the HotfixID as - the key; in this version the row numbers are hidden. - #> - [cmdletbinding()] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification="False positives when initializing variable in begin block")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification="MultipleSheet would be incorrect")] - #[Alias("Merge-MulipleSheets")] #There was a spelling error in the first release. This was there to ensure things didn't break but intelisense gave the alias first. - param ( - #Paths to the files to be merged. Files are also accepted - [Parameter(Mandatory=$true,ValueFromPipeline=$true)] - $Path , - #The row from where we start to import data, all rows above the Start row are disregarded. By default this is the first row. - [int]$Startrow = 1, - - #Specifies custom property names to use, instead of the values defined in the column headers of the Start row. - [String[]]$Headername, - - #If specified, property names will be automatically generated (P1, P2, P3, ..) instead of using the values from the start row. - [switch]$NoHeader, - - #Name(s) of Worksheets to compare. - $WorksheetName = "Sheet1", - #File to write output to. - [Alias('OutFile')] - $OutputFile = ".\temp.xlsx", - #Name of Worksheet to output - if none specified will use the reference Worksheet name. - [Alias('OutSheet')] - $OutputSheetName = "Sheet1", - #Properties to include in the comparison - supports wildcards, default is "*". - $Property = "*" , - #Properties to exclude from the the comparison - supports wildcards. - $ExcludeProperty , - #Name of a column which is unique used to pair up rows from the reference and difference sides, default is "Name". - $Key = "Name" , - #Sets the font color for the Key field; this means you can filter by color to get only changed rows. - $KeyFontColor = [System.Drawing.Color]::Red, - #Sets the background color for changed rows. - $ChangeBackgroundColor = [System.Drawing.Color]::Orange, - #Sets the background color for rows in the reference but deleted from the difference sheet. - $DeleteBackgroundColor = [System.Drawing.Color]::LightPink, - #Sets the background color for rows not in the reference but added to the difference sheet. - $AddBackgroundColor = [System.Drawing.Color]::Orange, - #If specified, hides the columns in the spreadsheet that contain the row numbers. - [switch]$HideRowNumbers , - #If specified, outputs the data to the pipeline (you can add -whatif so it the command only outputs to the pipeline). - [switch]$Passthru , - #If specified, opens the output workbook. - [Switch]$Show - ) - begin { $filestoProcess = @() } - process { $filestoProcess += $Path} - end { - if ($filestoProcess.Count -eq 1 -and $WorksheetName -match '\*') { - Write-Progress -Activity "Merging sheets" -CurrentOperation "Expanding * to names of sheets in $($filestoProcess[0]). " - $excel = Open-ExcelPackage -Path $filestoProcess - $WorksheetName = $excel.Workbook.Worksheets.Name.where({$_ -like $WorksheetName}) - Close-ExcelPackage -NoSave -ExcelPackage $excel - } - - #Merge identically named sheets in different work books; - if ($filestoProcess.Count -ge 2 -and $WorksheetName -is "string" ) { - Get-Variable -Name 'HeaderName','NoHeader','StartRow','Key','Property','ExcludeProperty','WorksheetName' -ErrorAction SilentlyContinue | - Where-Object {$_.Value} | ForEach-Object -Begin {$params= @{} } -Process {$params[$_.Name] = $_.Value} - - Write-Progress -Activity "Merging sheets" -CurrentOperation "comparing '$WorksheetName' in $($filestoProcess[-1]) against $($filestoProcess[0]). " - $merged = Merge-Worksheet @params -Referencefile $filestoProcess[0] -Differencefile $filestoProcess[-1] - $nextFileNo = 2 - while ($nextFileNo -lt $filestoProcess.count -and $merged) { - Write-Progress -Activity "Merging sheets" -CurrentOperation "comparing '$WorksheetName' in $($filestoProcess[-$nextFileNo]) against $($filestoProcess[0]). " - $merged = Merge-Worksheet @params -ReferenceObject $merged -Differencefile $filestoProcess[-$nextFileNo] - $nextFileNo ++ - - } - } - #Merge different sheets from one workbook - elseif ($filestoProcess.Count -eq 1 -and $WorksheetName.Count -ge 2 ) { - Get-Variable -Name 'HeaderName','NoHeader','StartRow','Key','Property','ExcludeProperty' -ErrorAction SilentlyContinue | - Where-Object {$_.Value} | ForEach-Object -Begin {$params= @{} } -Process {$params[$_.Name] = $_.Value} - - Write-Progress -Activity "Merging sheets" -CurrentOperation "Comparing $($WorksheetName[-1]) against $($WorksheetName[0]). " - $merged = Merge-Worksheet @params -Referencefile $filestoProcess[0] -Differencefile $filestoProcess[0] -WorksheetName $WorksheetName[0,-1] - $nextSheetNo = 2 - while ($nextSheetNo -lt $WorksheetName.count -and $merged) { - Write-Progress -Activity "Merging sheets" -CurrentOperation "Comparing $($WorksheetName[-$nextSheetNo]) against $($WorksheetName[0]). " - $merged = Merge-Worksheet @params -ReferenceObject $merged -Differencefile $filestoProcess[0] -WorksheetName $WorksheetName[-$nextSheetNo] -DiffPrefix $WorksheetName[-$nextSheetNo] - $nextSheetNo ++ - } - } - #We either need one Worksheet name and many files or one file and many sheets. - else { Write-Warning -Message "Need at least two files to process" ; return } - #if the process didn't return data then abandon now. - if (-not $merged) {Write-Warning -Message "The merge operation did not return any data."; return } - - $orderByProperties = $merged[0].psobject.properties.where({$_.name -match "row$"}).name - Write-Progress -Activity "Merging sheets" -CurrentOperation "creating output sheet '$OutputSheetName' in $OutputFile" - $excel = $merged | Sort-Object -Property $orderByProperties | - Export-Excel -Path $OutputFile -Worksheetname $OutputSheetName -ClearSheet -BoldTopRow -AutoFilter -PassThru - $sheet = $excel.Workbook.Worksheets[$OutputSheetName] - - #We will put in a conditional format for "if all the others are not flagged as 'same'" to mark rows where something is added, removed or changed - $sameChecks = @() - - #All the 'difference' columns in the sheet are labeled with the file they came from, 'reference' columns need their - #headers prefixed with the ref file name, $colnames is the basis of a regular expression to identify what should have $refPrefix appended - $colNames = @("^_Row$") - if ($key -ne "*") - {$colnames += "^$Key$"} - if ($filesToProcess.Count -ge 2) { - $refPrefix = (Split-Path -Path $filestoProcess[0] -Leaf) -replace "\.xlsx$"," " - } - else {$refPrefix = $WorksheetName[0] } - Write-Progress -Activity "Merging sheets" -CurrentOperation "applying formatting to sheet '$OutputSheetName' in $OutputFile" - #Find the column headings which are in the form "diffFile is"; which will hold 'Same', 'Added' or 'Changed' - foreach ($cell in $sheet.Cells[($sheet.Dimension.Address -replace "\d+$","1")].Where({$_.value -match "\sIS$"}) ) { - #Work leftwards across the headings applying conditional formatting which says - # 'Format this cell if the "IS" column has a value of ...' until you find a heading which doesn't have the prefix. - $prefix = $cell.value -replace "\sIS$","" - $columnNo = $cell.start.Column -1 - $cellAddr = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R1C$columnNo",1,$columnNo) - while ($sheet.cells[$cellAddr].value -match $prefix) { - $condFormattingParams = @{RuleType='Expression'; BackgroundPattern='Solid'; Worksheet=$sheet; StopIfTrue=$true; Range=$([OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R[1]C[$columnNo]:R[1048576]C[$columnNo]",0,0)) } - Add-ConditionalFormatting @condFormattingParams -ConditionValue ($cell.Address + '="Added"' ) -BackgroundColor $AddBackgroundColor - Add-ConditionalFormatting @condFormattingParams -ConditionValue ($cell.Address + '="Changed"') -BackgroundColor $ChangeBackgroundColor - Add-ConditionalFormatting @condFormattingParams -ConditionValue ($cell.Address + '="Removed"') -BackgroundColor $DeleteBackgroundColor - $columnNo -- - $cellAddr = [OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R1C$columnNo",1,$columnNo) - } - #build up a list of prefixes in $colnames - we'll use that to set headers on rows from the reference file; and build up the "if the 'is' cell isn't same" list - $colNames += $prefix - $sameChecks += (($cell.Address -replace "1","2") +'<>"Same"') - } - - #For all the columns which don't match one of the Diff-file prefixes or "_Row" or the 'Key' columnn name; add the reference file prefix to their header. - $nameRegex = $colNames -Join '|' - foreach ($cell in $sheet.Cells[($sheet.Dimension.Address -replace "\d+$","1")].Where({$_.value -Notmatch $nameRegex}) ) { - $cell.Value = $refPrefix + $cell.Value - $condFormattingParams = @{RuleType='Expression'; BackgroundPattern='Solid'; Worksheet=$sheet; StopIfTrue=$true; Range=[OfficeOpenXml.ExcelAddress]::TranslateFromR1C1("R[2]C[$($cell.start.column)]:R[1048576]C[$($cell.start.column)]",0,0)} - Add-ConditionalFormatting @condFormattingParams -ConditionValue ("OR(" +(($sameChecks -join ",") -replace '<>"Same"','="Added"' ) +")" ) -BackgroundColor $DeleteBackgroundColor - Add-ConditionalFormatting @condFormattingParams -ConditionValue ("AND(" +(($sameChecks -join ",") -replace '<>"Same"','="Changed"') +")" ) -BackgroundColor $ChangeBackgroundColor - } - #We've made a bunch of things wider so now is the time to autofit columns. Any hiding has to come AFTER this, because it unhides things - if ($env:NoAutoSize) {Write-Warning "Autofit is not available with this OS configuration."} - else {$sheet.Cells.AutoFitColumns()} - - #if we have a key field (we didn't concatenate all fields) use what we built up in $sameChecks to apply conditional formatting to it (Row no will be in column A, Key in Column B) - if ($Key -ne '*') { - Add-ConditionalFormatting -Worksheet $sheet -Range "B2:B1048576" -ForeGroundColor $KeyFontColor -BackgroundPattern 'None' -RuleType Expression -ConditionValue ("OR(" +($sameChecks -join ",") +")" ) - $sheet.view.FreezePanes(2, 3) - } - else {$sheet.view.FreezePanes(2, 2) } - #Go back over the headings to find and hide the "is" columns; - foreach ($cell in $sheet.Cells[($sheet.Dimension.Address -replace "\d+$","1")].Where({$_.value -match "\sIS$"}) ) { - $sheet.Column($cell.start.Column).HIDDEN = $true - } - - #If specified, look over the headings for "row" and hide the columns which say "this was in row such-and-such" - if ($HideRowNumbers) { - foreach ($cell in $sheet.Cells[($sheet.Dimension.Address -replace "\d+$","1")].Where({$_.value -match "Row$"}) ) { - $sheet.Column($cell.start.Column).HIDDEN = $true - } - } - if ($Passthru) {$excel} - else {Close-ExcelPackage -ExcelPackage $excel -Show:$Show} - Write-Progress -Activity "Merging sheets" -Completed - } -} diff --git a/New-ConditionalText.ps1 b/New-ConditionalText.ps1 deleted file mode 100644 index a0fb189..0000000 --- a/New-ConditionalText.ps1 +++ /dev/null @@ -1,84 +0,0 @@ -function New-ConditionalText { - <# - .SYNOPSIS - 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 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. - .PARAMETER ConditionalType - One of the supported rules; by default "ContainsText" is selected. - .PARAMETER Text - The text (or other value) to use in the rule. Note that Equals, GreaterThan/LessThan rules require text to wrapped in double quotes. - .PARAMETER ConditionalTextColor - The font color for the cell - by default: "DarkRed". - .PARAMETER BackgroundColor - The fill color for the cell - by default: "LightPink". - .PARAMETER PatternType - The background pattern for the cell - by default: "Solid" - .EXAMPLE - > - $ct = New-ConditionalText -Text 'Ferrari' - Export-Excel -ExcelPackage $excel -ConditionalTest $ct -show - - The first line creates a definition object which will highlight the word - "Ferrari" in any cell. and the second uses Export-Excel with an open package - to apply the format and save and open the file. - .EXAMPLE - > - $ct = New-ConditionalText -Text "Ferrari" - $ct2 = New-ConditionalText -Range $worksheet.Names["FinishPosition"].Address -ConditionalType LessThanOrEqual -Text 3 -ConditionalTextColor Red -BackgroundColor White - Export-Excel -ExcelPackage $excel -ConditionalText $ct,$ct2 -show - - This builds on the previous example, and specifies a condition of <=3 with - a format of red text on a white background; this applies to a named range - "Finish Position". The range could be written -Range "C:C" to specify a - named column, or -Range "C2:C102" to specify certain cells in the column. - .Link - Add-ConditionalFormatting - New-ConditionalFormattingIconSet - #> - [cmdletbinding()] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system State')] - param( - #[Parameter(Mandatory=$true)] - [Alias("ConditionValue")] - $Text, - [Alias("ForeGroundColor")] - $ConditionalTextColor=[System.Drawing.Color]::DarkRed, - $BackgroundColor=[System.Drawing.Color]::LightPink, - [String]$Range, - [OfficeOpenXml.Style.ExcelFillStyle]$PatternType=[OfficeOpenXml.Style.ExcelFillStyle]::Solid, - [ValidateSet( - "LessThan", "LessThanOrEqual", "GreaterThan", "GreaterThanOrEqual", - "Equal", "NotEqual", - "Top", "TopPercent", "Bottom", "BottomPercent", - "ContainsText", "NotContainsText", "BeginsWith", "EndsWith", - "ContainsBlanks", "NotContainsBlanks", "ContainsErrors", "NotContainsErrors", - "DuplicateValues", "UniqueValues", - "Tomorrow", "Today", "Yesterday", "Last7Days", - "NextWeek", "ThisWeek", "LastWeek", - "NextMonth", "ThisMonth", "LastMonth", - "AboveAverage", "AboveOrEqualAverage", "BelowAverage", "BelowOrEqualAverage" - )] - [Alias("RuleType")] - $ConditionalType="ContainsText" - ) - - $obj = [PSCustomObject]@{ - Text = $Text - ConditionalTextColor = $ConditionalTextColor - ConditionalType = $ConditionalType - PatternType = $PatternType - Range = $Range - BackgroundColor = $BackgroundColor - } - - $obj.pstypenames.Clear() - $obj.pstypenames.Add("ConditionalText") - $obj -} \ No newline at end of file diff --git a/New-ExcelChart.ps1 b/New-ExcelChart.ps1 deleted file mode 100644 index 2a1c98b..0000000 --- a/New-ExcelChart.ps1 +++ /dev/null @@ -1,471 +0,0 @@ -function New-ExcelChartDefinition { - <# - .SYNOPSIS - 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, - or to Add-PivotTable with the -PivotChartDefinition parameter. - This command sets up those definitions. - .PARAMETER Title - The title for the chart. - .PARAMETER TitleBold - Sets the title in bold face. - .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". - .PARAMETER XRange - The range of cells containing values for the X-Axis - usually labels. - .PARAMETER YRange - The range(s) of cells holding values for the Y-Axis - usually "data". - .PARAMETER Width - Width of the chart in pixels. Defaults to 500. - .PARAMETER Height - Height of the chart in pixels. Defaults to 350. - .PARAMETER Row - Row position of the top left corner of the chart. 0 places at the top of the sheet, 1 below row 1 and so on. - .PARAMETER RowOffSetPixels - Offset to position the chart by a fraction of a row. - .PARAMETER Column - Column position of the top left corner of the chart. 0 places at the edge of the sheet 1 to the right of column A and so on. - .PARAMETER ColumnOffSetPixels - Offset to position the chart by a fraction of a column. - .PARAMETER NoLegend - If specified, turns off display of the key. If you only have one data series it may be preferable to use the title to say what the chart is. - .PARAMETER SeriesHeader - Specifies explicit name(s) for the data series, which will appear in the legend/key - .PARAMETER LegendPosition - Location of the key, either "Left", "Right", "Top", "Bottom" or "TopRight". - .PARAMETER LegendSize - 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 ShowPercent - Attaches a percentage label in charts which support this. - .PARAMETER XAxisTitleText - Specifies a title for the X-axis. - .PARAMETER XAxisTitleBold - Sets the X-axis title in bold face. - .PARAMETER XAxisTitleSize - Sets the font size for the axis title. - .PARAMETER XAxisNumberformat - 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. - .PARAMETER XMinorUnit - Spacing for the minor gridlines / tick marks along the X-axis. - .PARAMETER XMaxValue - Maximum value for the scale along the X-axis. - .PARAMETER XMinValue - Minimum value for the scale along the X-axis. - .PARAMETER xAxisPosition - Position for the X-axis ("Top" or" Bottom"). - .PARAMETER YAxisTitleText - Specifies a title for the Y-axis. - .PARAMETER YAxisTitleBold - Sets the Y-axis title in bold face. - .PARAMETER YAxisTitleSize - Sets the font size for the Y-axis title. - .PARAMETER YAxisNumberformat - 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. - .PARAMETER YMinorUnit - Spacing for the minor gridlines / tick marks on the Y-axis. - .PARAMETER YMaxValue - Maximum value on the Y-axis. - .PARAMETER YMinValue - Minimum value on the Y-axis. - .PARAMETER YAxisPosition - Position for the Y-axis ("Left" or "Right"). - .PARAMETER Header - 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 ` - -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 - - 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 . - #> - [Alias("New-ExcelChart")] #This was the former name. The new name reflects that we are defining a chart, not making one in the workbook. - [cmdletbinding()] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Does not change system State')] - param( - $Title = "Chart Title", - $Header, - [OfficeOpenXml.Drawing.Chart.eChartType]$ChartType = "ColumnStacked", - [OfficeOpenXml.Drawing.Chart.eTrendLine[]]$ChartTrendLine, - $XRange, - $YRange, - $Width = 500, - $Height = 350, - $Row = 0, - $RowOffSetPixels = 10, - $Column = 6, - $ColumnOffSetPixels = 5, - [OfficeOpenXml.Drawing.Chart.eLegendPosition]$LegendPosition, - $LegendSize, - [Switch]$LegendBold, - [Switch]$NoLegend, - [Switch]$ShowCategory, - [Switch]$ShowPercent, - $SeriesHeader, - [Switch]$TitleBold, - [Int]$TitleSize , - [String]$XAxisTitleText, - [Switch]$XAxisTitleBold, - $XAxisTitleSize , - [string]$XAxisNumberformat, - $XMajorUnit, - $XMinorUnit, - $XMaxValue, - $XMinValue, - [OfficeOpenXml.Drawing.Chart.eAxisPosition]$XAxisPosition , - [String]$YAxisTitleText, - [Switch]$YAxisTitleBold, - $YAxisTitleSize, - [string]$YAxisNumberformat, - $YMajorUnit, - $YMinorUnit, - $YMaxValue, - $YMinValue, - [OfficeOpenXml.Drawing.Chart.eAxisPosition]$YAxisPosition - ) - if ( $Header ) { Write-Warning "The header parameter is ignored." } #Nothing was done with it when creating a chart. - #might be able to do [PSCustomObject]$PsboundParameters, the defaults here match those in Add-Excel Chart - [PSCustomObject]@{ - Title = $Title - ChartType = $ChartType - ChartTrendLine = $ChartTrendLine - XRange = $XRange - YRange = $YRange - Width = $Width - Height = $Height - Row = $Row - RowOffSetPixels = $RowOffSetPixels - Column = $Column - ColumnOffSetPixels = $ColumnOffSetPixels - LegendPosition = $LegendPosition - LegendSize = $LegendSize - Legendbold = $LegendBold - NoLegend = $NoLegend -as [Boolean] - ShowCategory = $ShowCategory -as [Boolean] - ShowPercent = $ShowPercent -as [Boolean] - SeriesHeader = $SeriesHeader - TitleBold = $TitleBold -as [Boolean] - TitleSize = $TitleSize - XAxisTitleText = $XAxisTitleText - XAxisTitleBold = $XAxisTitleBold -as [Boolean] - XAxisTitleSize = $XAxisTitleSize - XAxisNumberformat = $XAxisNumberformat - XMajorUnit = $XMajorUnit - XMinorUnit = $XMinorUnit - XMaxValue = $XMaxValue - XMinValue = $XMinValue - XAxisPosition = $XAxisPosition - YAxisTitleText = $YAxisTitleText - YAxisTitleBold = $YAxisTitleBold -as [Boolean] - YAxisTitleSize = $YAxisTitleSize - YAxisNumberformat = $YAxisNumberformat - YMajorUnit = $YMajorUnit - YMinorUnit = $YMinorUnit - YMaxValue = $YMaxValue - YMinValue = $YMinValue - YAxisPosition = $YAxisPosition - } -} - -function Add-ExcelChart { - <# - .SYNOPSIS - 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 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 existing Sheet where the chart will be created. - .PARAMETER Title - The title for the chart. - .PARAMETER TitleBold - Sets the title in bold face. - .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". - .PARAMETER XRange - The range of cells containing values for the X-Axis - usually labels. - .PARAMETER YRange - The range(s) of cells holding values for the Y-Axis - usually "data". - .PARAMETER PivotTable - Instead of specify X and Y ranges, get data from a PivotTable by passing a PivotTable Object. - .PARAMETER Width - Width of the chart in Pixels. Defaults to 500. - .PARAMETER Height - Height of the chart in Pixels. Defaults to 350. - .PARAMETER Row - Row position of the top left corner of the chart. 0 places at the top of the sheet, 1 below row 1 and so on. - .PARAMETER RowOffSetPixels - Offset to position the chart by a fraction of a row. - .PARAMETER Column - Column position of the top left corner of the chart. 0 places at the edge of the sheet 1 to the right of column A and so on. - .PARAMETER ColumnOffSetPixels - Offset to position the chart by a fraction of 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. The contents of a cell can be specified in the from =Sheet9!Z10 . - .PARAMETER LegendPosition - Location of the key, either left, right, top, bottom or TopRight. - .PARAMETER LegendSize - 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 ShowPercent - Attaches a percentage label in charts which support this. - .PARAMETER XAxisTitleText - Specifies a title for the X-axis. - .PARAMETER XAxisTitleBold - Sets the X-axis title in bold face. - .PARAMETER XAxisTitleSize - Sets the font size for the axis title. - .PARAMETER XAxisNumberformat - 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. - .PARAMETER XMinorUnit - Spacing for the minor gridlines / tick marks along the X-axis. - .PARAMETER XMaxValue - Maximum value for the scale along the X-axis. - .PARAMETER XMinValue - Minimum value for the scale along the X-axis. - .PARAMETER xAxisPosition - Position for the X-axis (Top or Bottom). - .PARAMETER YAxisTitleText - Specifies a title for the Y-axis. - .PARAMETER YAxisTitleBold - Sets the Y-axis title in bold face. - .PARAMETER YAxisTitleSize - Sets the font size for the Y-axis title - .PARAMETER YAxisNumberformat - 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. - .PARAMETER YMinorUnit - Spacing for the minor gridlines / tick marks on the Y-axis. - .PARAMETER YMaxValue - Maximum value on the Y-axis. - .PARAMETER YMinValue - Minimum value on the Y-axis. - .PARAMETER YAxisPosition - 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. - .EXAMPLE - > - 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 - > - 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 - > - 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 - > - 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)". - #> - [cmdletbinding(DefaultParameterSetName = 'Worksheet')] - [OutputType([OfficeOpenXml.Drawing.Chart.ExcelChart])] - param( - [Parameter(ParameterSetName = 'Workshet', Mandatory = $true)] - [OfficeOpenXml.ExcelWorksheet]$Worksheet, - [Parameter(ParameterSetName = 'PivotTable', Mandatory = $true)] - [OfficeOpenXml.Table.PivotTable.ExcelPivotTable]$PivotTable , - [String]$Title, - #$Header, Not used but referenced previously - [OfficeOpenXml.Drawing.Chart.eChartType]$ChartType = "ColumnStacked", - [OfficeOpenXml.Drawing.Chart.eTrendLine[]]$ChartTrendLine, - $XRange, - $YRange, - [int]$Width = 500, - [int]$Height = 350, - [int]$Row = 0, - [int]$RowOffSetPixels = 10, - [int]$Column = 6, - [int]$ColumnOffSetPixels = 5, - [OfficeOpenXml.Drawing.Chart.eLegendPosition]$LegendPosition, - $LegendSize, - [Switch]$LegendBold, - [Switch]$NoLegend, - [Switch]$ShowCategory, - [Switch]$ShowPercent, - [String[]]$SeriesHeader, - [Switch]$TitleBold, - [Int]$TitleSize , - [String]$XAxisTitleText, - [Switch]$XAxisTitleBold, - $XAxisTitleSize , - [string]$XAxisNumberformat, - $XMajorUnit, - $XMinorUnit, - $XMaxValue, - $XMinValue, - [OfficeOpenXml.Drawing.Chart.eAxisPosition]$XAxisPosition , - [String]$YAxisTitleText, - [Switch]$YAxisTitleBold, - $YAxisTitleSize, - [string]$YAxisNumberformat, - $YMajorUnit, - $YMinorUnit, - $YMaxValue, - $YMinValue, - [OfficeOpenXml.Drawing.Chart.eAxisPosition]$YAxisPosition, - [Switch]$PassThru - ) - try { - if ($PivotTable) { - $Worksheet = $PivotTable.WorkSheet - $chart = $Worksheet.Drawings.AddChart(("Chart" + $PivotTable.Name ), $ChartType, $PivotTable) - } - else { - $ChartName = 'Chart' + (Split-Path -Leaf ([System.IO.path]::GetTempFileName())) -replace 'tmp|\.', '' - $chart = $Worksheet.Drawings.AddChart($ChartName, $ChartType) - $chartDefCount = @($YRange).Count - if ($chartDefCount -eq 1) { - $Series = $chart.Series.Add($YRange, $XRange) - if ($ChartTrendLine) { - if ($ChartType -notmatch "stacked|3D$|pie|Doughnut|Cone|Cylinder|Pyramid") { - foreach ($trendLine in $ChartTrendLine) { - $null = $Series.TrendLines.Add($trendLine) - } - } - else { - Write-Warning "Chart trend line is not supported for chart type: $ChartType" - } - } - if ($SeriesHeader) { $Series.Header = $SeriesHeader } - else { $Series.Header = 'Series 1' } - } - else { - for ($idx = 0; $idx -lt $chartDefCount; $idx += 1) { - if ($Yrange.count -eq $xrange.count) { - $Series = $chart.Series.Add($YRange[$idx], $XRange[$idx]) - } - else { - $Series = $chart.Series.Add($YRange[$idx], $XRange) - } - if ($SeriesHeader.Count -gt 0) { - if ($SeriesHeader[$idx] -match '^=') { $Series.HeaderAddress = $SeriesHeader[$idx] -replace '^=', '' } - else { $Series.Header = $SeriesHeader[$idx] } - } - else { $Series.Header = "Series $($idx)" } - } - } - } - if ($Title) { - $chart.Title.Text = $Title - if ($TitleBold) { $chart.Title.Font.Bold = $true } - if ($TitleSize) { $chart.Title.Font.Size = $TitleSize } - } - if ($NoLegend) { $chart.Legend.Remove() } - else { - if ($PSBoundParameters.ContainsKey('LegendPosition')) { $chart.Legend.Position = $LegendPosition } - if ($PSBoundParameters.ContainsKey('LegendBold')) { $chart.Legend.Font.Bold = [boolean]$LegendBold } - if ($LegendSize) { $chart.Legend.Font.Size = $LegendSize } - } - - if ($XAxisTitleText) { - $chart.XAxis.Title.Text = $XAxisTitleText - if ($PSBoundParameters.ContainsKey('XAxisTitleBold')) { - $chart.XAxis.Title.Font.Bold = [boolean]$XAxisTitleBold - } - 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" } - #$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 } - if ($null -ne $XMinValue) { $chart.XAxis.MinValue = $XMinValue } - if ($null -ne $XMaxValue) { $chart.XAxis.MaxValue = $XMaxValue } - if ($XAxisNumberformat) { $chart.XAxis.Format = (Expand-NumberFormat $XAxisNumberformat) } - - if ($YAxisTitleText) { - $chart.YAxis.Title.Text = $YAxisTitleText - if ($PSBoundParameters.ContainsKey('YAxisTitleBold')) { - $chart.YAxis.Title.Font.Bold = [boolean]$YAxisTitleBold - } - 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" } - #$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 } - if ($null -ne $YMinValue) { $chart.YAxis.MinValue = $YMinValue } - if ($null -ne $YMaxValue) { $chart.YAxis.MaxValue = $YMaxValue } - if ($YAxisNumberformat) { $chart.YAxis.Format = (Expand-NumberFormat $YAxisNumberformat) } - if ($null -ne $chart.Datalabel) { - $chart.Datalabel.ShowCategory = [boolean]$ShowCategory - $chart.Datalabel.ShowPercent = [boolean]$ShowPercent - } - - $chart.SetPosition($Row, $RowOffsetPixels, $Column, $ColumnOffsetPixels) - $chart.SetSize($Width, $Height) - - if ($PassThru) { return $chart } - } - catch { Write-Warning -Message "Failed adding Chart to worksheet '$($WorkSheet).name': $_" } -} diff --git a/New-Plot.md b/New-Plot.md new file mode 100644 index 0000000..0c233b4 --- /dev/null +++ b/New-Plot.md @@ -0,0 +1,42 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# New-Plot + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +New-Plot +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/Open-ExcelPackage.ps1 b/Open-ExcelPackage.ps1 deleted file mode 100644 index 3c5a7b2..0000000 --- a/Open-ExcelPackage.ps1 +++ /dev/null @@ -1,129 +0,0 @@ -Function Open-ExcelPackage { -<# -.Synopsis - Returns an ExcelPackage object for the specified XLSX fil.e -.Description - Import-Excel and Export-Excel open an Excel file, carry out their tasks and close it again. - Sometimes it is necessary to open a file and do other work on it. - Open-ExcelPackage allows the file to be opened for these tasks. - It takes a -KillExcel switch to make sure Excel is not holding the file open; - a -Password parameter for existing protected files, - and a -Create switch to set-up a new file if no file already exists. -.Example - > - PS> $excel = Open-ExcelPackage -Path "$env:TEMP\test99.xlsx" -Create - $ws = Add-WorkSheet -ExcelPackage $excel - - This will create a new file in the temp folder if it doesn't already exist. - It then adds a worksheet - because no name is specified it will use the - default name of "Sheet1" -.Example - > - PS> $excel = Open-ExcelPackage -path "$xlPath" -Password $password - $sheet1 = $excel.Workbook.Worksheets["sheet1"] - Set-ExcelRange -Range $sheet1.Cells["E1:S1048576"], $sheet1.Cells["V1:V1048576"] -NFormat ([cultureinfo]::CurrentCulture.DateTimeFormat.ShortDatePattern) - Close-ExcelPackage $excel -Show - - This will open the password protected file at $xlPath using the password stored - in $Password. Sheet1 is selected and formatting applied to two blocks of the sheet; - then the file is and saved and loaded into Excel. -#> - [CmdLetBinding()] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")] - [OutputType([OfficeOpenXml.ExcelPackage])] - Param ( - #The path to the file to open. - [Parameter(Mandatory=$true)]$Path, - #If specified, any running instances of Excel will be terminated before opening the file. - [switch]$KillExcel, - #The password for a protected worksheet, as a [normal] string (not a secure string). - [String]$Password, - #By default Open-ExcelPackage will only opens an existing file; -Create instructs it to create a new file if required. - [switch]$Create - ) - - if($KillExcel) { - Get-Process -Name "excel" -ErrorAction Ignore | Stop-Process - while (Get-Process -Name "excel" -ErrorAction Ignore) {} - } - - $Path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path) - #If -Create was not specified only open the file if it exists already (send a warning if it doesn't exist). - if ($Create -and -not (Test-Path -Path $path)) { - #Create the directory if required. - $targetPath = Split-Path -Parent -Path $Path - if (!(Test-Path -Path $targetPath)) { - Write-Debug "Base path $($targetPath) does not exist, creating" - $null = New-item -ItemType Directory -Path $targetPath -ErrorAction Ignore - } - New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Path - } - elseif (Test-Path -Path $path) { - if ($Password) {$pkgobj = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Path , $Password } - else {$pkgobj = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Path } - if ($pkgobj) { - foreach ($w in $pkgobj.Workbook.Worksheets) { - $sb = [scriptblock]::Create(('$this.workbook.Worksheets["{0}"]' -f $w.name)) - Add-Member -InputObject $pkgobj -MemberType ScriptProperty -Name $w.name -Value $sb - } - return $pkgobj - } - } - else {Write-Warning "Could not find $path" } - } - -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 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. - .Example - Close-ExcelPackage -NoSave $excel - $excel holds a package object, this disposes of it without writing it to disk. - #> - [CmdLetBinding()] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")] - Param ( - #Package to close. - [parameter(Mandatory=$true, ValueFromPipeline=$true)] - [OfficeOpenXml.ExcelPackage]$ExcelPackage, - #Open the file in Excel. - [switch]$Show, - #Abandon the file without saving. - [Switch]$NoSave, - #Save file with a new name (ignored if -NoSave Specified). - $SaveAs, - #Password to protect the file. - [ValidateNotNullOrEmpty()] - [String]$Password, - #Attempt to recalculation the workbook before saving - [switch]$Calculate - ) - if ( $NoSave) {$ExcelPackage.Dispose()} - else { - if ($Calculate) { - try { [OfficeOpenXml.CalculationExtension]::Calculate($ExcelPackage.Workbook) } - Catch { Write-Warning "One or more errors occured while calculating, save will continue, but there may be errors in the workbook."} - } - if ($SaveAs) { - $SaveAs = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($SaveAs) - if ($Password) {$ExcelPackage.SaveAs( $SaveAs, $Password ) } - else {$ExcelPackage.SaveAs( $SaveAs)} - } - Else { - if ($Password) {$ExcelPackage.Save($Password) } - else {$ExcelPackage.Save() } - $SaveAs = $ExcelPackage.File.FullName - } - $ExcelPackage.Dispose() - if ($Show) {Start-Process -FilePath $SaveAs } - } -} - diff --git a/Pivot/Pivot.md b/Pivot/Pivot.md new file mode 100644 index 0000000..1ff8fcd --- /dev/null +++ b/Pivot/Pivot.md @@ -0,0 +1,107 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Pivot + +## SYNOPSIS +{{ Fill in the Synopsis }} + +## SYNTAX + +``` +Pivot [[-targetData] ] [[-pivotRows] ] [[-pivotData] ] [[-ChartType] ] + [] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -ChartType +{{ Fill ChartType Description }} + +```yaml +Type: eChartType +Parameter Sets: (All) +Aliases: +Accepted values: 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 + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -pivotData +{{ Fill pivotData Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -pivotRows +{{ Fill pivotRows Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -targetData +{{ Fill targetData Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### None + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/Pivot.ps1 b/Pivot/Pivot.ps1 similarity index 100% rename from Pivot.ps1 rename to Pivot/Pivot.ps1 diff --git a/PivotTable.ps1 b/PivotTable.ps1 deleted file mode 100644 index 5eca5dd..0000000 --- a/PivotTable.ps1 +++ /dev/null @@ -1,420 +0,0 @@ -function Add-PivotTable { - <# - .Synopsis - Adds a PivotTable (and optional PivotChart) to a workbook. - .Description - 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" - 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. - 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 - > - 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 (product) 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 - > - $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. - #> - [cmdletbinding(defaultParameterSetName = 'ChartbyParams')] - [OutputType([OfficeOpenXml.Table.PivotTable.ExcelPivotTable])] - param ( - #Name for the new PivotTable - this will be the name of a sheet in the Workbook. - [Parameter(Mandatory = $true)] - [string]$PivotTableName, - #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. - $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 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. - $PivotData, - #Fields to set as columns in the PivotTable. - $PivotColumns, - #Fields to use to filter in the PivotTable. - $PivotFilter, - #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 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". - [Switch]$NoTotalsInPivot, - #The name of a row field which should be grouped by parts of the date/time (ignored if GroupDateRow is not specified) - [String]$GroupDateRow, - #The Part(s) of the date to use in the grouping (ignored if GroupDateRow is not specified) - [OfficeOpenXml.Table.PivotTable.eDateGroupBy[]]$GroupDatePart, - #The name of a row field which should be grouped by Number (e.g 0-99, 100-199, 200-299 ) - [String]$GroupNumericRow, - #The starting point for grouping - [double]$GroupNumericMin = 0 , - #The endpoint for grouping - [double]$GroupNumericMax = [Double]::MaxValue , - #The interval for grouping - [double]$GroupNumericInterval = 100 , - #Number format to apply to the data cells in the PivotTable. - [string]$PivotNumberFormat, - #Apply a table style to the PivotTable. - [OfficeOpenXml.Table.TableStyles]$PivotTableStyle, - #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. - [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). - [Parameter(ParameterSetName = 'ChartbyParams')] - [int]$ChartHeight = 400 , - #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). - [Parameter(ParameterSetName = 'ChartbyParams')] - [Int]$ChartColumn = 4, - #Vertical offset of the chart from the cell corner. - [Parameter(ParameterSetName = 'ChartbyParams')] - [Int]$ChartRowOffSetPixels = 0 , - [Parameter(ParameterSetName = 'ChartbyParams')] - #Horizontal offset of the chart from the cell corner. - [Int]$ChartColumnOffSetPixels = 0, - #Type of chart; defaults to "Pie". - [Parameter(ParameterSetName = 'ChartbyParams')] - [OfficeOpenXml.Drawing.Chart.eChartType]$ChartType = 'Pie', - #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. - [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 PivotTable will not be active UNLESS Activate is specified. - [switch]$Activate, - #Return the PivotTable so it can be customized. - [Switch]$PassThru - ) - if ($PivotTableName.length -gt 250) { - Write-warning -Message "PivotTable name will be truncated" - $PivotTableName = $PivotTableName.Substring(0, 250) - } - if ($Address) { - [OfficeOpenXml.ExcelWorksheet]$wsPivot = $address.Worksheet - } - else { - 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 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 PivotTable. $_" } - } - #if the pivot doesn't exist, create it. - 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 . - if ( $SourceWorkSheet -is [string]) { - $SourceWorkSheet = $ExcelPackage.Workbook.Worksheets.where( {$_.name -Like $SourceWorkSheet})[0] - } - elseif ( $SourceWorkSheet -is [int] ) { - $SourceWorkSheet = $ExcelPackage.Workbook.Worksheets[$SourceWorkSheet] - } - if ( $SourceRange -is [OfficeOpenXml.Table.ExcelTable]) {$SourceRange = $SourceRange.Address } - if ( $sourceRange -is [OfficeOpenXml.ExcelRange] -or - $SourceRange -is [OfficeOpenXml.ExcelAddress]) { - $pivotTable = $wsPivot.PivotTables.Add($Address, $SourceRange, $pivotTableName) - } - elseif (-not $SourceRange) { - $pivotTable = $wsPivot.PivotTables.Add($Address, $SourceWorkSheet.cells[$SourceWorkSheet.Dimension.Address], $pivotTableName) - } - elseif ($SourceWorkSheet -isnot [OfficeOpenXml.ExcelWorksheet] ) { - Write-Warning -Message "Could not find source Worksheet for pivot-table '$pivotTableName'." ; return - } - 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 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." } - } - foreach ($Column in $PivotColumns) { - try {$null = $pivotTable.ColumnFields.Add($pivotTable.Fields[$Column])} - catch {Write-Warning -message "Could not add '$Column' to Columns in PivotTable $pivotTableName." } - } - if ($PivotData -is [HashTable] -or $PivotData -is [System.Collections.Specialized.OrderedDictionary]) { - $PivotData.Keys | ForEach-Object { - try { - $df = $pivotTable.DataFields.Add($pivotTable.Fields[$_]) - $df.Function = $PivotData.$_ - if ($PivotNumberFormat) {$df.Format = (Expand-NumberFormat -NumberFormat $PivotNumberFormat)} - } - catch {Write-Warning -message "Problem adding data fields to PivotTable $pivotTableName." } - } - } - else { - foreach ($field in $PivotData) { - try { - $df = $pivotTable.DataFields.Add($pivotTable.Fields[$field]) - $df.Function = 'Count' - } - catch {Write-Warning -message "Problem adding data field '$field' to PivotTable $pivotTableName." } - } - } - foreach ( $pFilter in $PivotFilter) { - try { $null = $pivotTable.PageFields.Add($pivotTable.Fields[$pFilter])} - catch {Write-Warning -message "Could not add '$pFilter' to Filter/Page fields in PivotTable $pivotTableName." } - } - if ($NoTotalsInPivot) {$PivotTotals = "None" } - if ($PivotTotals -eq "None" -or $PivotTotals -eq "Columns") { $pivotTable.RowGrandTotals = $false } - elseif ($PivotTotals -eq "Both" -or $PivotTotals -eq "Rows") { $pivotTable.RowGrandTotals = $true } - if ($PivotTotals -eq "None" -or $PivotTotals -eq "Rows") { $pivotTable.ColumGrandTotals = $false } # Epplus spelling mistake, not mine! - elseif ($PivotTotals -eq "Both" -or $PivotTotals -eq "Columns") { $pivotTable.ColumGrandTotals = $true } - if ($PivotDataToColumn ) { $pivotTable.DataOnRows = $false } - if ($PivotTableStyle) { $pivotTable.TableStyle = $PivotTableStyle} - if ($GroupNumericRow) { - $r = $pivotTable.RowFields.Where( {$_.name -eq $GroupNumericRow }) - if (-not $r ) {Write-Warning -Message "Could not find a Row field named '$GroupNumericRow'; no numeric grouping will be done."} - else {$r.AddNumericGrouping($GroupNumericMin, $GroupNumericMax, $GroupNumericInterval)} - } - if ($GroupDateRow -and $PSBoundParameters.ContainsKey("GroupDatePart")) { - $r = $pivotTable.RowFields.Where( {$_.name -eq $GroupDateRow }) - if (-not $r ) {Write-Warning -Message "Could not find a Row field named '$GroupDateRow'; no date grouping will be done."} - else {$r.AddDateGrouping($GroupDatePart)} - } - } - catch {Write-Warning -Message "Failed adding PivotTable '$pivotTableName': $_"} - } - else { - 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.SourceRange = $SourceWorkSheet.cells[$SourceRange] - #change for epPlus 4.5 - Previously needed to hack the xml - # $pivotTable.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref = $SourceRange - - } - - #Create the chart if it doesn't exist, leave alone if it does. - if ($IncludePivotChart -and -not $wsPivot.Drawings["Chart$pivotTableName"] ) { - try {Add-ExcelChart -PivotTable $pivotTable -ChartType $ChartType -Width $ChartWidth -Height $ChartHeight -Row $ChartRow -Column $ChartColumn -RowOffSetPixels $ChartRowOffSetPixels -ColumnOffSetPixels $ChartColumnOffSetPixels -Title $ChartTitle -NoLegend:$NoLegend -ShowCategory:$ShowCategory -ShowPercent:$ShowPercent } - catch {Write-Warning -Message "Failed adding chart for pivotable '$pivotTableName': $_"} - } - elseif ($PivotChartDefinition -and -not $wsPivot.Drawings["Chart$pivotTableName"]) { - if ($PivotChartDefinition -is [System.Management.Automation.PSCustomObject]) { - $params = @{PivotTable = $pivotTable } - $PivotChartDefinition.PSObject.Properties | ForEach-Object {if ( $null -ne $_.value) {$params[$_.name] = $_.value}} - Add-ExcelChart @params - } - elseif ($PivotChartDefinition -is [hashtable] -or $PivotChartDefinition -is [System.Collections.Specialized.OrderedDictionary]) { - Add-ExcelChart -PivotTable $pivotTable @PivotChartDefinition - } - } - if ($PassThru) {return $pivotTable} -} - -function New-PivotTableDefinition { - <# - .Synopsis - Creates PivotTable definitons for Export-Excel - .Description - 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 - > - PS> $pt = New-PivotTableDefinition -PivotTableName "PT1" -SourceWorkSheet "Sheet1" -PivotRows "Status" -PivotData @{Status='Count' } -PivotFilter 'StartType' -IncludePivotChart -ChartType BarClustered3D - $Pt += New-PivotTableDefinition -PivotTableName "PT2" -SourceWorkSheet "Sheet2" -PivotRows "Company" -PivotData @{Company='Count'} -IncludePivotChart -ChartType PieExploded3D -ShowPercent -ChartTitle "Breakdown of processes by company" - Get-Service | Select-Object -Property Status,Name,DisplayName,StartType | Export-Excel -Path .\test.xlsx -AutoSize - Get-Process | Select-Object -Property Name,Company,Handles,CPU,VM | Export-Excel -Path .\test.xlsx -AutoSize -WorksheetName 'sheet2' - $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. - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system State')] - param( - [Parameter(Mandatory)] - [Alias("PivtoTableName")]#Previous typo - use alias to avoid breaking scripts - $PivotTableName, - #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 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 PivotTable - $PivotColumns, - #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 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, - #The name of a row field which should be grouped by parts of the date/time (ignored if GroupDateRow is not specified) - [String]$GroupDateRow, - #The Part(s) of the date to use in the grouping (ignored if GroupDateRow is not specified) - [OfficeOpenXml.Table.PivotTable.eDateGroupBy[]]$GroupDatePart, - #The name of a row field which should be grouped by Number (e.g 0-99, 100-199, 200-299 ) - [String]$GroupNumericRow, - #The starting point for grouping - [double]$GroupNumericMin = 0 , - #The endpoint for grouping - [double]$GroupNumericMax = [Double]::MaxValue , - #The interval for grouping - [double]$GroupNumericInterval = 100 , - #Number format to apply to the data cells in the PivotTable - [string]$PivotNumberFormat, - #Apply a table style to the PivotTable - [OfficeOpenXml.Table.TableStyles]$PivotTableStyle, - #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. - [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) - [Parameter(ParameterSetName = 'ChartbyParams')] - [int]$ChartHeight = 400 , - #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) - [Parameter(ParameterSetName = 'ChartbyParams')] - [Int]$ChartColumn = 4, - #Vertical offset of the chart from the cell corner. - [Parameter(ParameterSetName = 'ChartbyParams')] - [Int]$ChartRowOffSetPixels = 0 , - #Horizontal offset of the chart from the cell corner. - [Parameter(ParameterSetName = 'ChartbyParams')] - [Int]$ChartColumnOffSetPixels = 0, - #Type of chart - [Parameter(ParameterSetName = 'ChartbyParams')] - [OfficeOpenXml.Drawing.Chart.eChartType]$ChartType = 'Pie', - #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. - [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 PivotTable will not be active UNLESS Activate is specified - [switch]$Activate - ) - $validDataFuntions = [system.enum]::GetNames([OfficeOpenXml.Table.PivotTable.DataFieldFunctions]) - - if ($PivotData.values.Where( {$_ -notin $validDataFuntions}) ) { - Write-Warning -Message ("Pivot data functions might not be valid, they should be one of " + ($validDataFuntions -join ", ") + ".") - } - - $parameters = @{} + $PSBoundParameters - if ($NoTotalsInPivot) { - $parameters.Remove('NoTotalsInPivot') - $parameters["PivotTotals"] = "None" - } - $parameters.Remove('PivotTableName') - if ($PivotChartDefinition) { - $parameters.PivotChartDefinition.XRange = $null - $parameters.PivotChartDefinition.YRange = $null - $parameters.PivotChartDefinition.SeriesHeader = $null - } - @{$PivotTableName = $parameters} -} diff --git a/SetFormat.ps1 b/SetFormat.ps1 deleted file mode 100644 index 272be88..0000000 --- a/SetFormat.ps1 +++ /dev/null @@ -1,496 +0,0 @@ -function Set-ExcelRange { - <# - .SYNOPSIS - Applies number, font, alignment and/or color formatting, values or formulas to a range of Excel cells. - .DESCRIPTION - Set-ExcelRange was created to set the style elements for a range of cells, - this includes auto-sizing and hiding, setting font elements (Name, Size, - Bold, Italic, Underline & UnderlineStyle and Subscript & SuperScript), - font and background colors, borders, text wrapping, rotation, alignment - within cells, and number format. - It was orignally named "Set-Format", but it has been extended to set - Values, Formulas and ArrayFormulas (sometimes called Ctrl-shift-Enter - [CSE] formulas); because of this, the name has become Set-ExcelRange - but the old name of Set-Format is preserved as an alias. - .EXAMPLE - $sheet.Column(3) | Set-ExcelRange -HorizontalAlignment Right -NumberFormat "#,###" -AutoFit - - Selects column 3 from a sheet object (within a workbook object, which - is a child of the ExcelPackage object) and passes it to Set-ExcelRange - which formats numbers as a integers with comma-separated groups, - aligns it right, and auto-fits the column to the contents. - .EXAMPLE - Set-ExcelRange -Range $sheet.Cells["E1:H1048576"] -HorizontalAlignment Right -NumberFormat "#,###" - - Instead of piping the address, this version specifies a block of cells - and applies similar formatting. - .EXAMPLE - Set-ExcelRange $excel.Workbook.Worksheets[1].Tables["Processes"] -Italic - - This time instead of specifying a range of cells, a table is selected - by name and formatted as italic. - #> - [cmdletbinding()] - [Alias("Set-Format")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system state')] - Param ( - #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. - [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. - [Alias("NFormat")] - $NumberFormat, - #Style of border to draw around the range. - [OfficeOpenXml.Style.ExcelBorderStyle]$BorderAround, - #Color of the border. - $BorderColor=[System.Drawing.Color]::Black, - #Style for the bottom border. - [OfficeOpenXml.Style.ExcelBorderStyle]$BorderBottom, - #Style for the top border. - [OfficeOpenXml.Style.ExcelBorderStyle]$BorderTop, - #Style for the left border. - [OfficeOpenXml.Style.ExcelBorderStyle]$BorderLeft, - #Style for the right border. - [OfficeOpenXml.Style.ExcelBorderStyle]$BorderRight, - #Colour for the text - if none is specified it will be left as it is. - [Alias('ForegroundColor')] - $FontColor, - #Value for the cell. - $Value, - #Formula for the cell. - $Formula, - #Specifies formula should be an array formula (a.k.a CSE [ctrl-shift-enter] formula). - [Switch]$ArrayFormula, - #Clear Bold, Italic, StrikeThrough and Underline and set color to Black. - [Switch]$ResetFont, - #Make text bold; use -Bold:$false to remove bold. - [Switch]$Bold, - #Make text italic; use -Italic:$false to remove italic. - [Switch]$Italic, - #Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. - [Switch]$Underline, - #Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". - [OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single, - #Strike through text; use -Strikethru:$false to remove Strike through - [Switch]$StrikeThru, - #Subscript or Superscript (or none). - [OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift, - #Font to use - Excel defaults to Calibri. - [String]$FontName, - #Point size for the text. - [float]$FontSize, - #Change background color. - $BackgroundColor, - #Background pattern - Solid by default. - [OfficeOpenXml.Style.ExcelFillStyle]$BackgroundPattern = [OfficeOpenXml.Style.ExcelFillStyle]::Solid , - #Secondary color for background pattern. - [Alias("PatternColour")] - $PatternColor, - #Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. - [Switch]$WrapText, - #Position cell contents to Left, Right, Center etc. default is 'General'. - [OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment, - #Position cell contents to Top, Bottom or Center. - [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). - [Alias("AutoFit")] - [Switch]$AutoSize, - #Set cells to a fixed width (columns or ranges only), ignored if Autosize is specified. - [float]$Width, - #Set cells to a fixed height (rows or ranges only). - [float]$Height, - #Hide a row or column (not a range); use -Hidden:$false to unhide. - [Switch]$Hidden, - #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. - [Switch]$Locked, - #Merges cells - it is recommended that you explicitly set -HorizontalAlignment - [Switch]$Merge - ) - process { - if ($Range -is [Array]) { - $null = $PSBoundParameters.Remove("Range") - $Range | Set-ExcelRange @PSBoundParameters - } - else { - #We should accept, a worksheet and a name of a range or a cell address; a table; the address of a table; a named range; a row, a column or .Cells[ ] - if ($Range -is [OfficeOpenXml.Table.ExcelTable]) {$Range = $Range.Address} - elseif ($WorkSheet -and ($Range -is [string] -or $Range -is [OfficeOpenXml.ExcelAddress])) { - $Range = $WorkSheet.Cells[$Range] - } - elseif ($Range -is [string]) {Write-Warning -Message "The range pararameter you have specified also needs a worksheet parameter." ;return} - #else we assume $Range is a range. - if ($ClearAll) { - $Range.Clear() - } - if ($ResetFont) { - $Range.Style.Font.Color.SetColor( ([System.Drawing.Color]::Black)) - $Range.Style.Font.Bold = $false - $Range.Style.Font.Italic = $false - $Range.Style.Font.UnderLine = $false - $Range.Style.Font.Strike = $false - $Range.Style.Font.VerticalAlign = [OfficeOpenXml.Style.ExcelVerticalAlignmentFont]::None - } - if ($PSBoundParameters.ContainsKey('Underline')) { - $Range.Style.Font.UnderLine = [boolean]$Underline - $Range.Style.Font.UnderLineType = $UnderLineType - } - if ($PSBoundParameters.ContainsKey('Bold')) { - $Range.Style.Font.Bold = [boolean]$bold - } - if ($PSBoundParameters.ContainsKey('Italic')) { - $Range.Style.Font.Italic = [boolean]$italic - } - if ($PSBoundParameters.ContainsKey('StrikeThru')) { - $Range.Style.Font.Strike = [boolean]$StrikeThru - } - if ($PSBoundParameters.ContainsKey('FontSize')){ - $Range.Style.Font.Size = $FontSize - } - if ($PSBoundParameters.ContainsKey('FontName')){ - $Range.Style.Font.Name = $FontName - } - if ($PSBoundParameters.ContainsKey('FontShift')){ - $Range.Style.Font.VerticalAlign = $FontShift - } - if ($PSBoundParameters.ContainsKey('FontColor')){ - if ($FontColor -is [string]) {$FontColor = [System.Drawing.Color]::$FontColor } - $Range.Style.Font.Color.SetColor( $FontColor) - } - if ($PSBoundParameters.ContainsKey('TextRotation')) { - $Range.Style.TextRotation = $TextRotation - } - if ($PSBoundParameters.ContainsKey('WrapText')) { - $Range.Style.WrapText = [boolean]$WrapText - } - if ($PSBoundParameters.ContainsKey('HorizontalAlignment')) { - $Range.Style.HorizontalAlignment = $HorizontalAlignment - } - if ($PSBoundParameters.ContainsKey('VerticalAlignment')) { - $Range.Style.VerticalAlignment = $VerticalAlignment - } - if ($PSBoundParameters.ContainsKey('Merge')) { - $Range.Merge = [boolean]$Merge - } - if ($PSBoundParameters.ContainsKey('Value')) { - if ($Value -match '^=') {$PSBoundParameters["Formula"] = $Value -replace '^=','' } - else { - $Range.Value = $Value - if ($Value -is [datetime]) { $Range.Style.Numberformat.Format = 'm/d/yy h:mm' }# This is not a custom format, but a preset recognized as date and localized. It might be overwritten in a moment - if ($Value -is [timespan]) { $Range.Style.Numberformat.Format = '[h]:mm:ss' } - } - } - if ($PSBoundParameters.ContainsKey('Formula')) { - if ($ArrayFormula) {$Range.CreateArrayFormula(($Formula -replace '^=','')) } - else {$Range.Formula = ($Formula -replace '^=','') } - } - if ($PSBoundParameters.ContainsKey('NumberFormat')) { - $Range.Style.Numberformat.Format = (Expand-NumberFormat $NumberFormat) - } - if ($BorderColor -is [string]) {$BorderColor = [System.Drawing.Color]::$BorderColor } - if ($PSBoundParameters.ContainsKey('BorderAround')) { - $Range.Style.Border.BorderAround($BorderAround, $BorderColor) - } - if ($PSBoundParameters.ContainsKey('BorderBottom')) { - $Range.Style.Border.Bottom.Style=$BorderBottom - $Range.Style.Border.Bottom.Color.SetColor($BorderColor) - } - if ($PSBoundParameters.ContainsKey('BorderTop')) { - $Range.Style.Border.Top.Style=$BorderTop - $Range.Style.Border.Top.Color.SetColor($BorderColor) - } - if ($PSBoundParameters.ContainsKey('BorderLeft')) { - $Range.Style.Border.Left.Style=$BorderLeft - $Range.Style.Border.Left.Color.SetColor($BorderColor) - } - if ($PSBoundParameters.ContainsKey('BorderRight')) { - $Range.Style.Border.Right.Style=$BorderRight - $Range.Style.Border.Right.Color.SetColor($BorderColor) - } - if ($PSBoundParameters.ContainsKey('BackgroundColor')) { - $Range.Style.Fill.PatternType = $BackgroundPattern - if ($BackgroundColor -is [string]) {$BackgroundColor = [System.Drawing.Color]::$BackgroundColor } - $Range.Style.Fill.BackgroundColor.SetColor($BackgroundColor) - if ($PatternColor) { - if ($PatternColor -is [string]) {$PatternColor = [System.Drawing.Color]::$PatternColor } - $Range.Style.Fill.PatternColor.SetColor( $PatternColor) - } - } - if ($PSBoundParameters.ContainsKey('Height')) { - if ($Range -is [OfficeOpenXml.ExcelRow] ) {$Range.Height = $Height } - elseif ($Range -is [OfficeOpenXml.ExcelRange] ) { - ($Range.Start.Row)..($Range.Start.Row + $Range.Rows) | - ForEach-Object {$Range.WorkSheet.Row($_).Height = $Height } - } - else {Write-Warning -Message ("Can set the height of a row or a range but not a {0} object" -f ($Range.GetType().name)) } - } - if ($Autosize -and -not $env:NoAutoSize) { - try { - if ($Range -is [OfficeOpenXml.ExcelColumn]) {$Range.AutoFit() } - elseif ($Range -is [OfficeOpenXml.ExcelRange] ) { - $Range.AutoFitColumns() - - } - else {Write-Warning -Message ("Can autofit a column or a range but not a {0} object" -f ($Range.GetType().name)) } - } - catch {Write-Warning -Message "Failed autosizing columns of worksheet '$WorksheetName': $_"} - } - elseif ($AutoSize) {Write-Warning -Message "Auto-fitting columns is not available with this OS configuration." } - elseif ($PSBoundParameters.ContainsKey('Width')) { - if ($Range -is [OfficeOpenXml.ExcelColumn]) {$Range.Width = $Width} - elseif ($Range -is [OfficeOpenXml.ExcelRange] ) { - ($Range.Start.Column)..($Range.Start.Column + $Range.Columns - 1) | - ForEach-Object { - #$ws.Column($_).Width = $Width - $Range.Worksheet.Column($_).Width = $Width - } - } - else {Write-Warning -Message ("Can set the width of a column or a range but not a {0} object" -f ($Range.GetType().name)) } - } - if ($PSBoundParameters.ContainsKey('Hidden')) { - if ($Range -is [OfficeOpenXml.ExcelRow] -or - $Range -is [OfficeOpenXml.ExcelColumn] ) {$Range.Hidden = [boolean]$Hidden} - else {Write-Warning -Message ("Can hide a row or a column but not a {0} object" -f ($Range.GetType().name)) } - } - if ($PSBoundParameters.ContainsKey('Locked')) { - $Range.Style.Locked=$Locked - } - } - } -} - -function NumberFormatCompletion { - param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) - $numformats = [ordered]@{ - "General" = "General" # format ID 0 - "Number" = "0.00" # format ID 2 - "Percentage" = "0.00%" # format ID 10 - "Scientific" = "0.00E+00" # format ID 11 - "Fraction" = "# ?/?" # format ID 12 - "Short Date" = "Localized" # format ID 14 - will be translated to "mm-dd-yy" which is localized on load by Excel. - "Short Time" = "Localized" # format ID 20 - will be translated to "h:mm" which is localized on load by Excel. - "Long Time" = "Localized" # format ID 21 - will be translated to "h:mm:ss" which is localized on load by Excel. - "Date-Time" = "Localized" # format ID 22 - will be translated to "m/d/yy h:mm" which is localized on load by Excel. - "Currency" = [cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol + "#,##0.00" - "Text" = "@" # format ID 49 - "h:mm AM/PM" = "h:mm AM/PM" # format ID 18 - "h:mm:ss AM/PM" = "h:mm:ss AM/PM" # format ID 19 - "mm:ss" = "mm:ss" # format ID 45 - "[h]:mm:ss" = "Elapsed hours" # format ID 46 - "mm:ss.0" = "mm:ss.0" # format ID 47 - "d-mmm-yy" = "Localized" # format ID 15 which is localized on load by Excel. - "d-mmm" = "Localized" # format ID 16 which is localized on load by Excel. - "mmm-yy" = "mmm-yy" # format ID 17 which is localized on load by Excel. - "0" = "Whole number" # format ID 1 - "0.00" = "Number, 2 decimals" # format ID 2 or "number" - "#,##0" = "Thousand separators" # format ID 3 - "#,##0.00" = "Thousand separators and 2 decimals" # format ID 4 - "#," = "Whole thousands" - "#.0,," = "Millions, 1 Decimal" - "0%" = "Nearest whole percentage" # format ID 9 - "0.00%" = "Percentage with decimals" # format ID 10 or "Percentage" - "00E+00" = "Scientific" # format ID 11 or "Scientific" - "# ?/?" = "One Digit fraction" # format ID 12 or "Fraction" - "# ??/??" = "Two Digit fraction" # format ID 13 - "@" = "Text" # format ID 49 or "Text" - } - $numformats.keys.where({$_ -like "$wordToComplete*"} ) | ForEach-Object { - New-Object -TypeName System.Management.Automation.CompletionResult -ArgumentList "'$_'" , $_ , - ([System.Management.Automation.CompletionResultType]::ParameterValue) , $numformats[$_] - } -} -if (Get-Command -ErrorAction SilentlyContinue -name Register-ArgumentCompleter) { - Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion - Register-ArgumentCompleter -CommandName Export-Excel -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion - Register-ArgumentCompleter -CommandName New-ExcelStyle -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion - Register-ArgumentCompleter -CommandName Set-ExcelRange -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion - Register-ArgumentCompleter -CommandName Set-ExcelColumn -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion - Register-ArgumentCompleter -CommandName Set-ExcelRow -ParameterName NumberFormat -ScriptBlock $Function:NumberFormatCompletion - Register-ArgumentCompleter -CommandName Add-PivotTable -ParameterName PivotNumberFormat -ScriptBlock $Function:NumberFormatCompletion - Register-ArgumentCompleter -CommandName New-PivotTableDefinition -ParameterName PivotNumberFormat -ScriptBlock $Function:NumberFormatCompletion - Register-ArgumentCompleter -CommandName New-ExcelChartDefinition -ParameterName XAxisNumberformat -ScriptBlock $Function:NumberFormatCompletion - Register-ArgumentCompleter -CommandName New-ExcelChartDefinition -ParameterName YAxisNumberformat -ScriptBlock $Function:NumberFormatCompletion - Register-ArgumentCompleter -CommandName Add-ExcelChart -ParameterName XAxisNumberformat -ScriptBlock $Function:NumberFormatCompletion - Register-ArgumentCompleter -CommandName Add-ExcelChart -ParameterName YAxisNumberformat -ScriptBlock $Function:NumberFormatCompletion -} - -function ListFonts { - param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) - if (-not $script:FontFamilies) { - $script:FontFamilies = @("","") - try { - $script:FontFamilies = (New-Object System.Drawing.Text.InstalledFontCollection).Families.Name - } - catch {} - } - $script:FontFamilies.where({$_ -Gt "" -and $_ -like "$wordToComplete*"} ) | ForEach-Object { - New-Object -TypeName System.Management.Automation.CompletionResult -ArgumentList "'$_'" , $_ , - ([System.Management.Automation.CompletionResultType]::ParameterValue) , $_ - } -} -if (Get-Command -ErrorAction SilentlyContinue -name Register-ArgumentCompleter) { - Register-ArgumentCompleter -CommandName New-ExcelStyle -ParameterName FontName -ScriptBlock $Function:ListFonts - Register-ArgumentCompleter -CommandName Set-ExcelColumn -ParameterName FontName -ScriptBlock $Function:ListFonts - Register-ArgumentCompleter -CommandName Set-ExcelRange -ParameterName FontName -ScriptBlock $Function:ListFonts - Register-ArgumentCompleter -CommandName Set-ExcelRow -ParameterName FontName -ScriptBlock $Function:ListFonts -} - -function Expand-NumberFormat { - <# - .SYNOPSIS - Converts short names for number formats to the formatting strings used in Excel - .DESCRIPTION - Where you can type a number format you can write, for example, 'Short-Date' - and the module will translate it into the format string used by Excel. - Some formats, like Short-Date change how they are presented when Excel - loads (so date will use the local ordering of year, month and Day). Other - formats change how they appear when loaded with different cultures - (depending on the country "," or "." or " " may be the thousand seperator - although Excel always stores it as ",") - .EXAMPLE - Expand-NumberFormat percentage - - Returns "0.00%" - .EXAMPLE - Expand-NumberFormat Currency - - Returns the currency format specified in the local regional settings. This - may not be the same as Excel uses. The regional settings set the currency - symbol and then whether it is before or after the number and separated with - a space or not; for negative numbers the number may be wrapped in parentheses - or a - sign might appear before or after the number and symbol. - So this returns $#,##0.00;($#,##0.00) for English US, #,##0.00 €;€#,##0.00- - for French. (Note some Eurozone countries write €1,23 and others 1,23€ ) - In French the decimal point will be rendered as a "," and the thousand - separator as a space. - #> - [cmdletbinding()] - [OutputType([String])] - param ( - #the format string to Expand - $NumberFormat - ) - switch ($NumberFormat) { - "Currency" { - #https://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencynegativepattern(v=vs.110).aspx - $sign = [cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol - switch ([cultureinfo]::CurrentCulture.NumberFormat.CurrencyPositivePattern) { - 0 {$pos = "$Sign#,##0.00" ; break } - 1 {$pos = "#,##0.00$Sign" ; break } - 2 {$pos = "$Sign #,##0.00" ; break } - 3 {$pos = "#,##0.00 $Sign" ; break } - } - switch ([cultureinfo]::CurrentCulture.NumberFormat.CurrencyPositivePattern) { - 0 {return "$pos;($Sign#,##0.00)" } - 1 {return "$pos;-$Sign#,##0.00" } - 2 {return "$pos;$Sign-#,##0.00" } - 3 {return "$pos;$Sign#,##0.00-" } - 4 {return "$pos;(#,##0.00$Sign)" } - 5 {return "$pos;-#,##0.00$Sign" } - 6 {return "$pos;#,##0.00-$Sign" } - 7 {return "$pos;#,##0.00$Sign-" } - 8 {return "$pos;-#,##0.00 $Sign" } - 9 {return "$pos;-$Sign #,##0.00" } - 10 {return "$pos;#,##0.00 $Sign-" } - 11 {return "$pos;$Sign #,##0.00-" } - 12 {return "$pos;$Sign -#,##0.00" } - 13 {return "$pos;#,##0.00- $Sign" } - 14 {return "$pos;($Sign #,##0.00)" } - 15 {return "$pos;(#,##0.00 $Sign)" } - } - } - "Number" {return "0.00" } # format id 2 - "Percentage" {return "0.00%" } # format id 10 - "Scientific" {return "0.00E+00" } # format id 11 - "Fraction" {return "# ?/?" } # format id 12 - "Short Date" {return "mm-dd-yy" } # format id 14 localized on load by Excel. - "Short Time" {return "h:mm" } # format id 20 localized on load by Excel. - "Long Time" {return "h:mm:ss" } # format id 21 localized on load by Excel. - "Date-Time" {return "m/d/yy h:mm"} # format id 22 localized on load by Excel. - "Text" {return "@" } # format ID 49 - Default {return $NumberFormat} - } -} - -function New-ExcelStyle { - param ( - [Alias("Address")] - $Range , - #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. - [OfficeOpenXml.Style.ExcelBorderStyle]$BorderAround, - #Color of the border. - $BorderColor=[System.Drawing.Color]::Black, - #Style for the bottom border. - [OfficeOpenXml.Style.ExcelBorderStyle]$BorderBottom, - #Style for the top border. - [OfficeOpenXml.Style.ExcelBorderStyle]$BorderTop, - #Style for the left border. - [OfficeOpenXml.Style.ExcelBorderStyle]$BorderLeft, - #Style for the right border. - [OfficeOpenXml.Style.ExcelBorderStyle]$BorderRight, - #Colour for the text - if none is specified it will be left as it is. - [Alias('ForegroundColor')] - $FontColor, - #Value for the cell. - $Value, - #Formula for the cell. - $Formula, - #Specifies formula should be an array formula (a.k.a CSE [ctrl-shift-enter] formula). - [Switch]$ArrayFormula, - #Clear Bold, Italic, StrikeThrough and Underline and set color to Black. - [Switch]$ResetFont, - #Make text bold; use -Bold:$false to remove bold. - [Switch]$Bold, - #Make text italic; use -Italic:$false to remove italic. - [Switch]$Italic, - #Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. - [Switch]$Underline, - #Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". - [OfficeOpenXml.Style.ExcelUnderLineType]$UnderLineType = [OfficeOpenXml.Style.ExcelUnderLineType]::Single, - #Strike through text; use -Strikethru:$false to remove Strike through - [Switch]$StrikeThru, - #Subscript or Superscript (or none). - [OfficeOpenXml.Style.ExcelVerticalAlignmentFont]$FontShift, - #Font to use - Excel defaults to Calibri. - [String]$FontName, - #Point size for the text. - [float]$FontSize, - #Change background color. - $BackgroundColor, - #Background pattern - Solid by default. - [OfficeOpenXml.Style.ExcelFillStyle]$BackgroundPattern = [OfficeOpenXml.Style.ExcelFillStyle]::Solid , - #Secondary color for background pattern. - [Alias("PatternColour")] - $PatternColor, - #Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. - [Switch]$WrapText, - #Position cell contents to Left, Right, Center etc. default is 'General'. - [OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment, - #Position cell contents to Top, Bottom or Center. - [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). - [Alias("AutoFit")] - [Switch]$AutoSize, - #Set cells to a fixed width (columns or ranges only), ignored if Autosize is specified. - [float]$Width, - #Set cells to a fixed height (rows or ranges only). - [float]$Height, - #Hide a row or column (not a range); use -Hidden:$false to unhide. - [Switch]$Hidden, - #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. - [Switch]$Locked, - [Switch]$Merge - ) - $PSBoundParameters -} \ No newline at end of file diff --git a/Update-FirstObjectProperties.ps1 b/Update-FirstObjectProperties.ps1 deleted file mode 100644 index b053337..0000000 --- a/Update-FirstObjectProperties.ps1 +++ /dev/null @@ -1,98 +0,0 @@ -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Scope='Function', Target='Update*', Justification='Does not change system state')] -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Scope='Function', Target='Update*', Justification='Property would be incorrect')] - -param() - -Function Update-FirstObjectProperties { - <# - .SYNOPSIS - Updates the first object to contain all the properties of the object with the most properties in the array. - - .DESCRIPTION - Updates the first object to contain all the properties of the object with the most properties in the array. This is usefull when not all objects have the same quantity of properties and CmdLets like Out-GridView or Export-Excel are not able to show all the properties because the first object doesn't have them all. - - .EXAMPLE - $Array = @() - - $Obj1 = [PSCustomObject]@{ - Member1 = 'First' - Member2 = 'Second' - } - - $Obj2 = [PSCustomObject]@{ - Member1 = 'First' - Member2 = 'Second' - Member3 = 'Third' - } - - $Obj3 = [PSCustomObject]@{ - Member1 = 'First' - Member2 = 'Second' - Member3 = 'Third' - Member4 = 'Fourth' - } - - $Array = $Obj1, $Obj2, $Obj3 - $Array | Out-GridView -Title 'Not showing Member3 and Member4' - $Array | Update-FirstObjectProperties | Out-GridView -Title 'All properties are visible' - - Updates the fist object of the array by adding Member3 and Member4. - - .EXAMPLE - $ExcelParams = @{ - Path = $env:TEMP + '\Excel.xlsx' - Show = $true - Verbose = $true - } - Remove-Item -Path $ExcelParams.Path -Force -EA Ignore - - $Array = @() - - $Obj1 = [PSCustomObject]@{ - Member1 = 'First' - Member2 = 'Second' - } - - $Obj2 = [PSCustomObject]@{ - Member1 = 'First' - Member2 = 'Second' - Member3 = 'Third' - } - - $Obj3 = [PSCustomObject]@{ - Member1 = 'First' - Member2 = 'Second' - Member3 = 'Third' - Member4 = 'Fourth' - } - - $Array = $Obj1, $Obj2, $Obj3 - $Array | Out-GridView -Title 'Not showing Member3 and Member4' - $Array | Update-FirstObjectProperties | Export-Excel @ExcelParams -WorkSheetname Numbers - - Updates the first object of the array by adding property 'Member3' and 'Member4'. Afterwards. all objects are exported to an Excel file and all column headers are visible. - - .LINK - https://github.com/dfinke/ImportExcel - - .NOTES - CHANGELOG - 2017/06/08 Function born - #> - - Try { - $Union = @() - $Input | ForEach-Object { - If ($Union.Count) { - $_ | Get-Member | Where-Object {-not ($Union[0] | Get-Member $_.Name)} | ForEach-Object { - $Union[0] | Add-Member -MemberType NoteProperty -Name $_.Name -Value $Null - } - } - $Union += $_ - } - $Union - } - Catch { - throw "Failed updating the properties of the first object: $_" - } -} \ No newline at end of file diff --git a/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 b/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 index 962a08e..d85d67c 100644 --- a/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 +++ b/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 @@ -21,18 +21,6 @@ Sebastian Vettel,/wiki/Sebastian_Vettel,1987-07-03 Describe "Number format expansion and setting" { - Context "Argmument Completer for NumberFormat" { - it "Returned at least 20 items " { - (NumberFormatCompletion ).count | Should beGreaterThan 20 - } - It "Resolved percent to 'percentage' " { - $x = (NumberFormatCompletion -wordToComplete Percent) - $x.count | Should be 1 - $x.CompletionText | Should match "^'.*'$" - $x.ToolTip | Should be "0.00%" - $x.ListItemText | Should be "Percentage" - } - } Context "Expand-NumberFormat function" { It "Expanded named number formats as expected " { $r = [regex]::Escape([cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol) diff --git a/en-US/ImportExcel-help.xml b/en-US/ImportExcel-help.xml new file mode 100644 index 0000000..a7eb2b6 --- /dev/null +++ b/en-US/ImportExcel-help.xml @@ -0,0 +1,23342 @@ + + + + + Add-ConditionalFormatting + Add + ConditionalFormatting + + Adds conditional formatting to all or part of a worksheet. + + + + Conditional formatting allows Excel to: + * Mark cells with icons depending on their value + * Show a databar whose length indicates the value or a two or three color scale where the color indicates the relative value + * Change the color, font, or number format of cells which meet given criteria + Add-ConditionalFormatting allows these parameters to be set; for fine tuning of the rules, the -PassThru switch will return the rule so that you can modify things which are specific to that type of rule, example, the values which correspond to each icon in an Icon-Set. + + + + Add-ConditionalFormatting + + Address + + A block of cells to format - you can use a named range with -Address $ws.names[1] or $ws.cells["RangeName"] + + Object + + Object + + + None + + + RuleType + + A standard named-rule - Top / Bottom / Less than / Greater than / Contains etc. + + + AboveAverage + AboveOrEqualAverage + BelowAverage + BelowOrEqualAverage + AboveStdDev + BelowStdDev + Bottom + BottomPercent + Top + TopPercent + Last7Days + LastMonth + LastWeek + NextMonth + NextWeek + ThisMonth + ThisWeek + Today + Tomorrow + Yesterday + BeginsWith + Between + ContainsBlanks + ContainsErrors + ContainsText + DuplicateValues + EndsWith + Equal + Expression + GreaterThan + GreaterThanOrEqual + LessThan + LessThanOrEqual + NotBetween + NotContains + NotContainsBlanks + NotContainsErrors + NotContainsText + NotEqual + UniqueValues + ThreeColorScale + TwoColorScale + ThreeIconSet + FourIconSet + FiveIconSet + DataBar + + eExcelConditionalFormattingRuleType + + eExcelConditionalFormattingRuleType + + + None + + + ConditionValue + + A value for the condition (for example 2000 if the test is 'lessthan 2000'; Formulas should begin with "=" ) + + Object + + Object + + + None + + + ConditionValue2 + + A second value for the conditions like "Between X and Y" + + Object + + Object + + + None + + + WorkSheet + + The worksheet where the format is to be applied + + ExcelWorksheet + + ExcelWorksheet + + + None + + + ForegroundColor + + Text color for matching objects + + Object + + Object + + + None + + + Reverse + + Use the Icon-Set in reverse order, or reverse the orders of Two- & Three-Color Scales + + + SwitchParameter + + + False + + + BackgroundColor + + Background color for matching items + + Object + + Object + + + None + + + BackgroundPattern + + Background pattern for matching items + + + None + Solid + DarkGray + MediumGray + LightGray + Gray125 + Gray0625 + DarkVertical + DarkHorizontal + DarkDown + DarkUp + DarkGrid + DarkTrellis + LightVertical + LightHorizontal + LightDown + LightUp + LightGrid + LightTrellis + + ExcelFillStyle + + ExcelFillStyle + + + None + + + PatternColor + + Secondary color when a background pattern requires it + + Object + + Object + + + None + + + NumberFormat + + Sets the numeric format for matching items + + Object + + Object + + + None + + + Bold + + Put matching items in bold face + + + SwitchParameter + + + False + + + Italic + + Put matching items in italic + + + SwitchParameter + + + False + + + Underline + + Underline matching items + + + SwitchParameter + + + False + + + StrikeThru + + Strikethrough text of matching items + + + SwitchParameter + + + False + + + StopIfTrue + + Prevent the processing of subsequent rules + + + SwitchParameter + + + False + + + Priority + + Set the sequence for rule processing + + Int32 + + Int32 + + + 0 + + + PassThru + + If specified pass the rule back to the caller to allow additional customization. + + + SwitchParameter + + + False + + + + Add-ConditionalFormatting + + Address + + A block of cells to format - you can use a named range with -Address $ws.names[1] or $ws.cells["RangeName"] + + Object + + Object + + + None + + + WorkSheet + + The worksheet where the format is to be applied + + ExcelWorksheet + + ExcelWorksheet + + + None + + + DataBarColor + + Color for databar type charts + + Object + + Object + + + None + + + Priority + + Set the sequence for rule processing + + Int32 + + Int32 + + + 0 + + + PassThru + + If specified pass the rule back to the caller to allow additional customization. + + + SwitchParameter + + + False + + + + Add-ConditionalFormatting + + Address + + A block of cells to format - you can use a named range with -Address $ws.names[1] or $ws.cells["RangeName"] + + Object + + Object + + + None + + + WorkSheet + + The worksheet where the format is to be applied + + ExcelWorksheet + + ExcelWorksheet + + + None + + + ThreeIconsSet + + One of the three-icon set types (e.g. Traffic Lights) + + + Arrows + ArrowsGray + Flags + Signs + Symbols + Symbols2 + TrafficLights1 + TrafficLights2 + + eExcelconditionalFormatting3IconsSetType + + eExcelconditionalFormatting3IconsSetType + + + None + + + Reverse + + Use the Icon-Set in reverse order, or reverse the orders of Two- & Three-Color Scales + + + SwitchParameter + + + False + + + Priority + + Set the sequence for rule processing + + Int32 + + Int32 + + + 0 + + + PassThru + + If specified pass the rule back to the caller to allow additional customization. + + + SwitchParameter + + + False + + + + Add-ConditionalFormatting + + Address + + A block of cells to format - you can use a named range with -Address $ws.names[1] or $ws.cells["RangeName"] + + Object + + Object + + + None + + + WorkSheet + + The worksheet where the format is to be applied + + ExcelWorksheet + + ExcelWorksheet + + + None + + + FourIconsSet + + A four-icon set name + + + Arrows + ArrowsGray + Rating + RedToBlack + TrafficLights + + eExcelconditionalFormatting4IconsSetType + + eExcelconditionalFormatting4IconsSetType + + + None + + + Reverse + + Use the Icon-Set in reverse order, or reverse the orders of Two- & Three-Color Scales + + + SwitchParameter + + + False + + + Priority + + Set the sequence for rule processing + + Int32 + + Int32 + + + 0 + + + PassThru + + If specified pass the rule back to the caller to allow additional customization. + + + SwitchParameter + + + False + + + + Add-ConditionalFormatting + + Address + + A block of cells to format - you can use a named range with -Address $ws.names[1] or $ws.cells["RangeName"] + + Object + + Object + + + None + + + WorkSheet + + The worksheet where the format is to be applied + + ExcelWorksheet + + ExcelWorksheet + + + None + + + FiveIconsSet + + A five-icon set name + + + Arrows + ArrowsGray + Quarters + Rating + + eExcelconditionalFormatting5IconsSetType + + eExcelconditionalFormatting5IconsSetType + + + None + + + Reverse + + Use the Icon-Set in reverse order, or reverse the orders of Two- & Three-Color Scales + + + SwitchParameter + + + False + + + Priority + + Set the sequence for rule processing + + Int32 + + Int32 + + + 0 + + + PassThru + + If specified pass the rule back to the caller to allow additional customization. + + + SwitchParameter + + + False + + + + + + Address + + A block of cells to format - you can use a named range with -Address $ws.names[1] or $ws.cells["RangeName"] + + Object + + Object + + + None + + + WorkSheet + + The worksheet where the format is to be applied + + ExcelWorksheet + + ExcelWorksheet + + + None + + + RuleType + + A standard named-rule - Top / Bottom / Less than / Greater than / Contains etc. + + eExcelConditionalFormattingRuleType + + eExcelConditionalFormattingRuleType + + + None + + + ForegroundColor + + Text color for matching objects + + Object + + Object + + + None + + + DataBarColor + + Color for databar type charts + + Object + + Object + + + None + + + ThreeIconsSet + + One of the three-icon set types (e.g. Traffic Lights) + + eExcelconditionalFormatting3IconsSetType + + eExcelconditionalFormatting3IconsSetType + + + None + + + FourIconsSet + + A four-icon set name + + eExcelconditionalFormatting4IconsSetType + + eExcelconditionalFormatting4IconsSetType + + + None + + + FiveIconsSet + + A five-icon set name + + eExcelconditionalFormatting5IconsSetType + + eExcelconditionalFormatting5IconsSetType + + + None + + + Reverse + + Use the Icon-Set in reverse order, or reverse the orders of Two- & Three-Color Scales + + SwitchParameter + + SwitchParameter + + + False + + + ConditionValue + + A value for the condition (for example 2000 if the test is 'lessthan 2000'; Formulas should begin with "=" ) + + Object + + Object + + + None + + + ConditionValue2 + + A second value for the conditions like "Between X and Y" + + Object + + Object + + + None + + + BackgroundColor + + Background color for matching items + + Object + + Object + + + None + + + BackgroundPattern + + Background pattern for matching items + + ExcelFillStyle + + ExcelFillStyle + + + None + + + PatternColor + + Secondary color when a background pattern requires it + + Object + + Object + + + None + + + NumberFormat + + Sets the numeric format for matching items + + Object + + Object + + + None + + + Bold + + Put matching items in bold face + + SwitchParameter + + SwitchParameter + + + False + + + Italic + + Put matching items in italic + + SwitchParameter + + SwitchParameter + + + False + + + Underline + + Underline matching items + + SwitchParameter + + SwitchParameter + + + False + + + StrikeThru + + Strikethrough text of matching items + + SwitchParameter + + SwitchParameter + + + False + + + StopIfTrue + + Prevent the processing of subsequent rules + + SwitchParameter + + SwitchParameter + + + False + + + Priority + + Set the sequence for rule processing + + Int32 + + Int32 + + + 0 + + + PassThru + + If specified pass the rule back to the caller to allow additional customization. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> $excel = $avdata | Export-Excel -Path (Join-path $FilePath "\Machines.XLSX" ) -WorksheetName "Server Anti-Virus" -AutoSize -FreezeTopRow -AutoFilter -PassThru + Add-ConditionalFormatting -WorkSheet $excel.Workbook.Worksheets[1] -Address "b2:b1048576" -ForeGroundColor "RED" -RuleType ContainsText -ConditionValue "2003" + Add-ConditionalFormatting -WorkSheet $excel.Workbook.Worksheets[1] -Address "i2:i1048576" -ForeGroundColor "RED" -RuleType ContainsText -ConditionValue "Disabled" + $excel.Workbook.Worksheets[1].Cells["D1:G1048576"].Style.Numberformat.Format = [cultureinfo]::CurrentCulture.DateTimeFormat.ShortDatePattern + $excel.Workbook.Worksheets[1].Row(1).style.font.bold = $true + $excel.Save() ; $excel.Dispose() + + Here Export-Excel is called with the -PassThru parameter, so the ExcelPackage object representing Machines.XLSX is stored in $Excel.The desired worksheet is selected, and then columns" B" and "I" are conditionally formatted (excluding the top row) to show red text if they contain "2003" or "Disabled" respectively. + A fixed date format is then applied to columns D to G, and the top row is formatted. + Finally the workbook is saved and the Excel package object is closed. + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\> $r = Add-ConditionalFormatting -WorkSheet $excel.Workbook.Worksheets[1] -Range "B1:B100" -ThreeIconsSet Flags -Passthru + $r.Reverse = $true ; $r.Icon1.Type = "Num"; $r.Icon2.Type = "Num" ; $r.Icon2.value = 100 ; $r.Icon3.type = "Num" ;$r.Icon3.value = 1000 + + Again Export-Excel has been called with -PassThru leaving a package object in $Excel. + This time B1:B100 has been conditionally formatted with 3 icons, using the "Flags" Icon-Set. + Add-ConditionalFormatting does not provide accessto every option in the formatting rule, so -PassThru has been used and the rule is modified to apply the flags in reverse order, and transitions between flags are set to 100 and 1000. + + + + -------------------------- EXAMPLE 3 -------------------------- + PS\> Add-ConditionalFormatting -WorkSheet $sheet -Range "D2:D1048576" -DataBarColor Red + + This time $sheet holds an ExcelWorkshseet object and databars are added to column D, excluding the top row. + + + + -------------------------- EXAMPLE 4 -------------------------- + PS\> Add-ConditionalFormatting -Address $worksheet.cells["FinishPosition"] -RuleType Equal -ConditionValue 1 -ForeGroundColor Purple -Bold -Priority 1 -StopIfTrue + + In this example a named range is used to select the cells where the condition should apply, and instead of specifying a sheet and range within the sheet as separate parameters, the cells where the format should apply are specified directly. + If a cell in the "FinishPosition" range is 1, then the text is turned to Bold & Purple. + This rule is moved to first in the priority list, and where cells have a value of 1, no other rules will be processed. + + + + -------------------------- EXAMPLE 5 -------------------------- + PS\> $excel = Get-ChildItem | Select-Object -Property Name,Length,LastWriteTime,CreationTime | Export-Excel "$env:temp\test43.xlsx" -PassThru -AutoSize + $ws = $excel.Workbook.Worksheets["Sheet1"] + $ws.Cells["E1"].Value = "SavedAt" + $ws.Cells["F1"].Value = [datetime]::Now + $ws.Cells["F1"].Style.Numberformat.Format = (Expand-NumberFormat -NumberFormat 'Date-Time') + $lastRow = $ws.Dimension.End.Row + Add-ConditionalFormatting -WorkSheet $ws -address "A2:A$Lastrow" -RuleType LessThan -ConditionValue "A" -ForeGroundColor Gray + Add-ConditionalFormatting -WorkSheet $ws -address "B2:B$Lastrow" -RuleType GreaterThan -ConditionValue 1000000 -NumberFormat '#,###,,.00"M"' + Add-ConditionalFormatting -WorkSheet $ws -address "C2:C$Lastrow" -RuleType GreaterThan -ConditionValue "=INT($F$1-7)" -ForeGroundColor Green -StopIfTrue + Add-ConditionalFormatting -WorkSheet $ws -address "D2:D$Lastrow" -RuleType Equal -ConditionValue "=C2" -ForeGroundColor Blue -StopIfTrue + Close-ExcelPackage -Show $excel + + The first few lines of code export a list of file and directory names, sizes and dates to a spreadsheet. + It puts the date of the export in cell F1. + The first Conditional format changes the color of files and folders that begin with a ".", "_" or anything else which sorts before "A". + The second Conditional format changes the Number format of numbers bigger than 1 million, for example 1,234,567,890 will dispay as "1,234.57M" + The third highlights datestamps of files less than a week old when the export was run; the = is necessary in the condition value otherwise the rule will look for the the text INT($F$1-7), and the cell address for the date is fixed using the standard Excel $ notation. + The final Conditional format looks for files which have not changed since they were created. Here the condition value is "=C2". The = sign means C2 is treated as a formula, not literal text. Unlike the file age, we want the cell used to change for each cell where the conditional format applies. + The first cell in the conditional format range is D2, which is compared against C2, then D3 is compared against C3 and so on. A common mistake is to include the title row in the range and accidentally apply conditional formatting to it, or to begin the range at row 2 but use row 1 as the starting point for comparisons. + + + + -------------------------- EXAMPLE 6 -------------------------- + PS\> Add-ConditionalFormatting $ws.Cells["B:B"] GreaterThan 10000000 -Fore Red -Stop -Pri 1 + + This version shows the shortest syntax - the Address, Ruletype, and Conditionvalue can be identified from their position, and ForegroundColor, StopIfTrue and Priority can all be shortend. + + + + + + + + Add-ExcelChart + Add + ExcelChart + + Creates a chart in an existing Excel worksheet. + + + + Creates a chart. + It is possible to configure the type of chart, the range of X values (labels) and Y values, the title, the legend, the ranges for both axes, the format and position of the axes. + Normally the command does not return anything, but if -passthru is specified the chart is returned so that it can be customized. + + + + Add-ExcelChart + + Worksheet + + An existing Sheet where the chart will be created. + + ExcelWorksheet + + ExcelWorksheet + + + None + + + Title + + The title for the chart. + + String + + String + + + None + + + ChartType + + One of the built-in chart types, such as Pie, ClusteredColumn, Line etc. Defaults to "ColumnStacked". + + + Area + Line + Pie + Bubble + ColumnClustered + ColumnStacked + ColumnStacked100 + ColumnClustered3D + ColumnStacked3D + ColumnStacked1003D + BarClustered + BarStacked + BarStacked100 + BarClustered3D + BarStacked3D + BarStacked1003D + LineStacked + LineStacked100 + LineMarkers + LineMarkersStacked + LineMarkersStacked100 + PieOfPie + PieExploded + PieExploded3D + BarOfPie + XYScatterSmooth + XYScatterSmoothNoMarkers + XYScatterLines + XYScatterLinesNoMarkers + AreaStacked + AreaStacked100 + AreaStacked3D + AreaStacked1003D + DoughnutExploded + RadarMarkers + RadarFilled + Surface + SurfaceWireframe + SurfaceTopView + SurfaceTopViewWireframe + Bubble3DEffect + StockHLC + StockOHLC + StockVHLC + StockVOHLC + CylinderColClustered + CylinderColStacked + CylinderColStacked100 + CylinderBarClustered + CylinderBarStacked + CylinderBarStacked100 + CylinderCol + ConeColClustered + ConeColStacked + ConeColStacked100 + ConeBarClustered + ConeBarStacked + ConeBarStacked100 + ConeCol + PyramidColClustered + PyramidColStacked + PyramidColStacked100 + PyramidBarClustered + PyramidBarStacked + PyramidBarStacked100 + PyramidCol + XYScatter + Radar + Doughnut + Pie3D + Line3D + Column3D + Area3D + + eChartType + + eChartType + + + ColumnStacked + + + ChartTrendLine + + {{ Fill ChartTrendLine Description }} + + + Exponential + Linear + Logarithmic + MovingAvgerage + Polynomial + Power + + eTrendLine[] + + eTrendLine[] + + + None + + + XRange + + The range of cells containing values for the X-Axis - usually labels. + + Object + + Object + + + None + + + YRange + + The range(s) of cells holding values for the Y-Axis - usually "data". + + Object + + Object + + + None + + + Width + + Width of the chart in Pixels; defaults to 500. + + Int32 + + Int32 + + + 500 + + + Height + + Height of the chart in Pixels; defaults to 350. + + Int32 + + Int32 + + + 350 + + + Row + + Row position of the top left corner of the chart. ) places at the top of the sheet, 1 below row 1 and so on. + + Int32 + + Int32 + + + 0 + + + RowOffSetPixels + + Offset to position the chart by a fraction of a row. + + Int32 + + Int32 + + + 10 + + + Column + + Column position of the top left corner of the chart; 0 places at the edge of the sheet 1 to the right of column A and so on. + + Int32 + + Int32 + + + 6 + + + ColumnOffSetPixels + + Offset to position the chart by a fraction of a column. + + Int32 + + Int32 + + + 5 + + + LegendPosition + + Location of the key, either left, right, top, bottom or TopRight. + + + Top + Left + Right + Bottom + TopRight + + eLegendPosition + + eLegendPosition + + + None + + + LegendSize + + Font size for the key. + + Object + + Object + + + None + + + LegendBold + + Sets the key in bold type. + + + SwitchParameter + + + False + + + NoLegend + + If specified, turns of display of the key. If you only have one data series it may be preferable to use the title to say what the chart is. + + + SwitchParameter + + + False + + + ShowCategory + + Attaches a category label, in charts which support this. + + + SwitchParameter + + + False + + + ShowPercent + + Attaches a percentage label, in charts which support this. + + + SwitchParameter + + + False + + + SeriesHeader + + Specify explicit name(s) for the data series, which will appear in the legend/key. The contents of a cell can be specified in the from =Sheet9!Z10 . + + String[] + + String[] + + + None + + + TitleBold + + Sets the title in bold face. + + + SwitchParameter + + + False + + + TitleSize + + Sets the point size for the title. + + Int32 + + Int32 + + + 0 + + + XAxisTitleText + + Specifies a title for the X-axis. + + String + + String + + + None + + + XAxisTitleBold + + Sets the X-axis title in bold face. + + + SwitchParameter + + + False + + + XAxisTitleSize + + Sets the font size for the axis title. + + Object + + Object + + + None + + + XAxisNumberformat + + A number formatting string, like "#,##0.00", for numbers along the X-axis. + + String + + String + + + None + + + XMajorUnit + + Spacing for the major gridlines / tick marks along the X-axis. + + Object + + Object + + + None + + + XMinorUnit + + Spacing for the minor gridlines / tick marks along the X-axis. + + Object + + Object + + + None + + + XMaxValue + + Maximum value for the scale along the X-axis. + + Object + + Object + + + None + + + XMinValue + + Minimum value for the scale along the X-axis. + + Object + + Object + + + None + + + XAxisPosition + + Position for the X-axis (Top or Bottom). + + + Left + Bottom + Right + Top + + eAxisPosition + + eAxisPosition + + + None + + + YAxisTitleText + + Specifies a title for the Y-axis. + + String + + String + + + None + + + YAxisTitleBold + + Sets the Y-axis title in bold face. + + + SwitchParameter + + + False + + + YAxisTitleSize + + Sets the font size for the Y-axis title + + Object + + Object + + + None + + + YAxisNumberformat + + A number formatting string, like "#,##0.00", for numbers on the Y-axis. + + String + + String + + + None + + + YMajorUnit + + Spacing for the major gridlines / tick marks on the Y-axis. + + Object + + Object + + + None + + + YMinorUnit + + Spacing for the minor gridlines / tick marks on the Y-axis. + + Object + + Object + + + None + + + YMaxValue + + Maximum value on the Y-axis. + + Object + + Object + + + None + + + YMinValue + + Minimum value on the Y-axis. + + Object + + Object + + + None + + + YAxisPosition + + Position for the Y-axis (Left or Right). + + + Left + Bottom + Right + Top + + eAxisPosition + + eAxisPosition + + + None + + + PassThru + + Add-Excel chart doesn't normally return anything, but if -PassThru is specified it returns the newly created chart to allow it to be fine tuned. + + + SwitchParameter + + + False + + + + Add-ExcelChart + + PivotTable + + Instead of specify X and Y ranges, get data from a PivotTable by passing a PivotTable Object. + + ExcelPivotTable + + ExcelPivotTable + + + None + + + Title + + The title for the chart. + + String + + String + + + None + + + ChartType + + One of the built-in chart types, such as Pie, ClusteredColumn, Line etc. Defaults to "ColumnStacked". + + + Area + Line + Pie + Bubble + ColumnClustered + ColumnStacked + ColumnStacked100 + ColumnClustered3D + ColumnStacked3D + ColumnStacked1003D + BarClustered + BarStacked + BarStacked100 + BarClustered3D + BarStacked3D + BarStacked1003D + LineStacked + LineStacked100 + LineMarkers + LineMarkersStacked + LineMarkersStacked100 + PieOfPie + PieExploded + PieExploded3D + BarOfPie + XYScatterSmooth + XYScatterSmoothNoMarkers + XYScatterLines + XYScatterLinesNoMarkers + AreaStacked + AreaStacked100 + AreaStacked3D + AreaStacked1003D + DoughnutExploded + RadarMarkers + RadarFilled + Surface + SurfaceWireframe + SurfaceTopView + SurfaceTopViewWireframe + Bubble3DEffect + StockHLC + StockOHLC + StockVHLC + StockVOHLC + CylinderColClustered + CylinderColStacked + CylinderColStacked100 + CylinderBarClustered + CylinderBarStacked + CylinderBarStacked100 + CylinderCol + ConeColClustered + ConeColStacked + ConeColStacked100 + ConeBarClustered + ConeBarStacked + ConeBarStacked100 + ConeCol + PyramidColClustered + PyramidColStacked + PyramidColStacked100 + PyramidBarClustered + PyramidBarStacked + PyramidBarStacked100 + PyramidCol + XYScatter + Radar + Doughnut + Pie3D + Line3D + Column3D + Area3D + + eChartType + + eChartType + + + ColumnStacked + + + ChartTrendLine + + {{ Fill ChartTrendLine Description }} + + + Exponential + Linear + Logarithmic + MovingAvgerage + Polynomial + Power + + eTrendLine[] + + eTrendLine[] + + + None + + + XRange + + The range of cells containing values for the X-Axis - usually labels. + + Object + + Object + + + None + + + YRange + + The range(s) of cells holding values for the Y-Axis - usually "data". + + Object + + Object + + + None + + + Width + + Width of the chart in Pixels; defaults to 500. + + Int32 + + Int32 + + + 500 + + + Height + + Height of the chart in Pixels; defaults to 350. + + Int32 + + Int32 + + + 350 + + + Row + + Row position of the top left corner of the chart. ) places at the top of the sheet, 1 below row 1 and so on. + + Int32 + + Int32 + + + 0 + + + RowOffSetPixels + + Offset to position the chart by a fraction of a row. + + Int32 + + Int32 + + + 10 + + + Column + + Column position of the top left corner of the chart; 0 places at the edge of the sheet 1 to the right of column A and so on. + + Int32 + + Int32 + + + 6 + + + ColumnOffSetPixels + + Offset to position the chart by a fraction of a column. + + Int32 + + Int32 + + + 5 + + + LegendPosition + + Location of the key, either left, right, top, bottom or TopRight. + + + Top + Left + Right + Bottom + TopRight + + eLegendPosition + + eLegendPosition + + + None + + + LegendSize + + Font size for the key. + + Object + + Object + + + None + + + LegendBold + + Sets the key in bold type. + + + SwitchParameter + + + False + + + NoLegend + + If specified, turns of display of the key. If you only have one data series it may be preferable to use the title to say what the chart is. + + + SwitchParameter + + + False + + + ShowCategory + + Attaches a category label, in charts which support this. + + + SwitchParameter + + + False + + + ShowPercent + + Attaches a percentage label, in charts which support this. + + + SwitchParameter + + + False + + + SeriesHeader + + Specify explicit name(s) for the data series, which will appear in the legend/key. The contents of a cell can be specified in the from =Sheet9!Z10 . + + String[] + + String[] + + + None + + + TitleBold + + Sets the title in bold face. + + + SwitchParameter + + + False + + + TitleSize + + Sets the point size for the title. + + Int32 + + Int32 + + + 0 + + + XAxisTitleText + + Specifies a title for the X-axis. + + String + + String + + + None + + + XAxisTitleBold + + Sets the X-axis title in bold face. + + + SwitchParameter + + + False + + + XAxisTitleSize + + Sets the font size for the axis title. + + Object + + Object + + + None + + + XAxisNumberformat + + A number formatting string, like "#,##0.00", for numbers along the X-axis. + + String + + String + + + None + + + XMajorUnit + + Spacing for the major gridlines / tick marks along the X-axis. + + Object + + Object + + + None + + + XMinorUnit + + Spacing for the minor gridlines / tick marks along the X-axis. + + Object + + Object + + + None + + + XMaxValue + + Maximum value for the scale along the X-axis. + + Object + + Object + + + None + + + XMinValue + + Minimum value for the scale along the X-axis. + + Object + + Object + + + None + + + XAxisPosition + + Position for the X-axis (Top or Bottom). + + + Left + Bottom + Right + Top + + eAxisPosition + + eAxisPosition + + + None + + + YAxisTitleText + + Specifies a title for the Y-axis. + + String + + String + + + None + + + YAxisTitleBold + + Sets the Y-axis title in bold face. + + + SwitchParameter + + + False + + + YAxisTitleSize + + Sets the font size for the Y-axis title + + Object + + Object + + + None + + + YAxisNumberformat + + A number formatting string, like "#,##0.00", for numbers on the Y-axis. + + String + + String + + + None + + + YMajorUnit + + Spacing for the major gridlines / tick marks on the Y-axis. + + Object + + Object + + + None + + + YMinorUnit + + Spacing for the minor gridlines / tick marks on the Y-axis. + + Object + + Object + + + None + + + YMaxValue + + Maximum value on the Y-axis. + + Object + + Object + + + None + + + YMinValue + + Minimum value on the Y-axis. + + Object + + Object + + + None + + + YAxisPosition + + Position for the Y-axis (Left or Right). + + + Left + Bottom + Right + Top + + eAxisPosition + + eAxisPosition + + + None + + + PassThru + + Add-Excel chart doesn't normally return anything, but if -PassThru is specified it returns the newly created chart to allow it to be fine tuned. + + + SwitchParameter + + + False + + + + + + Worksheet + + An existing Sheet where the chart will be created. + + ExcelWorksheet + + ExcelWorksheet + + + None + + + PivotTable + + Instead of specify X and Y ranges, get data from a PivotTable by passing a PivotTable Object. + + ExcelPivotTable + + ExcelPivotTable + + + None + + + Title + + The title for the chart. + + String + + String + + + None + + + ChartType + + One of the built-in chart types, such as Pie, ClusteredColumn, Line etc. Defaults to "ColumnStacked". + + eChartType + + eChartType + + + ColumnStacked + + + ChartTrendLine + + {{ Fill ChartTrendLine Description }} + + eTrendLine[] + + eTrendLine[] + + + None + + + XRange + + The range of cells containing values for the X-Axis - usually labels. + + Object + + Object + + + None + + + YRange + + The range(s) of cells holding values for the Y-Axis - usually "data". + + Object + + Object + + + None + + + Width + + Width of the chart in Pixels; defaults to 500. + + Int32 + + Int32 + + + 500 + + + Height + + Height of the chart in Pixels; defaults to 350. + + Int32 + + Int32 + + + 350 + + + Row + + Row position of the top left corner of the chart. ) places at the top of the sheet, 1 below row 1 and so on. + + Int32 + + Int32 + + + 0 + + + RowOffSetPixels + + Offset to position the chart by a fraction of a row. + + Int32 + + Int32 + + + 10 + + + Column + + Column position of the top left corner of the chart; 0 places at the edge of the sheet 1 to the right of column A and so on. + + Int32 + + Int32 + + + 6 + + + ColumnOffSetPixels + + Offset to position the chart by a fraction of a column. + + Int32 + + Int32 + + + 5 + + + LegendPosition + + Location of the key, either left, right, top, bottom or TopRight. + + eLegendPosition + + eLegendPosition + + + None + + + LegendSize + + Font size for the key. + + Object + + Object + + + None + + + LegendBold + + Sets the key in bold type. + + SwitchParameter + + SwitchParameter + + + False + + + NoLegend + + If specified, turns of display of the key. If you only have one data series it may be preferable to use the title to say what the chart is. + + SwitchParameter + + SwitchParameter + + + False + + + ShowCategory + + Attaches a category label, in charts which support this. + + SwitchParameter + + SwitchParameter + + + False + + + ShowPercent + + Attaches a percentage label, in charts which support this. + + SwitchParameter + + SwitchParameter + + + False + + + SeriesHeader + + Specify explicit name(s) for the data series, which will appear in the legend/key. The contents of a cell can be specified in the from =Sheet9!Z10 . + + String[] + + String[] + + + None + + + TitleBold + + Sets the title in bold face. + + SwitchParameter + + SwitchParameter + + + False + + + TitleSize + + Sets the point size for the title. + + Int32 + + Int32 + + + 0 + + + XAxisTitleText + + Specifies a title for the X-axis. + + String + + String + + + None + + + XAxisTitleBold + + Sets the X-axis title in bold face. + + SwitchParameter + + SwitchParameter + + + False + + + XAxisTitleSize + + Sets the font size for the axis title. + + Object + + Object + + + None + + + XAxisNumberformat + + A number formatting string, like "#,##0.00", for numbers along the X-axis. + + String + + String + + + None + + + XMajorUnit + + Spacing for the major gridlines / tick marks along the X-axis. + + Object + + Object + + + None + + + XMinorUnit + + Spacing for the minor gridlines / tick marks along the X-axis. + + Object + + Object + + + None + + + XMaxValue + + Maximum value for the scale along the X-axis. + + Object + + Object + + + None + + + XMinValue + + Minimum value for the scale along the X-axis. + + Object + + Object + + + None + + + XAxisPosition + + Position for the X-axis (Top or Bottom). + + eAxisPosition + + eAxisPosition + + + None + + + YAxisTitleText + + Specifies a title for the Y-axis. + + String + + String + + + None + + + YAxisTitleBold + + Sets the Y-axis title in bold face. + + SwitchParameter + + SwitchParameter + + + False + + + YAxisTitleSize + + Sets the font size for the Y-axis title + + Object + + Object + + + None + + + YAxisNumberformat + + A number formatting string, like "#,##0.00", for numbers on the Y-axis. + + String + + String + + + None + + + YMajorUnit + + Spacing for the major gridlines / tick marks on the Y-axis. + + Object + + Object + + + None + + + YMinorUnit + + Spacing for the minor gridlines / tick marks on the Y-axis. + + Object + + Object + + + None + + + YMaxValue + + Maximum value on the Y-axis. + + Object + + Object + + + None + + + YMinValue + + Minimum value on the Y-axis. + + Object + + Object + + + None + + + YAxisPosition + + Position for the Y-axis (Left or Right). + + eAxisPosition + + eAxisPosition + + + None + + + PassThru + + Add-Excel chart doesn't normally return anything, but if -PassThru is specified it returns the newly created chart to allow it to be fine tuned. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + OfficeOpenXml.Drawing.Chart.ExcelChart + + + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> $Excel = ConvertFrom-Csv @" + Product, City, Sales + Apple, London, 300 + Orange, London, 400 + Banana, London, 300 + Orange, Paris, 600 + Banana, Paris, 300 + Apple, New York, 1200 +"@ | Export-Excel -Path test.xlsx -PassThru + Add-ExcelChart -Worksheet $Excel.Workbook.Worksheets[1] -ChartType "Doughnut" -XRange "A2:B7" -YRange "C2:C7" -width 500 + Close-ExcelPackage -Show $Excel + + The first command expands a multi-line string into 6 rows of data which is exported to new Excel file; leaving an ExcelPackage object in $excel The second command adds a chart - the cell ranges are explicitly specified. + Note that the XRange (labels) is TWO columns wide and the chart will combine the name of the product and the name of the City to create the label. + The width of the chart is set explictly, the default legend is used and there is no Chart title. + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\> $Excel = Invoke-Sum (Get-Process) Company Handles, PM, VirtualMemorySize | Export-Excel $path -AutoSize -ExcelChartDefinition $c -AutoNameRange -PassThru + Add-ExcelChart -Worksheet $Excel.Workbook.Worksheets[1] -Title "VM use" -ChartType PieExploded3D -XRange "Name" -YRange "VirtualMemorySize" -NoLegend -ShowCategory + Close-ExcelPackage $Excel -Show + + The first line exports information and creates named ranges for each column. + The Second line uses the ranges to specify a chart - the labels come from the range "Name" and the data from the range "VirtualMemorySize" + The chart is specified as a 3D exploded PIE chart, with a title of "VM Use" and instead of a legend the the pie slices are identified with a label. + + + + -------------------------- EXAMPLE 3 -------------------------- + PS\> $Excel = Invoke-Sum (Get-Process) Company Handles, PM, VirtualMemorySize | Export-Excel test.xlsx -TableName Processes -PassThru + Add-ExcelChart -Worksheet $Excel.Workbook.Worksheets[1] -Title Stats -ChartType LineMarkersStacked -XRange "Processes[Name]" -YRange "Processes[PM]", "Processes[VirtualMemorySize]" -SeriesHeader 'PM', 'VMSize' + Close-ExcelPackage $Excel -Show + + The first line exports information to a table in new file; and captures the excel Package object in $Excel + The second line creates a chart on the first page of the work sheet, using the notation "TableName[ColumnnName]" to refer to the data, the labels come Name column in the table, and the data series from its PM and VirtualMemorySize columns. The display names for these in the header are set to 'PM' and 'VMSize'. + + + + -------------------------- EXAMPLE 4 -------------------------- + PS\> $excel = 0..360 | ForEach-Object {[pscustomobject][ordered]@{x = $_; Sinx = "=Sin(Radians(x)) "}} | Export-Excel -AutoNameRange -Path Text.xlsx -WorkSheetname SinX -PassThru +Add-ExcelChart -Worksheet $excel.Workbook.Worksheets["Sinx"] -ChartType line -XRange "X" -YRange "Sinx" -Title "Graph of Sine X" -TitleBold -TitleSize 14 \` + -Column 2 -ColumnOffSetPixels 35 -Width 800 -XAxisTitleText "Degrees" -XAxisTitleBold -XAxisTitleSize 12 -XMajorUnit 30 -XMinorUnit 10 -XMinValue 0 -XMaxValue 361 -XAxisNumberformat "000" \` + -YMinValue -1.25 -YMaxValue 1.25 -YMajorUnit 0.25 -YAxisNumberformat "0.00" -YAxisTitleText "Sine" -YAxisTitleBold -YAxisTitleSize 12 \` + -SeriesHeader "Sin(x)" -LegendSize 8 -legendBold -LegendPosition Bottom +Close-ExcelPackage $Excel -Show + + The first line puts numbers from 0 to 360 into a sheet, as the first column, and a formula to calculate the Sine of that number of number of degrees in the second column. It creates named-ranges for the two columns - "X" and "SinX" respectively + The Add-ExcelChart command adds a chart to that worksheet, specifying a line chart with the X values coming from named-range "X" and the Y values coming from named-range "SinX". The chart has a title, and is positioned to the right of column 2 and sized 800 pixels wide + The X-axis is labelled "Degrees", in bold 12 point type and runs from 0 to 361 with labels every 30, and minor tick marks every 10. Degrees are shown padded to 3 digits. + The Y-axis is labelled "Sine" and to allow some room above and below its scale runs from -1.25 to 1.25, and is marked off in units of 0.25 shown to two decimal places. + The key will for the chart will be at the bottom in 8 point bold type and the line will be named "Sin(x)". + + + + + + + + Add-ExcelDataValidationRule + Add + ExcelDataValidationRule + + Adds data validation to a range of cells + + + + Excel supports the validation of user input, and ranges of cells can be marked to only contain numbers, or date, or Text up to a particular length, or selections from a list. This command adds validation rules to a worksheet. + + + + Add-ExcelDataValidationRule + + Range + + The range of cells to be validate, for example, "B2:C100" + + Object + + Object + + + None + + + WorkSheet + + The worksheet where the cells should be validated + + ExcelWorksheet + + ExcelWorksheet + + + None + + + ValidationType + + An option corresponding to a choice from the 'Allow' pull down on the settings page in the Excel dialog. "Any" means "any allowed" - in other words, no Validation + + Object + + Object + + + None + + + Operator + + The operator to apply to Decimal, Integer, TextLength, DateTime and time fields, for example "equal" or "between" + + + between + notBetween + equal + notEqual + lessThan + lessThanOrEqual + greaterThan + greaterThanOrEqual + + ExcelDataValidationOperator + + ExcelDataValidationOperator + + + Equal + + + Value + + For Decimal, Integer, TextLength, DateTime the [first] data value + + Object + + Object + + + None + + + Value2 + + When using the between operator, the second data value + + Object + + Object + + + None + + + Formula + + The [first] data value as a formula. Use absolute formulas $A$1 if (e.g.) you want all cells to check against the same list + + Object + + Object + + + None + + + Formula2 + + When using the between operator, the second data value as a formula + + Object + + Object + + + None + + + ValueSet + + When using the list validation type, a set of values (rather than refering to Sheet!B$2:B$100 ) + + Object + + Object + + + None + + + ShowErrorMessage + + Corresponds to the the 'Show Error alert ...' check box on error alert page in the Excel dialog + + + SwitchParameter + + + False + + + ErrorStyle + + Stop, Warning, or Infomation, corresponding to to the style setting in the Excel dialog + + + undefined + stop + warning + information + + ExcelDataValidationWarningStyle + + ExcelDataValidationWarningStyle + + + None + + + ErrorTitle + + The title for the message box corresponding to to the title setting in the Excel dialog + + String + + String + + + None + + + ErrorBody + + The error message corresponding to to the Error message setting in the Excel dialog + + String + + String + + + None + + + ShowPromptMessage + + Corresponds to the the 'Show Input message ...' check box on input message page in the Excel dialog + + + SwitchParameter + + + False + + + PromptBody + + The prompt message corresponding to to the Input message setting in the Excel dialog + + String + + String + + + None + + + PromptTitle + + The title for the message box corresponding to to the title setting in the Excel dialog + + String + + String + + + None + + + NoBlank + + By default the 'Ignore blank' option will be selected, unless NoBlank is sepcified. + + String + + String + + + None + + + + + + Range + + The range of cells to be validate, for example, "B2:C100" + + Object + + Object + + + None + + + WorkSheet + + The worksheet where the cells should be validated + + ExcelWorksheet + + ExcelWorksheet + + + None + + + ValidationType + + An option corresponding to a choice from the 'Allow' pull down on the settings page in the Excel dialog. "Any" means "any allowed" - in other words, no Validation + + Object + + Object + + + None + + + Operator + + The operator to apply to Decimal, Integer, TextLength, DateTime and time fields, for example "equal" or "between" + + ExcelDataValidationOperator + + ExcelDataValidationOperator + + + Equal + + + Value + + For Decimal, Integer, TextLength, DateTime the [first] data value + + Object + + Object + + + None + + + Value2 + + When using the between operator, the second data value + + Object + + Object + + + None + + + Formula + + The [first] data value as a formula. Use absolute formulas $A$1 if (e.g.) you want all cells to check against the same list + + Object + + Object + + + None + + + Formula2 + + When using the between operator, the second data value as a formula + + Object + + Object + + + None + + + ValueSet + + When using the list validation type, a set of values (rather than refering to Sheet!B$2:B$100 ) + + Object + + Object + + + None + + + ShowErrorMessage + + Corresponds to the the 'Show Error alert ...' check box on error alert page in the Excel dialog + + SwitchParameter + + SwitchParameter + + + False + + + ErrorStyle + + Stop, Warning, or Infomation, corresponding to to the style setting in the Excel dialog + + ExcelDataValidationWarningStyle + + ExcelDataValidationWarningStyle + + + None + + + ErrorTitle + + The title for the message box corresponding to to the title setting in the Excel dialog + + String + + String + + + None + + + ErrorBody + + The error message corresponding to to the Error message setting in the Excel dialog + + String + + String + + + None + + + ShowPromptMessage + + Corresponds to the the 'Show Input message ...' check box on input message page in the Excel dialog + + SwitchParameter + + SwitchParameter + + + False + + + PromptBody + + The prompt message corresponding to to the Input message setting in the Excel dialog + + String + + String + + + None + + + PromptTitle + + The title for the message box corresponding to to the title setting in the Excel dialog + + String + + String + + + None + + + NoBlank + + By default the 'Ignore blank' option will be selected, unless NoBlank is sepcified. + + String + + String + + + None + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\>Add-ExcelDataValidationRule -WorkSheet $PlanSheet -Range 'E2:E1001' -ValidationType Integer -Operator between -Value 0 -Value2 100 \` + -ShowErrorMessage -ErrorStyle stop -ErrorTitle 'Invalid Data' -ErrorBody 'Percentage must be a whole number between 0 and 100' + + This defines a validation rule on cells E2-E1001; it is an integer rule and requires a number between 0 and 100. If a value is input with a fraction, negative number, or positive number > 100 a stop dialog box appears. + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\>Add-ExcelDataValidationRule -WorkSheet $PlanSheet -Range 'B2:B1001' -ValidationType List -Formula 'values!$a$2:$a$1000' + -ShowErrorMessage -ErrorStyle stop -ErrorTitle 'Invalid Data' -ErrorBody 'You must select an item from the list' + + This defines a list rule on Cells B2:1001, and the posible values are in a sheet named "values" at cells A2 to A1000 Blank cells in this range are ignored. + If $ signs were left out of the fomrmula B2 would be checked against A2-A1000, B3, against A3-A1001, B4 against A4-A1002 up to B1001 beng checked against A1001-A1999 + + + + -------------------------- EXAMPLE 3 -------------------------- + PS\>Add-ExcelDataValidationRule -WorkSheet $PlanSheet -Range 'I2:N1001' -ValidationType List -ValueSet @('yes','YES','Yes') + -ShowErrorMessage -ErrorStyle stop -ErrorTitle 'Invalid Data' -ErrorBody "Select Yes or leave blank for no" + + Similar to the previous example but this time provides a value set; Excel comparisons are case sesnsitive, hence 3 versions of Yes. + + + + + + + + Add-ExcelName + Add + ExcelName + + Adds a named-range to an existing Excel worksheet. + + + + It is often helpful to be able to refer to sets of cells with a name rather than using their co-ordinates; Add-ExcelName sets up these names. + + + + Add-ExcelName + + Range + + The range of cells to assign as a name. + + ExcelRange + + ExcelRange + + + None + + + RangeName + + The name to assign to the range. If the name exists it will be updated to the new range. If no name is specified, the first cell in the range will be used as the name. + + String + + String + + + None + + + + + + Range + + The range of cells to assign as a name. + + ExcelRange + + ExcelRange + + + None + + + RangeName + + The name to assign to the range. If the name exists it will be updated to the new range. If no name is specified, the first cell in the range will be used as the name. + + String + + String + + + None + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> Add-ExcelName -Range $ws.Cells[$dataRange] -RangeName $rangeName + + $WS is a worksheet, and $dataRange is a string describing a range of cells - for example "A1:Z10" - which will become a named range, using the name in $rangeName. + + + + + + + + Add-ExcelTable + Add + ExcelTable + + Adds Tables to Excel workbooks. + + + + Unlike named ranges, where the name only needs to be unique within a sheet, Table names must be unique in the workbook. + Tables carry formatting and by default have a filter. + The filter, header, totals, first and last column highlights can all be configured. + + + + Add-ExcelTable + + Range + + The range of cells to assign to a table. + + ExcelRange + + ExcelRange + + + None + + + TableName + + The name for the Table - this should be unqiue in the Workbook - auto generated names will be used if this is left empty. + + String + + String + + + None + + + TableStyle + + The Style for the table, by default "Medium6" is used + + + None + Custom + Light1 + Light2 + Light3 + Light4 + Light5 + Light6 + Light7 + Light8 + Light9 + Light10 + Light11 + Light12 + Light13 + Light14 + Light15 + Light16 + Light17 + Light18 + Light19 + Light20 + Light21 + Medium1 + Medium2 + Medium3 + Medium4 + Medium5 + Medium6 + Medium7 + Medium8 + Medium9 + Medium10 + Medium11 + Medium12 + Medium13 + Medium14 + Medium15 + Medium16 + Medium17 + Medium18 + Medium19 + Medium20 + Medium21 + Medium22 + Medium23 + Medium24 + Medium25 + Medium26 + Medium27 + Medium28 + Dark1 + Dark2 + Dark3 + Dark4 + Dark5 + Dark6 + Dark7 + Dark8 + Dark9 + Dark10 + Dark11 + + TableStyles + + TableStyles + + + Medium6 + + + TotalSettings + + A HashTable in the form ColumnName = "Average"|"Count"|"CountNums"|"Max"|"Min"|"None"|"StdDev"|"Sum"|"Var" - if specified, -ShowTotal is not needed. + + Hashtable + + Hashtable + + + None + + + ShowHeader + + By default the header row is shown - it can be turned off with -ShowHeader:$false. + + + SwitchParameter + + + False + + + ShowFilter + + By default the filter is enabled - it can be turned off with -ShowFilter:$false. + + + SwitchParameter + + + False + + + ShowTotal + + Show total adds a totals row. This does not automatically sum the columns but provides a drop-down in each to select sum, average etc + + + SwitchParameter + + + False + + + ShowFirstColumn + + Highlights the first column in bold. + + + SwitchParameter + + + False + + + ShowLastColumn + + Highlights the last column in bold. + + + SwitchParameter + + + False + + + ShowRowStripes + + By default the table formats show striped rows, the can be turned off with -ShowRowStripes:$false + + + SwitchParameter + + + False + + + ShowColumnStripes + + Turns on column stripes. + + + SwitchParameter + + + False + + + PassThru + + If -PassThru is specified, the table object will be returned to allow additional changes to be made. + + + SwitchParameter + + + False + + + + + + Range + + The range of cells to assign to a table. + + ExcelRange + + ExcelRange + + + None + + + TableName + + The name for the Table - this should be unqiue in the Workbook - auto generated names will be used if this is left empty. + + String + + String + + + None + + + TableStyle + + The Style for the table, by default "Medium6" is used + + TableStyles + + TableStyles + + + Medium6 + + + ShowHeader + + By default the header row is shown - it can be turned off with -ShowHeader:$false. + + SwitchParameter + + SwitchParameter + + + False + + + ShowFilter + + By default the filter is enabled - it can be turned off with -ShowFilter:$false. + + SwitchParameter + + SwitchParameter + + + False + + + ShowTotal + + Show total adds a totals row. This does not automatically sum the columns but provides a drop-down in each to select sum, average etc + + SwitchParameter + + SwitchParameter + + + False + + + TotalSettings + + A HashTable in the form ColumnName = "Average"|"Count"|"CountNums"|"Max"|"Min"|"None"|"StdDev"|"Sum"|"Var" - if specified, -ShowTotal is not needed. + + Hashtable + + Hashtable + + + None + + + ShowFirstColumn + + Highlights the first column in bold. + + SwitchParameter + + SwitchParameter + + + False + + + ShowLastColumn + + Highlights the last column in bold. + + SwitchParameter + + SwitchParameter + + + False + + + ShowRowStripes + + By default the table formats show striped rows, the can be turned off with -ShowRowStripes:$false + + SwitchParameter + + SwitchParameter + + + False + + + ShowColumnStripes + + Turns on column stripes. + + SwitchParameter + + SwitchParameter + + + False + + + PassThru + + If -PassThru is specified, the table object will be returned to allow additional changes to be made. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + OfficeOpenXml.Table.ExcelTable + + + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $TableName + + $WS is a worksheet, and $dataRange is a string describing a range of cells - for example "A1:Z10". This range which will become a table, named $TableName + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\> Add-ExcelTable -Range $ws.cells[$($ws.Dimension.address)] -TableStyle Light1 -TableName Musictable -ShowFilter:$false -ShowTotal -ShowFirstColumn + + Again $ws is a worksheet, range here is the whole of the active part of the worksheet. The table style and name are set, the filter is turned off, and a "Totals" row added, and first column is set in bold. + + + + + + + + Add-PivotTable + Add + PivotTable + + Adds a PivotTable (and optional PivotChart) to a workbook. + + + + If the PivotTable already exists, the source data will be updated. + + + + Add-PivotTable + + PivotTableName + + Name for the new PivotTable - this will be the name of a sheet in the Workbook. + + String + + String + + + None + + + Address + + By default, a PivotTable will be created on its own sheet, but it can be created on an existing sheet by giving the address where the top left corner of the table should go. (Allow two rows for the filter if one is used.) + + ExcelAddressBase + + ExcelAddressBase + + + None + + + ExcelPackage + + An Excel-package object for the workbook. + + Object + + Object + + + None + + + SourceWorkSheet + + Worksheet where the data is found. + + Object + + Object + + + None + + + SourceRange + + Address range in the worksheet e.g "A10:F20" - the first row must be column names: if not specified the whole sheet will be used. + + Object + + Object + + + None + + + PivotRows + + Fields to set as rows in the PivotTable. + + Object + + Object + + + None + + + PivotData + + A hash table in form "FieldName"="Function", where function is one of Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP. + + Object + + Object + + + None + + + PivotColumns + + Fields to set as columns in the PivotTable. + + Object + + Object + + + None + + + PivotFilter + + Fields to use to filter in the PivotTable. + + Object + + Object + + + None + + + PivotDataToColumn + + If there are multiple data items in a PivotTable, by default they are shown on separate rows; this switch makes them separate columns. + + + SwitchParameter + + + False + + + PivotTotals + + Define whether totals should be added to rows, columns neither, or both (the default is both). + + String + + String + + + Both + + + NoTotalsInPivot + + Included for compatibility - equivalent to -PivotTotals "None". + + + SwitchParameter + + + False + + + GroupDateRow + + The name of a row field which should be grouped by parts of the date/time (ignored if GroupDateRow is not specified) + + String + + String + + + None + + + GroupDatePart + + The Part(s) of the date to use in the grouping (ignored if GroupDateRow is not specified) + + + Years + Quarters + Months + Days + Hours + Minutes + Seconds + + eDateGroupBy[] + + eDateGroupBy[] + + + None + + + GroupNumericRow + + The name of a row field which should be grouped by Number (e.g. 0-99, 100-199, 200-299 ) + + String + + String + + + None + + + GroupNumericMin + + The starting point for grouping + + Double + + Double + + + 0 + + + GroupNumericMax + + The endpoint for grouping + + Double + + Double + + + 1.79769313486232E+308 + + + GroupNumericInterval + + The interval for grouping + + Double + + Double + + + 100 + + + PivotNumberFormat + + Number format to apply to the data cells in the PivotTable. + + String + + String + + + None + + + PivotTableStyle + + Apply a table style to the PivotTable. + + + None + Custom + Light1 + Light2 + Light3 + Light4 + Light5 + Light6 + Light7 + Light8 + Light9 + Light10 + Light11 + Light12 + Light13 + Light14 + Light15 + Light16 + Light17 + Light18 + Light19 + Light20 + Light21 + Medium1 + Medium2 + Medium3 + Medium4 + Medium5 + Medium6 + Medium7 + Medium8 + Medium9 + Medium10 + Medium11 + Medium12 + Medium13 + Medium14 + Medium15 + Medium16 + Medium17 + Medium18 + Medium19 + Medium20 + Medium21 + Medium22 + Medium23 + Medium24 + Medium25 + Medium26 + Medium27 + Medium28 + Dark1 + Dark2 + Dark3 + Dark4 + Dark5 + Dark6 + Dark7 + Dark8 + Dark9 + Dark10 + Dark11 + + TableStyles + + TableStyles + + + None + + + PivotChartDefinition + + Use a chart definition instead of specifying chart settings one by one. + + Object + + Object + + + None + + + Activate + + If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified. + + + SwitchParameter + + + False + + + PassThru + + Return the PivotTable so it can be customized. + + + SwitchParameter + + + False + + + + Add-PivotTable + + PivotTableName + + Name for the new PivotTable - this will be the name of a sheet in the Workbook. + + String + + String + + + None + + + Address + + By default, a PivotTable will be created on its own sheet, but it can be created on an existing sheet by giving the address where the top left corner of the table should go. (Allow two rows for the filter if one is used.) + + ExcelAddressBase + + ExcelAddressBase + + + None + + + ExcelPackage + + An Excel-package object for the workbook. + + Object + + Object + + + None + + + SourceWorkSheet + + Worksheet where the data is found. + + Object + + Object + + + None + + + SourceRange + + Address range in the worksheet e.g "A10:F20" - the first row must be column names: if not specified the whole sheet will be used. + + Object + + Object + + + None + + + PivotRows + + Fields to set as rows in the PivotTable. + + Object + + Object + + + None + + + PivotData + + A hash table in form "FieldName"="Function", where function is one of Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP. + + Object + + Object + + + None + + + PivotColumns + + Fields to set as columns in the PivotTable. + + Object + + Object + + + None + + + PivotFilter + + Fields to use to filter in the PivotTable. + + Object + + Object + + + None + + + PivotDataToColumn + + If there are multiple data items in a PivotTable, by default they are shown on separate rows; this switch makes them separate columns. + + + SwitchParameter + + + False + + + PivotTotals + + Define whether totals should be added to rows, columns neither, or both (the default is both). + + String + + String + + + Both + + + NoTotalsInPivot + + Included for compatibility - equivalent to -PivotTotals "None". + + + SwitchParameter + + + False + + + GroupDateRow + + The name of a row field which should be grouped by parts of the date/time (ignored if GroupDateRow is not specified) + + String + + String + + + None + + + GroupDatePart + + The Part(s) of the date to use in the grouping (ignored if GroupDateRow is not specified) + + + Years + Quarters + Months + Days + Hours + Minutes + Seconds + + eDateGroupBy[] + + eDateGroupBy[] + + + None + + + GroupNumericRow + + The name of a row field which should be grouped by Number (e.g. 0-99, 100-199, 200-299 ) + + String + + String + + + None + + + GroupNumericMin + + The starting point for grouping + + Double + + Double + + + 0 + + + GroupNumericMax + + The endpoint for grouping + + Double + + Double + + + 1.79769313486232E+308 + + + GroupNumericInterval + + The interval for grouping + + Double + + Double + + + 100 + + + PivotNumberFormat + + Number format to apply to the data cells in the PivotTable. + + String + + String + + + None + + + PivotTableStyle + + Apply a table style to the PivotTable. + + + None + Custom + Light1 + Light2 + Light3 + Light4 + Light5 + Light6 + Light7 + Light8 + Light9 + Light10 + Light11 + Light12 + Light13 + Light14 + Light15 + Light16 + Light17 + Light18 + Light19 + Light20 + Light21 + Medium1 + Medium2 + Medium3 + Medium4 + Medium5 + Medium6 + Medium7 + Medium8 + Medium9 + Medium10 + Medium11 + Medium12 + Medium13 + Medium14 + Medium15 + Medium16 + Medium17 + Medium18 + Medium19 + Medium20 + Medium21 + Medium22 + Medium23 + Medium24 + Medium25 + Medium26 + Medium27 + Medium28 + Dark1 + Dark2 + Dark3 + Dark4 + Dark5 + Dark6 + Dark7 + Dark8 + Dark9 + Dark10 + Dark11 + + TableStyles + + TableStyles + + + None + + + IncludePivotChart + + If specified, a chart will be included. + + + SwitchParameter + + + False + + + ChartTitle + + Optional title for the pivot chart, by default the title omitted. + + String + + String + + + None + + + ChartHeight + + Height of the chart in Pixels (400 by default). + + Int32 + + Int32 + + + 400 + + + ChartWidth + + Width of the chart in Pixels (600 by default). + + Int32 + + Int32 + + + 600 + + + ChartRow + + Cell position of the top left corner of the chart, there will be this number of rows above the top edge of the chart (default is 0, chart starts at top edge of row 1). + + Int32 + + Int32 + + + 0 + + + ChartColumn + + Cell position of the top left corner of the chart, there will be this number of cells to the left of the chart (default is 4, chart starts at left edge of column E). + + Int32 + + Int32 + + + 4 + + + ChartRowOffSetPixels + + Vertical offset of the chart from the cell corner. + + Int32 + + Int32 + + + 0 + + + ChartColumnOffSetPixels + + Horizontal offset of the chart from the cell corner. + + Int32 + + Int32 + + + 0 + + + ChartType + + Type of chart; defaults to "Pie". + + + Area + Line + Pie + Bubble + ColumnClustered + ColumnStacked + ColumnStacked100 + ColumnClustered3D + ColumnStacked3D + ColumnStacked1003D + BarClustered + BarStacked + BarStacked100 + BarClustered3D + BarStacked3D + BarStacked1003D + LineStacked + LineStacked100 + LineMarkers + LineMarkersStacked + LineMarkersStacked100 + PieOfPie + PieExploded + PieExploded3D + BarOfPie + XYScatterSmooth + XYScatterSmoothNoMarkers + XYScatterLines + XYScatterLinesNoMarkers + AreaStacked + AreaStacked100 + AreaStacked3D + AreaStacked1003D + DoughnutExploded + RadarMarkers + RadarFilled + Surface + SurfaceWireframe + SurfaceTopView + SurfaceTopViewWireframe + Bubble3DEffect + StockHLC + StockOHLC + StockVHLC + StockVOHLC + CylinderColClustered + CylinderColStacked + CylinderColStacked100 + CylinderBarClustered + CylinderBarStacked + CylinderBarStacked100 + CylinderCol + ConeColClustered + ConeColStacked + ConeColStacked100 + ConeBarClustered + ConeBarStacked + ConeBarStacked100 + ConeCol + PyramidColClustered + PyramidColStacked + PyramidColStacked100 + PyramidBarClustered + PyramidBarStacked + PyramidBarStacked100 + PyramidCol + XYScatter + Radar + Doughnut + Pie3D + Line3D + Column3D + Area3D + + eChartType + + eChartType + + + Pie + + + NoLegend + + If specified hides the chart legend. + + + SwitchParameter + + + False + + + ShowCategory + + If specified attaches the category to slices in a pie chart : not supported on all chart types, this may give errors if applied to an unsupported type. + + + SwitchParameter + + + False + + + ShowPercent + + If specified attaches percentages to slices in a pie chart. + + + SwitchParameter + + + False + + + Activate + + If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified. + + + SwitchParameter + + + False + + + PassThru + + Return the PivotTable so it can be customized. + + + SwitchParameter + + + False + + + + + + PivotTableName + + Name for the new PivotTable - this will be the name of a sheet in the Workbook. + + String + + String + + + None + + + Address + + By default, a PivotTable will be created on its own sheet, but it can be created on an existing sheet by giving the address where the top left corner of the table should go. (Allow two rows for the filter if one is used.) + + ExcelAddressBase + + ExcelAddressBase + + + None + + + ExcelPackage + + An Excel-package object for the workbook. + + Object + + Object + + + None + + + SourceWorkSheet + + Worksheet where the data is found. + + Object + + Object + + + None + + + SourceRange + + Address range in the worksheet e.g "A10:F20" - the first row must be column names: if not specified the whole sheet will be used. + + Object + + Object + + + None + + + PivotRows + + Fields to set as rows in the PivotTable. + + Object + + Object + + + None + + + PivotData + + A hash table in form "FieldName"="Function", where function is one of Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP. + + Object + + Object + + + None + + + PivotColumns + + Fields to set as columns in the PivotTable. + + Object + + Object + + + None + + + PivotFilter + + Fields to use to filter in the PivotTable. + + Object + + Object + + + None + + + PivotDataToColumn + + If there are multiple data items in a PivotTable, by default they are shown on separate rows; this switch makes them separate columns. + + SwitchParameter + + SwitchParameter + + + False + + + PivotTotals + + Define whether totals should be added to rows, columns neither, or both (the default is both). + + String + + String + + + Both + + + NoTotalsInPivot + + Included for compatibility - equivalent to -PivotTotals "None". + + SwitchParameter + + SwitchParameter + + + False + + + GroupDateRow + + The name of a row field which should be grouped by parts of the date/time (ignored if GroupDateRow is not specified) + + String + + String + + + None + + + GroupDatePart + + The Part(s) of the date to use in the grouping (ignored if GroupDateRow is not specified) + + eDateGroupBy[] + + eDateGroupBy[] + + + None + + + GroupNumericRow + + The name of a row field which should be grouped by Number (e.g. 0-99, 100-199, 200-299 ) + + String + + String + + + None + + + GroupNumericMin + + The starting point for grouping + + Double + + Double + + + 0 + + + GroupNumericMax + + The endpoint for grouping + + Double + + Double + + + 1.79769313486232E+308 + + + GroupNumericInterval + + The interval for grouping + + Double + + Double + + + 100 + + + PivotNumberFormat + + Number format to apply to the data cells in the PivotTable. + + String + + String + + + None + + + PivotTableStyle + + Apply a table style to the PivotTable. + + TableStyles + + TableStyles + + + None + + + PivotChartDefinition + + Use a chart definition instead of specifying chart settings one by one. + + Object + + Object + + + None + + + IncludePivotChart + + If specified, a chart will be included. + + SwitchParameter + + SwitchParameter + + + False + + + ChartTitle + + Optional title for the pivot chart, by default the title omitted. + + String + + String + + + None + + + ChartHeight + + Height of the chart in Pixels (400 by default). + + Int32 + + Int32 + + + 400 + + + ChartWidth + + Width of the chart in Pixels (600 by default). + + Int32 + + Int32 + + + 600 + + + ChartRow + + Cell position of the top left corner of the chart, there will be this number of rows above the top edge of the chart (default is 0, chart starts at top edge of row 1). + + Int32 + + Int32 + + + 0 + + + ChartColumn + + Cell position of the top left corner of the chart, there will be this number of cells to the left of the chart (default is 4, chart starts at left edge of column E). + + Int32 + + Int32 + + + 4 + + + ChartRowOffSetPixels + + Vertical offset of the chart from the cell corner. + + Int32 + + Int32 + + + 0 + + + ChartColumnOffSetPixels + + Horizontal offset of the chart from the cell corner. + + Int32 + + Int32 + + + 0 + + + ChartType + + Type of chart; defaults to "Pie". + + eChartType + + eChartType + + + Pie + + + NoLegend + + If specified hides the chart legend. + + SwitchParameter + + SwitchParameter + + + False + + + ShowCategory + + If specified attaches the category to slices in a pie chart : not supported on all chart types, this may give errors if applied to an unsupported type. + + SwitchParameter + + SwitchParameter + + + False + + + ShowPercent + + If specified attaches percentages to slices in a pie chart. + + SwitchParameter + + SwitchParameter + + + False + + + Activate + + If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified. + + SwitchParameter + + SwitchParameter + + + False + + + PassThru + + Return the PivotTable so it can be customized. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + OfficeOpenXml.Table.PivotTable.ExcelPivotTable + + + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> $excel = Get-Service | Export-Excel -Path test.xlsx -WorksheetName Services -PassThru -AutoSize -DisplayPropertySet -TableName ServiceTable -Title "Services on $Env:COMPUTERNAME" + Add-PivotTable -ExcelPackage $excel -PivotTableName ServiceSummary -SourceRange $excel.Workbook.Worksheets\[1\].Tables\[0\].Address -PivotRows Status -PivotData Name -NoTotalsInPivot -Activate + Close-ExcelPackage $excel -Show + + This exports data to new workbook and creates a table with the data in it. + The Pivot table is added on its own page, the table created in the first command is used as the source for the PivotTable; which counts the service names in for each Status. + At the end the Pivot page is made active. + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\> $chartdef = New-ExcelChartDefinition -Title "Gross and net by city and product" -ChartType ColumnClustered ` + -Column 11 -Width 500 -Height 360 -YMajorUnit 500 -YMinorUnit 100 -YAxisNumberformat "$#,##0" -LegendPosition Bottom + $excel = ConvertFrom-Csv @" +Product, City, Gross, Net +Apple, London , 300, 250 +Orange, London , 400, 350 +Banana, London , 300, 200 +Orange, Paris, 600, 500 +Banana, Paris, 300, 200 +Apple, New York, 1200,700 +"@ | Export-Excel -Path "test.xlsx" -TableStyle Medium13 -tablename "RawData" -PassThru + Add-PivotTable -PivotTableName Sales -Address $excel.Workbook.Worksheets[1].Cells["F1"] ` + -SourceWorkSheet $excel.Workbook.Worksheets[1] -PivotRows City -PivotColumns Product -PivotData @{Gross="Sum";Net="Sum"} ` + -PivotNumberFormat "$#,##0.00" -PivotTotals Both -PivotTableStyle Medium12 -PivotChartDefinition $chartdef + Close-ExcelPackage -show $excel + + This script starts by defining a chart. + Then it exports some data to an XLSX file and keeps the file open. + The next step is to add the pivot table, normally this would be on its own sheet in the workbook, but here -Address is specified to place it beside the data. + The Add-Pivot table is given the chart definition and told to create a tale using the City field to create rows, the Product field to create columns and the data should be the sum of the gross field and the sum of the net field; grand totals for both gross and net are included for rows (Cities) and columns (Products) and the data is explicitly formatted as a currency. + Note that in the chart definition the number format for the axis does not include any fraction part. + + + + -------------------------- EXAMPLE 3 -------------------------- + PS> $excel = Convertfrom-csv @" +Location,OrderDate,quantity +Boston,1/1/2017,100 +New York,1/21/2017,200 +Boston,1/11/2017,300 +New York,1/9/2017,400 +Boston,1/18/2017,500 +Boston,2/1/2017,600 +New York,2/21/2017,700 +New York,2/11/2017,800 +Boston,2/9/2017,900 +Boston,2/18/2017,1000 +New York,1/1/2018,100 +Boston,1/21/2018,200 +New York,1/11/2018,300 +Boston,1/9/2018,400 +New York,1/18/2018,500 +Boston,2/1/2018,600 +Boston,2/21/2018,700 +New York,2/11/2018,800 +New York,2/9/2018,900 +Boston,2/18/2018,1000 +"@ | Select-Object -Property @{n="OrderDate";e={[datetime]::ParseExact($_.OrderDate,"M/d/yyyy",(Get-Culture))}}, + Location, Quantity | Export-Excel "test2.xlsx" -PassThru -AutoSize + Set-ExcelColumn -Worksheet $excel.sheet1 -Column 1 -NumberFormat 'Short Date' + $pt = Add-PivotTable -PassThru -PivotTableName "ByDate" -Address $excel.Sheet1.cells["F1"] -SourceWorkSheet $excel.Sheet1 -PivotRows location,orderdate -PivotData @{'quantity'='sum'} -GroupDateRow orderdate -GroupDatePart 'Months,Years' -PivotTotals None + $pt.RowFields[0].SubtotalTop=$false + $pt.RowFields[0].Compact=$false + Close-ExcelPackage $excel -Show + + Here the data contains dates formatted as strings using US format. + These are converted to DateTime objects before being exported to Excel; the "OrderDate" column is formatted with the local short-date style. + Then the PivotTable is added; it groups information by date and location, the date is split into years and then months. + No grand totals are displayed. + The Pivot table object is caught in a variable, and the "Location" column has its subtotal moved from the top to the bottom of each location section, and the "Compact" option is disabled to prevent "Year" moving into the same column as location. + Finally the workbook is saved and shown in Excel. + + + + + + + + Add-WorkSheet + Add + WorkSheet + + Adds a worksheet to an existing workbook. + + + + If the named worksheet already exists, the -Clearsheet parameter decides whether it should be deleted and a new one returned, or if not specified the existing sheet will be returned. + By default the sheet is created at the end of the work book, the -MoveXXXX switches allow the sheet to be [re]positioned at the start or before or after another sheet. + A new sheet will only be made the default sheet when excel opens if -Activate is specified. + + + + Add-WorkSheet + + ExcelPackage + + An object representing an Excel Package. + + ExcelPackage + + ExcelPackage + + + None + + + WorksheetName + + The name of the worksheet, 'Sheet1' by default. + + String + + String + + + None + + + ClearSheet + + If the worksheet already exists, by default it will returned, unless -ClearSheet is specified in which case it will be deleted and re-created. + + + SwitchParameter + + + False + + + MoveToStart + + If specified, the worksheet will be moved to the start of the workbook. + MoveToStart takes precedence over MoveToEnd, Movebefore and MoveAfter if more than one is specified. + + + SwitchParameter + + + False + + + MoveToEnd + + If specified, the worksheet will be moved to the end of the workbook. + (This is the default position for newly created sheets, but it can be used to move existing sheets.) + + + SwitchParameter + + + False + + + MoveBefore + + If specified, the worksheet will be moved before the nominated one (which can be an index starting from 1, or a name). + MoveBefore takes precedence over MoveAfter if both are specified. + + Object + + Object + + + None + + + MoveAfter + + If specified, the worksheet will be moved after the nominated one (which can be an index starting from 1, or a name or *). + If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically. + + Object + + Object + + + None + + + Activate + + If there is already content in the workbook the new sheet will not be active UNLESS Activate is specified. + + + SwitchParameter + + + False + + + CopySource + + If worksheet is provided as a copy source the new worksheet will be a copy of it. The source can be in the same workbook, or in a different file. + + ExcelWorksheet + + ExcelWorksheet + + + None + + + NoClobber + + Ignored but retained for backwards compatibility. + + + SwitchParameter + + + False + + + + Add-WorkSheet + + ExcelWorkbook + + An Excel Workbook to which the Worksheet will be added - a Package contains one Workbook, so you can use whichever fits at the time. + + ExcelWorkbook + + ExcelWorkbook + + + None + + + WorksheetName + + The name of the worksheet, 'Sheet1' by default. + + String + + String + + + None + + + ClearSheet + + If the worksheet already exists, by default it will returned, unless -ClearSheet is specified in which case it will be deleted and re-created. + + + SwitchParameter + + + False + + + MoveToStart + + If specified, the worksheet will be moved to the start of the workbook. + MoveToStart takes precedence over MoveToEnd, Movebefore and MoveAfter if more than one is specified. + + + SwitchParameter + + + False + + + MoveToEnd + + If specified, the worksheet will be moved to the end of the workbook. + (This is the default position for newly created sheets, but it can be used to move existing sheets.) + + + SwitchParameter + + + False + + + MoveBefore + + If specified, the worksheet will be moved before the nominated one (which can be an index starting from 1, or a name). + MoveBefore takes precedence over MoveAfter if both are specified. + + Object + + Object + + + None + + + MoveAfter + + If specified, the worksheet will be moved after the nominated one (which can be an index starting from 1, or a name or *). + If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically. + + Object + + Object + + + None + + + Activate + + If there is already content in the workbook the new sheet will not be active UNLESS Activate is specified. + + + SwitchParameter + + + False + + + CopySource + + If worksheet is provided as a copy source the new worksheet will be a copy of it. The source can be in the same workbook, or in a different file. + + ExcelWorksheet + + ExcelWorksheet + + + None + + + NoClobber + + Ignored but retained for backwards compatibility. + + + SwitchParameter + + + False + + + + + + ExcelPackage + + An object representing an Excel Package. + + ExcelPackage + + ExcelPackage + + + None + + + ExcelWorkbook + + An Excel Workbook to which the Worksheet will be added - a Package contains one Workbook, so you can use whichever fits at the time. + + ExcelWorkbook + + ExcelWorkbook + + + None + + + WorksheetName + + The name of the worksheet, 'Sheet1' by default. + + String + + String + + + None + + + ClearSheet + + If the worksheet already exists, by default it will returned, unless -ClearSheet is specified in which case it will be deleted and re-created. + + SwitchParameter + + SwitchParameter + + + False + + + MoveToStart + + If specified, the worksheet will be moved to the start of the workbook. + MoveToStart takes precedence over MoveToEnd, Movebefore and MoveAfter if more than one is specified. + + SwitchParameter + + SwitchParameter + + + False + + + MoveToEnd + + If specified, the worksheet will be moved to the end of the workbook. + (This is the default position for newly created sheets, but it can be used to move existing sheets.) + + SwitchParameter + + SwitchParameter + + + False + + + MoveBefore + + If specified, the worksheet will be moved before the nominated one (which can be an index starting from 1, or a name). + MoveBefore takes precedence over MoveAfter if both are specified. + + Object + + Object + + + None + + + MoveAfter + + If specified, the worksheet will be moved after the nominated one (which can be an index starting from 1, or a name or *). + If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically. + + Object + + Object + + + None + + + Activate + + If there is already content in the workbook the new sheet will not be active UNLESS Activate is specified. + + SwitchParameter + + SwitchParameter + + + False + + + CopySource + + If worksheet is provided as a copy source the new worksheet will be a copy of it. The source can be in the same workbook, or in a different file. + + ExcelWorksheet + + ExcelWorksheet + + + None + + + NoClobber + + Ignored but retained for backwards compatibility. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + OfficeOpenXml.ExcelWorksheet + + + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> $WorksheetActors = $ExcelPackage | Add-WorkSheet -WorkSheetname Actors + + $ExcelPackage holds an Excel package object (returned by Open-ExcelPackage, or Export-Excel -passthru). This command will add a sheet named 'Actors', or return the sheet if it exists, and the result is stored in $WorkSheetActors. + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\> $WorksheetActors = Add-WorkSheet -ExcelPackage $ExcelPackage -WorkSheetname "Actors" -ClearSheet -MoveToStart + + This time the Excel package object is passed as a parameter instead of piped. + If the 'Actors' sheet already exists it is deleted and re-created. + The new sheet will be created last in the workbook, and -MoveToStart Moves it to the start. + + + + -------------------------- EXAMPLE 3 -------------------------- + PS\> $null = Add-WorkSheet -ExcelWorkbook $wb -WorkSheetname $DestinationName -CopySource $sourceWs -Activate + + This time a workbook is used instead of a package, and a worksheet is copied - $SourceWs is a worksheet object, which can come from the same workbook or a different one. + Here the new copy of the data is made the active sheet when the workbook is opened. + + + + + + + + Close-ExcelPackage + Close + ExcelPackage + + Closes an Excel Package, saving, saving under a new name or abandoning changes and opening the file in Excel as required. + + + + When working with an ExcelPackage object, the Workbook is held in memory and not saved until the .Save() method of the package is called. + Close-ExcelPackage saves and disposes of the Package object. + It can be called with -NoSave to abandon the file without saving, with a new "SaveAs" filename, and/or with a password to protect the file. And -Show will open the file in Excel; -Calculate will try to update the workbook, although not everything can be recalculated + + + + Close-ExcelPackage + + ExcelPackage + + Package to close. + + ExcelPackage + + ExcelPackage + + + None + + + SaveAs + + Save file with a new name (ignored if -NoSave Specified). + + Object + + Object + + + None + + + Password + + Password to protect the file. + + String + + String + + + None + + + Show + + Open the file in Excel. + + + SwitchParameter + + + False + + + NoSave + + Abandon the file without saving. + + + SwitchParameter + + + False + + + Calculate + + Attempt to recalculation the workbook before saving + + + SwitchParameter + + + False + + + + + + ExcelPackage + + Package to close. + + ExcelPackage + + ExcelPackage + + + None + + + Show + + Open the file in Excel. + + SwitchParameter + + SwitchParameter + + + False + + + NoSave + + Abandon the file without saving. + + SwitchParameter + + SwitchParameter + + + False + + + SaveAs + + Save file with a new name (ignored if -NoSave Specified). + + Object + + Object + + + None + + + Password + + Password to protect the file. + + String + + String + + + None + + + Calculate + + Attempt to recalculation the workbook before saving + + SwitchParameter + + SwitchParameter + + + False + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + Close-ExcelPackage -show $excel + + $excel holds a package object, this saves the workbook and loads it into Excel. + + + + -------------------------- EXAMPLE 2 -------------------------- + Close-ExcelPackage -NoSave $excel + + $excel holds a package object, this disposes of it without writing it to disk. + + + + + + + + Compare-WorkSheet + Compare + WorkSheet + + Compares two worksheets and shows the differences. + + + + This command takes two file names, one or two worksheet names and a name for a "key" column. + It reads the worksheet from each file and decides the column names and builds a hashtable of the key-column values and the rows in which they appear. + It then uses PowerShell's Compare-Object command to compare the sheets (explicitly checking all the column names which have not been excluded). + For the difference rows it adds the row number for the key of that row - we have to add the key after doing the comparison, otherwise identical rows at different positions in the file will not be considered a match. + We also add the name of the file and sheet in which the difference occurs. + If -BackgroundColor is specified the difference rows will be changed to that background in the orginal file. + + + + Compare-WorkSheet + + Referencefile + + First file to compare. + + Object + + Object + + + None + + + Differencefile + + Second file to compare. + + Object + + Object + + + None + + + WorkSheetName + + Name(s) of worksheets to compare. + + Object + + Object + + + Sheet1 + + + Property + + Properties to include in the comparison - supports wildcards, default is "*". + + Object + + Object + + + * + + + ExcludeProperty + + Properties to exclude from the comparison - supports wildcards. + + Object + + Object + + + None + + + Headername + + Specifies custom property names to use, instead of the values defined in the starting row of the sheet. + + String[] + + String[] + + + None + + + Startrow + + The row from where we start to import data: all rows above the start row are disregarded. By default, this is the first row. + + Int32 + + Int32 + + + 1 + + + AllDataBackgroundColor + + If specified, highlights all the cells - so you can make Equal cells one color, and Different cells another. + + Object + + Object + + + None + + + BackgroundColor + + If specified, highlights the rows with differences. + + Object + + Object + + + None + + + TabColor + + If specified identifies the tabs which contain difference rows (ignored if -BackgroundColor is omitted). + + Object + + Object + + + None + + + Key + + Name of a column which is unique and will be used to add a row to the DIFF object, defaults to "Name". + + Object + + Object + + + Name + + + FontColor + + If specified, highlights the DIFF columns in rows which have the same key. + + Object + + Object + + + None + + + Show + + If specified, opens the Excel workbooks instead of outputting the diff to the console (unless -PassThru is also specified). + + + SwitchParameter + + + False + + + GridView + + If specified, the command tries to the show the DIFF in a Grid-View and not on the console (unless-PassThru is also specified). This works best with few columns selected, and requires a key. + + + SwitchParameter + + + False + + + PassThru + + If specified a full set of DIFF data is returned without filtering to the specified properties. + + + SwitchParameter + + + False + + + IncludeEqual + + If specified the result will include equal rows as well. By default only different rows are returned. + + + SwitchParameter + + + False + + + ExcludeDifferent + + If specified, the result includes only the rows where both are equal. + + + SwitchParameter + + + False + + + + Compare-WorkSheet + + Referencefile + + First file to compare. + + Object + + Object + + + None + + + Differencefile + + Second file to compare. + + Object + + Object + + + None + + + WorkSheetName + + Name(s) of worksheets to compare. + + Object + + Object + + + Sheet1 + + + Property + + Properties to include in the comparison - supports wildcards, default is "*". + + Object + + Object + + + * + + + ExcludeProperty + + Properties to exclude from the comparison - supports wildcards. + + Object + + Object + + + None + + + NoHeader + + Automatically generate property names (P1, P2, P3 ...) instead of the using the values the starting row of the sheet. + + + SwitchParameter + + + False + + + Startrow + + The row from where we start to import data: all rows above the start row are disregarded. By default, this is the first row. + + Int32 + + Int32 + + + 1 + + + AllDataBackgroundColor + + If specified, highlights all the cells - so you can make Equal cells one color, and Different cells another. + + Object + + Object + + + None + + + BackgroundColor + + If specified, highlights the rows with differences. + + Object + + Object + + + None + + + TabColor + + If specified identifies the tabs which contain difference rows (ignored if -BackgroundColor is omitted). + + Object + + Object + + + None + + + Key + + Name of a column which is unique and will be used to add a row to the DIFF object, defaults to "Name". + + Object + + Object + + + Name + + + FontColor + + If specified, highlights the DIFF columns in rows which have the same key. + + Object + + Object + + + None + + + Show + + If specified, opens the Excel workbooks instead of outputting the diff to the console (unless -PassThru is also specified). + + + SwitchParameter + + + False + + + GridView + + If specified, the command tries to the show the DIFF in a Grid-View and not on the console (unless-PassThru is also specified). This works best with few columns selected, and requires a key. + + + SwitchParameter + + + False + + + PassThru + + If specified a full set of DIFF data is returned without filtering to the specified properties. + + + SwitchParameter + + + False + + + IncludeEqual + + If specified the result will include equal rows as well. By default only different rows are returned. + + + SwitchParameter + + + False + + + ExcludeDifferent + + If specified, the result includes only the rows where both are equal. + + + SwitchParameter + + + False + + + + + + Referencefile + + First file to compare. + + Object + + Object + + + None + + + Differencefile + + Second file to compare. + + Object + + Object + + + None + + + WorkSheetName + + Name(s) of worksheets to compare. + + Object + + Object + + + Sheet1 + + + Property + + Properties to include in the comparison - supports wildcards, default is "*". + + Object + + Object + + + * + + + ExcludeProperty + + Properties to exclude from the comparison - supports wildcards. + + Object + + Object + + + None + + + Headername + + Specifies custom property names to use, instead of the values defined in the starting row of the sheet. + + String[] + + String[] + + + None + + + NoHeader + + Automatically generate property names (P1, P2, P3 ...) instead of the using the values the starting row of the sheet. + + SwitchParameter + + SwitchParameter + + + False + + + Startrow + + The row from where we start to import data: all rows above the start row are disregarded. By default, this is the first row. + + Int32 + + Int32 + + + 1 + + + AllDataBackgroundColor + + If specified, highlights all the cells - so you can make Equal cells one color, and Different cells another. + + Object + + Object + + + None + + + BackgroundColor + + If specified, highlights the rows with differences. + + Object + + Object + + + None + + + TabColor + + If specified identifies the tabs which contain difference rows (ignored if -BackgroundColor is omitted). + + Object + + Object + + + None + + + Key + + Name of a column which is unique and will be used to add a row to the DIFF object, defaults to "Name". + + Object + + Object + + + Name + + + FontColor + + If specified, highlights the DIFF columns in rows which have the same key. + + Object + + Object + + + None + + + Show + + If specified, opens the Excel workbooks instead of outputting the diff to the console (unless -PassThru is also specified). + + SwitchParameter + + SwitchParameter + + + False + + + GridView + + If specified, the command tries to the show the DIFF in a Grid-View and not on the console (unless-PassThru is also specified). This works best with few columns selected, and requires a key. + + SwitchParameter + + SwitchParameter + + + False + + + PassThru + + If specified a full set of DIFF data is returned without filtering to the specified properties. + + SwitchParameter + + SwitchParameter + + + False + + + IncludeEqual + + If specified the result will include equal rows as well. By default only different rows are returned. + + SwitchParameter + + SwitchParameter + + + False + + + ExcludeDifferent + + If specified, the result includes only the rows where both are equal. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> Compare-WorkSheet -Referencefile 'Server56.xlsx' -Differencefile 'Server57.xlsx' -WorkSheetName Products -key IdentifyingNumber -ExcludeProperty Install* | Format-Table + + The two workbooks in this example contain the result of redirecting a subset of properties from Get-WmiObject -Class win32_product to Export-Excel. + The command compares the "Products" pages in the two workbooks, but we don't want to register a difference if the software was installed on a different date or from a different place, and excluding Install* removes InstallDate and InstallSource. + This data doesn't have a "Name" column, so we specify the "IdentifyingNumber" column as the key. + The results will be presented as a table. + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\> Compare-WorkSheet "Server54.xlsx" "Server55.xlsx" -WorkSheetName Services -GridView + + This time two workbooks contain the result of redirecting the command Get-WmiObject -Class win32_service to Export-Excel. + Here the -Differencefile and -Referencefile parameter switches are assumed and the default setting for -Key ("Name") works for services. + This will display the differences between the "Services" sheets using a grid view + + + + -------------------------- EXAMPLE 3 -------------------------- + PS\> Compare-WorkSheet 'Server54.xlsx' 'Server55.xlsx' -WorkSheetName Services -BackgroundColor lightGreen + + This version of the command outputs the differences between the "services" pages and highlights any different rows in the spreadsheet files. + + + + -------------------------- EXAMPLE 4 -------------------------- + PS\> Compare-WorkSheet 'Server54.xlsx' 'Server55.xlsx' -WorkSheetName Services -BackgroundColor lightGreen -FontColor Red -Show + + This example builds on the previous one: this time where two changed rows have the value in the "Name" column (the default value for -Key), this version adds highlighting of the changed cells in red; and then opens the Excel file. + + + + -------------------------- EXAMPLE 5 -------------------------- + PS\> Compare-WorkSheet 'Pester-tests.xlsx' 'Pester-tests.xlsx' -WorkSheetName 'Server1','Server2' -Property "full Description","Executed","Result" -Key "full Description" + + This time the reference file and the difference file are the same file and two different sheets are used. + Because the tests include the machine name and time the test was run, the command specifies that a limited set of columns should be used. + + + + -------------------------- EXAMPLE 6 -------------------------- + PS\> Compare-WorkSheet 'Server54.xlsx' 'Server55.xlsx' -WorkSheetName general -Startrow 2 -Headername Label,value -Key Label -GridView -ExcludeDifferent + + The "General" page in the two workbooks has a title and two unlabelled columns with a row each for CPU, Memory, Domain, Disk and so on. + So the command is told to start at row 2 in order to skip the title and given names for the columns: the first is "label" and the second "Value"; the label acts as the key. + This time we are interested in those rows which are the same in both sheets, and the result is displayed using grid view. + Note that grid view works best when the number of columns is small. + + + + -------------------------- EXAMPLE 7 -------------------------- + PS\>Compare-WorkSheet 'Server1.xlsx' 'Server2.xlsx' -WorkSheetName general -Startrow 2 -Headername Label,value -Key Label -BackgroundColor White -Show -AllDataBackgroundColor LightGray + + This version of the previous command highlights all the cells in LightGray and then sets the changed rows back to white. + Only the unchanged rows are highlighted. + + + + + + + + Convert-ExcelRangeToImage + Convert + ExcelRangeToImage + + Gets the specified part of an Excel file and exports it as an image + + + + Excel allows charts to be exported directly to a file, but it can't do this with the rest of a sheet. To work round this, this function + * Opens a copy of Excel and loads a file + * Selects a worksheet and then a range of cells in that worksheet + * Copies the select to the clipboard + * Saves the clipboard contents as an image file (it will save as .JPG unless the file name ends .BMP or .PNG) + * Copies a single cell to the clipboard (to prevent the "you have put a lot in the clipboard" message appearing) + * Closes Excel + Unlike most functions in the module it needs a local copy of Excel to be installed. + + + + Convert-ExcelRangeToImage + + Path + + Path to the Excel file + + Object + + Object + + + None + + + WorkSheetname + + Worksheet name - if none is specified "Sheet1" will be assumed + + Object + + Object + + + Sheet1 + + + Range + + Range of cells within the sheet, e.g "A1:Z99" + + Object + + Object + + + None + + + Destination + + A bmp, png or jpg file where the result will be saved + + Object + + Object + + + "$pwd\temp.png" + + + Show + + If specified opens the image in the default viewer. + + + SwitchParameter + + + False + + + + + + Path + + Path to the Excel file + + Object + + Object + + + None + + + WorkSheetname + + Worksheet name - if none is specified "Sheet1" will be assumed + + Object + + Object + + + Sheet1 + + + Range + + Range of cells within the sheet, e.g "A1:Z99" + + Object + + Object + + + None + + + Destination + + A bmp, png or jpg file where the result will be saved + + Object + + Object + + + "$pwd\temp.png" + + + Show + + If specified opens the image in the default viewer. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + + + + + + + + + ConvertFrom-ExcelToSQLInsert + ConvertFrom + ExcelToSQLInsert + + Generate SQL insert statements from Excel spreadsheet. + + + + Generate SQL insert statements from Excel spreadsheet. + + + + ConvertFrom-ExcelToSQLInsert + + TableName + + Name of the target database table. + + Object + + Object + + + None + + + Path + + Path to an existing .XLSX file This parameter is passed to Import-Excel as is. + + Object + + Object + + + None + + + WorkSheetname + + Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported. This parameter is passed to Import-Excel as is. + + Object + + Object + + + 1 + + + StartRow + + The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. When one of both parameters are provided, the property names are automatically created and this row will be treated as a regular row containing data. + + Int32 + + Int32 + + + 0 + + + Header + + Specifies custom property names to use, instead of the values defined in the column headers of the TopRow. If you provide fewr header names than there is data in the worksheet, then only the data with a corresponding header name will be imported and the data without header name will be disregarded. If you provide more header names than there is data in the worksheet, then all data will be imported and all objects will have all the property names you defined in the header names. As such, the last properties will be blank as there is no data for them. + + String[] + + String[] + + + None + + + NoHeader + + Automatically generate property names (P1, P2, P3, ..) instead of the ones defined in the column headers of the TopRow. This switch is best used when you want to import the complete worksheet 'as is' and are not concerned with the property names. + + + SwitchParameter + + + False + + + DataOnly + + Import only rows and columns that contain data, empty rows and empty columns are not imported. + + + SwitchParameter + + + False + + + ConvertEmptyStringsToNull + + If specified, cells without any data are replaced with NULL, instead of an empty string. This is to address behviors in certain DBMS where an empty string is insert as 0 for INT column, instead of a NULL value. + + + SwitchParameter + + + False + + + UseMSSQLSyntax + + {{ Fill UseMSSQLSyntax Description }} + + + SwitchParameter + + + False + + + + + + TableName + + Name of the target database table. + + Object + + Object + + + None + + + Path + + Path to an existing .XLSX file This parameter is passed to Import-Excel as is. + + Object + + Object + + + None + + + WorkSheetname + + Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported. This parameter is passed to Import-Excel as is. + + Object + + Object + + + 1 + + + StartRow + + The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. When one of both parameters are provided, the property names are automatically created and this row will be treated as a regular row containing data. + + Int32 + + Int32 + + + 0 + + + Header + + Specifies custom property names to use, instead of the values defined in the column headers of the TopRow. If you provide fewr header names than there is data in the worksheet, then only the data with a corresponding header name will be imported and the data without header name will be disregarded. If you provide more header names than there is data in the worksheet, then all data will be imported and all objects will have all the property names you defined in the header names. As such, the last properties will be blank as there is no data for them. + + String[] + + String[] + + + None + + + NoHeader + + Automatically generate property names (P1, P2, P3, ..) instead of the ones defined in the column headers of the TopRow. This switch is best used when you want to import the complete worksheet 'as is' and are not concerned with the property names. + + SwitchParameter + + SwitchParameter + + + False + + + DataOnly + + Import only rows and columns that contain data, empty rows and empty columns are not imported. + + SwitchParameter + + SwitchParameter + + + False + + + ConvertEmptyStringsToNull + + If specified, cells without any data are replaced with NULL, instead of an empty string. This is to address behviors in certain DBMS where an empty string is insert as 0 for INT column, instead of a NULL value. + + SwitchParameter + + SwitchParameter + + + False + + + UseMSSQLSyntax + + {{ Fill UseMSSQLSyntax Description }} + + SwitchParameter + + SwitchParameter + + + False + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + Generate SQL insert statements from Movies.xlsx file, leaving blank cells as empty strings: + +---------------------------------------------------------- +| File: Movies.xlsx - Sheet: Sheet1 | +---------------------------------------------------------- +| A B C | +|1 Movie Name Year Rating | +|2 The Bodyguard 1992 9 | +|3 The Matrix 1999 8 | +|4 Skyfall 2012 9 | +|5 The Avengers 2012 | +---------------------------------------------------------- + +PS C:\> ConvertFrom-ExcelToSQLInsert -TableName "Movies" -Path 'C:\Movies.xlsx' +INSERT INTO Movies ('Movie Name', 'Year', 'Rating') Values('The Bodyguard', '1992', '9'); +INSERT INTO Movies ('Movie Name', 'Year', 'Rating') Values('The Matrix', '1999', '8'); +INSERT INTO Movies ('Movie Name', 'Year', 'Rating') Values('Skyfall', '2012', '9'); +INSERT INTO Movies ('Movie Name', 'Year', 'Rating') Values('The Avengers', '2012', ''); + + + + + + -------------------------- EXAMPLE 2 -------------------------- + Generate SQL insert statements from Movies.xlsx file, specify NULL instead of an empty string. + +---------------------------------------------------------- +| File: Movies.xlsx - Sheet: Sheet1 | +---------------------------------------------------------- +| A B C | +|1 Movie Name Year Rating | +|2 The Bodyguard 1992 9 | +|3 The Matrix 1999 8 | +|4 Skyfall 2012 9 | +|5 The Avengers 2012 | +---------------------------------------------------------- + +PS C:\> ConvertFrom-ExcelToSQLInsert -TableName "Movies" -Path "C:\Movies.xlsx" -ConvertEmptyStringsToNull +INSERT INTO Movies ('Movie Name', 'Year', 'Rating') Values('The Bodyguard', '1992', '9'); +INSERT INTO Movies ('Movie Name', 'Year', 'Rating') Values('The Matrix', '1999', '8'); +INSERT INTO Movies ('Movie Name', 'Year', 'Rating') Values('Skyfall', '2012', '9'); +INSERT INTO Movies ('Movie Name', 'Year', 'Rating') Values('The Avengers', '2012', NULL); + + + + + + + + + + Copy-ExcelWorkSheet + Copy + ExcelWorkSheet + + Copies a worksheet between workbooks or within the same workbook. + + + + Copy-ExcelWorkSheet takes a Source object which is either a worksheet, or a package, Workbook or path, in which case the source worksheet can be specified by name or number (starting from 1). The destination worksheet can be explicitly named, or will follow the name of the source if no name is specified. The Destination workbook can be given as the path to an XLSx file, an ExcelPackage object or an ExcelWorkbook object. + + + + Copy-ExcelWorkSheet + + SourceObject + + An ExcelWorkbook or ExcelPackage object or the path to an XLSx file where the data is found. + + Object + + Object + + + None + + + SourceWorkSheet + + Name or number (starting from 1) of the worksheet in the source workbook (defaults to 1). + + Object + + Object + + + 1 + + + DestinationWorkbook + + An ExcelWorkbook or ExcelPackage object or the path to an XLSx file where the data should be copied. + + Object + + Object + + + None + + + DestinationWorksheet + + Name of the worksheet in the destination workbook; by default the same as the source worksheet's name. If the sheet exists it will be deleted and re-copied. + + Object + + Object + + + None + + + Show + + if the destination is an excel package or a path, launch excel and open the file on completion. + + + SwitchParameter + + + False + + + + + + SourceObject + + An ExcelWorkbook or ExcelPackage object or the path to an XLSx file where the data is found. + + Object + + Object + + + None + + + SourceWorkSheet + + Name or number (starting from 1) of the worksheet in the source workbook (defaults to 1). + + Object + + Object + + + 1 + + + DestinationWorkbook + + An ExcelWorkbook or ExcelPackage object or the path to an XLSx file where the data should be copied. + + Object + + Object + + + None + + + DestinationWorksheet + + Name of the worksheet in the destination workbook; by default the same as the source worksheet's name. If the sheet exists it will be deleted and re-copied. + + Object + + Object + + + None + + + Show + + if the destination is an excel package or a path, launch excel and open the file on completion. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + Copy-ExcelWorkSheet -SourceWorkbook Test1.xlsx -DestinationWorkbook Test2.xlsx + + This is the simplest version of the command: no source worksheet is specified so Copy-ExcelWorksheet uses the first sheet in the workbook No Destination sheet is specified so the new worksheet will be the same as the one which is being copied. + + + + -------------------------- EXAMPLE 2 -------------------------- + Copy-ExcelWorkSheet -SourceWorkbook Server1.xlsx -sourceWorksheet "Settings" -DestinationWorkbook Settings.xlsx -DestinationWorksheet "Server1" + + Here the Settings page from Server1's workbook is copied to the 'Server1" page of a "Settings" workbook. + + + + -------------------------- EXAMPLE 3 -------------------------- + $excel = Open-ExcelPackage .\test.xlsx + + C:\> Copy-ExcelWorkSheet -SourceWorkbook $excel -SourceWorkSheet "first" -DestinationWorkbook $excel -Show -DestinationWorksheet Duplicate This opens the workbook test.xlsx and copies the worksheet named "first" to a new worksheet named "Duplicate", because -Show is specified the file is saved and opened in Excel + + + + -------------------------- EXAMPLE 4 -------------------------- + $excel = Open-ExcelPackage .\test.xlsx + + C:\> Copy-ExcelWorkSheet -SourceWorkbook $excel -SourceWorkSheet 1 -DestinationWorkbook $excel -DestinationWorksheet Duplicate C:\> Close-ExcelPackage $excel This is almost the same as the previous example, except source sheet is specified by position rather than name and because -Show is not specified, so other steps can be carried using the package object, at the end the file is saved by Close-ExcelPackage + + + + + + + + Expand-NumberFormat + Expand + NumberFormat + + Converts short names for number formats to the formatting strings used in Excel + + + + Where you can type a number format you can write, for example, 'Short-Date' and the module will translate it into the format string used by Excel. Some formats, like Short-Date, change when Excel loads (so date will use the local ordering of year, month and Day). Excel also changes how markers in the are presented different cultures "," is used in the format string to mean "local thousand seperator" but depending on the country "," or "." or " " may used as the thousand seperator. + + + + Expand-NumberFormat + + NumberFormat + + The format string to Expand + + Object + + Object + + + None + + + + + + NumberFormat + + The format string to Expand + + Object + + Object + + + None + + + + + + + System.String + + + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + Expand-NumberFormat percentage + + Returns "0.00%" + + + + -------------------------- EXAMPLE 2 -------------------------- + Expand-NumberFormat Currency + + Returns the currency format specified in the local regional settings, which may not be the same as Excel uses. + The regional settings set the currency symbol and then whether it is before or after the number and separated with a space or not; for negative numbers the number may be wrapped in parentheses or a - sign might appear before or after the number and symbol. + So this returns $#,##0.00;($#,##0.00) for English US, #,##0.00 €;€#,##0.00- for French. + Note some Eurozone countries write €1,23 and others 1,23€. In French the decimal point will be rendered as a "," and the thousand separator as a space. + + + + + + + + Export-Excel + Export + Excel + + Exports data to an Excel worksheet. + + + + Exports data to an Excel file and where possible tries to convert numbers in text fields so Excel recognizes them as numbers instead of text. After all: Excel is a spreadsheet program used for number manipulation and calculations. The parameter -NoNumberConversion * can be used if number conversion is not desired. + + + + Export-Excel + + Path + + Path to a new or existing .XLSX file. + + String + + String + + + None + + + InputObject + + Date is usually piped into Export-Excel, but it also accepts data through the InputObject parameter + + Object + + Object + + + None + + + Calculate + + If specified, a recalculation of the worksheet will be requested before saving. + + + SwitchParameter + + + False + + + Show + + Opens the Excel file immediately after creation; convenient for viewing the results instantly without having to search for the file first. + + + SwitchParameter + + + False + + + WorksheetName + + The name of a sheet within the workbook - "Sheet1" by default. + + String + + String + + + Sheet1 + + + Password + + Sets password protection on the workbook. + + String + + String + + + None + + + ClearSheet + + If specified Export-Excel will remove any existing worksheet with the selected name. + The default behaviour is to overwrite cells in this sheet as needed (but leaving non-overwritten ones in place). + + + SwitchParameter + + + False + + + Append + + If specified data will be added to the end of an existing sheet, using the same column headings. + + + SwitchParameter + + + False + + + Title + + Text of a title to be placed in the top left cell. + + String + + String + + + None + + + TitleFillPattern + + Sets the fill pattern for the title cell. + + + None + Solid + DarkGray + MediumGray + LightGray + Gray125 + Gray0625 + DarkVertical + DarkHorizontal + DarkDown + DarkUp + DarkGrid + DarkTrellis + LightVertical + LightHorizontal + LightDown + LightUp + LightGrid + LightTrellis + + ExcelFillStyle + + ExcelFillStyle + + + Solid + + + TitleBold + + Sets the title in boldface type. + + + SwitchParameter + + + False + + + TitleSize + + Sets the point size for the title. + + Int32 + + Int32 + + + 22 + + + TitleBackgroundColor + + Sets the cell background color for the title cell. + + Object + + Object + + + None + + + IncludePivotTable + + Adds a PivotTable using the data in the worksheet. + + + SwitchParameter + + + False + + + PivotTableName + + If a PivotTable is created from command line parameters, specifies the name of the new sheet holding the pivot. Defaults to "WorksheetName-PivotTable". + + String + + String + + + None + + + PivotRows + + Name(s) of column(s) from the spreadsheet which will provide the Row name(s) in a PivotTable created from command line parameters. + + String[] + + String[] + + + None + + + PivotColumns + + Name(s) of columns from the spreadsheet which will provide the Column name(s) in a PivotTable created from command line parameters. + + String[] + + String[] + + + None + + + PivotData + + In a PivotTable created from command line parameters, the fields to use in the table body are given as a Hash-table in the form + ColumnName = Average|Count|CountNums|Max|Min|Product|None|StdDev|StdDevP|Sum|Var|VarP. + + Object + + Object + + + None + + + PivotFilter + + Name(s) columns from the spreadsheet which will provide the Filter name(s) in a PivotTable created from command line parameters. + + String[] + + String[] + + + None + + + PivotDataToColumn + + If there are multiple datasets in a PivotTable, by default they are shown as separate rows under the given row heading; this switch makes them separate columns. + + + SwitchParameter + + + False + + + PivotTableDefinition + + Instead of describing a single PivotTable with multiple command-line parameters; you can use a HashTable in the form PivotTableName = Definition; + In this table Definition is itself a Hashtable with Sheet, PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values. The New-PivotTableDefinition command will create the definition from a command line. + + Hashtable + + Hashtable + + + None + + + IncludePivotChart + + Include a chart with the PivotTable - implies -IncludePivotTable. + + + SwitchParameter + + + False + + + ChartType + + The type for PivotChart (one of Excel's defined chart types). + + + Area + Line + Pie + Bubble + ColumnClustered + ColumnStacked + ColumnStacked100 + ColumnClustered3D + ColumnStacked3D + ColumnStacked1003D + BarClustered + BarStacked + BarStacked100 + BarClustered3D + BarStacked3D + BarStacked1003D + LineStacked + LineStacked100 + LineMarkers + LineMarkersStacked + LineMarkersStacked100 + PieOfPie + PieExploded + PieExploded3D + BarOfPie + XYScatterSmooth + XYScatterSmoothNoMarkers + XYScatterLines + XYScatterLinesNoMarkers + AreaStacked + AreaStacked100 + AreaStacked3D + AreaStacked1003D + DoughnutExploded + RadarMarkers + RadarFilled + Surface + SurfaceWireframe + SurfaceTopView + SurfaceTopViewWireframe + Bubble3DEffect + StockHLC + StockOHLC + StockVHLC + StockVOHLC + CylinderColClustered + CylinderColStacked + CylinderColStacked100 + CylinderBarClustered + CylinderBarStacked + CylinderBarStacked100 + CylinderCol + ConeColClustered + ConeColStacked + ConeColStacked100 + ConeBarClustered + ConeBarStacked + ConeBarStacked100 + ConeCol + PyramidColClustered + PyramidColStacked + PyramidColStacked100 + PyramidBarClustered + PyramidBarStacked + PyramidBarStacked100 + PyramidCol + XYScatter + Radar + Doughnut + Pie3D + Line3D + Column3D + Area3D + + eChartType + + eChartType + + + Pie + + + NoLegend + + Exclude the legend from the PivotChart. + + + SwitchParameter + + + False + + + ShowCategory + + Add category labels to the PivotChart. + + + SwitchParameter + + + False + + + ShowPercent + + Add percentage labels to the PivotChart. + + + SwitchParameter + + + False + + + AutoSize + + Sizes the width of the Excel column to the maximum width needed to display all the containing data in that cell. + + + SwitchParameter + + + False + + + MaxAutoSizeRows + + Autosizing can be time consuming, so this sets a maximum number of rows to look at for the Autosize operation. Default is 1000; If 0 is specified ALL rows will be checked + + Object + + Object + + + 1000 + + + NoClobber + + Not used. Left in to avoid problems with older scripts, it may be removed in future versions. + + + SwitchParameter + + + False + + + FreezeTopRow + + Freezes headers etc. in the top row. + + + SwitchParameter + + + False + + + FreezeFirstColumn + + Freezes titles etc. in the left column. + + + SwitchParameter + + + False + + + FreezeTopRowFirstColumn + + Freezes top row and left column (equivalent to Freeze pane 2,2 ). + + + SwitchParameter + + + False + + + FreezePane + + Freezes panes at specified coordinates (in the form RowNumber, ColumnNumber). + + Int32[] + + Int32[] + + + None + + + AutoFilter + + Enables the Excel filter on the complete header row, so users can easily sort, filter and/or search the data in the selected column. + + + SwitchParameter + + + False + + + BoldTopRow + + Makes the top row boldface. + + + SwitchParameter + + + False + + + NoHeader + + Specifies that field names should not be put at the top of columns. + + + SwitchParameter + + + False + + + RangeName + + Makes the data in the worksheet a named range. + + String + + String + + + None + + + TableName + + Makes the data in the worksheet a table with a name, and applies a style to it. The name must not contain spaces. If the -Tablestyle parameter is specified without Tablename, "table1", "table2" etc. will be used. + + Object + + Object + + + None + + + TableStyle + + Selects the style for the named table - if the Tablename parameter is specified without giving a style, 'Medium6' is used as a default. + + + None + Custom + Light1 + Light2 + Light3 + Light4 + Light5 + Light6 + Light7 + Light8 + Light9 + Light10 + Light11 + Light12 + Light13 + Light14 + Light15 + Light16 + Light17 + Light18 + Light19 + Light20 + Light21 + Medium1 + Medium2 + Medium3 + Medium4 + Medium5 + Medium6 + Medium7 + Medium8 + Medium9 + Medium10 + Medium11 + Medium12 + Medium13 + Medium14 + Medium15 + Medium16 + Medium17 + Medium18 + Medium19 + Medium20 + Medium21 + Medium22 + Medium23 + Medium24 + Medium25 + Medium26 + Medium27 + Medium28 + Dark1 + Dark2 + Dark3 + Dark4 + Dark5 + Dark6 + Dark7 + Dark8 + Dark9 + Dark10 + Dark11 + + TableStyles + + TableStyles + + + Medium6 + + + Barchart + + Creates a "quick" bar chart using the first text column as labels and the first numeric column as values. + + + SwitchParameter + + + False + + + PieChart + + Creates a "quick" pie chart using the first text column as labels and the first numeric column as values. + + + SwitchParameter + + + False + + + LineChart + + Creates a "quick" line chart using the first text column as labels and the first numeric column as values. + + + SwitchParameter + + + False + + + ColumnChart + + Creates a "quick" column chart using the first text column as labels and the first numeric column as values. + + + SwitchParameter + + + False + + + ExcelChartDefinition + + A hash-table containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-Pivot] charts. This can be created with the New-ExcelChartDefinition command. + + Object[] + + Object[] + + + None + + + HideSheet + + Name(s) of Sheet(s) to hide in the workbook, supports wildcards. If the selection would cause all sheets to be hidden, the sheet being worked on will be revealed. + + String[] + + String[] + + + None + + + UnHideSheet + + Name(s) of Sheet(s) to reveal in the workbook, supports wildcards. + + String[] + + String[] + + + None + + + MoveToStart + + If specified, the worksheet will be moved to the start of the workbook. + -MoveToStart takes precedence over -MoveToEnd, -Movebefore and -MoveAfter if more than one is specified. + + + SwitchParameter + + + False + + + MoveToEnd + + If specified, the worksheet will be moved to the end of the workbook. (This is the default position for newly created sheets, but the option can be specified to move existing sheets.) + + + SwitchParameter + + + False + + + MoveBefore + + If specified, the worksheet will be moved before the nominated one (which can be a position starting from 1, or a name). + -MoveBefore takes precedence over -MoveAfter if both are specified. + + Object + + Object + + + None + + + MoveAfter + + If specified, the worksheet will be moved after the nominated one (which can be a position starting from 1, or a name or *). + If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically. + + Object + + Object + + + None + + + KillExcel + + Closes Excel without stopping to ask if work should be saved - prevents errors writing to the file because Excel has it open. + + + SwitchParameter + + + False + + + AutoNameRange + + Makes each column a named range. + + + SwitchParameter + + + False + + + StartRow + + Row to start adding data. 1 by default. Row 1 will contain the title, if any is specifed. Then headers will appear (Unless -No header is specified) then the data appears. + + Int32 + + Int32 + + + 1 + + + StartColumn + + Column to start adding data - 1 by default. + + Int32 + + Int32 + + + 1 + + + PassThru + + If specified, Export-Excel returns an object representing the Excel package without saving the package first. To save, you must either use the Close-ExcelPackage command, or send the package object back to Export-Excel which will save and close the file, or use the object's .Save() or SaveAs() method. + + + SwitchParameter + + + False + + + Numberformat + + Formats all values that can be converted to a number to the format specified. For examples: + + '0' integer (not really needed unless you need to round numbers, Excel will use default cell properties). + '#' integer without displaying the number 0 in the cell. + '0.0' number with 1 decimal place. + '0.00' number with 2 decimal places. + '#,##0.00' number with 2 decimal places and thousand-separator. + '€#,##0.00' number with 2 decimal places and thousand-separator and money-symbol. + '0%' number with 2 decimal places and thousand-separator and money-symbol. + '[Blue]$#,##0.00;[Red]-$#,##0.00' + blue for positive numbers and red for negative numbers; Both proceeded by a '$' sign + + String + + String + + + General + + + ExcludeProperty + + Specifies properties which may exist in the target data but should not be placed on the worksheet. + + String[] + + String[] + + + None + + + NoAliasOrScriptPropeties + + Some objects in PowerShell duplicate existing properties by adding aliases, or have Script properties which may take a long time to return a value and slow the export down, if specified this option removes these properties + + + SwitchParameter + + + False + + + DisplayPropertySet + + Many (but not all) objects in PowerShell have a hidden property named psStandardmembers with a child property DefaultDisplayPropertySet ; this parameter reduces the properties exported to those in this set. + + + SwitchParameter + + + False + + + NoNumberConversion + + By default the command will convert all values to numbers if possible, but this isn't always desirable. -NoNumberConversion allows you to add exceptions for the conversion. + The only Wildcard allowed is * for all properties + + String[] + + String[] + + + None + + + ConditionalFormat + + One or more conditional formatting rules defined with New-ConditionalFormattingIconSet. + + Object[] + + Object[] + + + None + + + ConditionalText + + Applies a Conditional formatting rule defined with New-ConditionalText. When specific conditions are met the format is applied. + + Object[] + + Object[] + + + None + + + Style + + Takes style settings as a hash-table (which may be built with the New-ExcelStyle command) and applies them to the worksheet. If the hash-table contains a range the settings apply to the range, otherewise they apply to the whole sheet. + + Object[] + + Object[] + + + None + + + CellStyleSB + + A script block which is run at the end of the export to apply styles to cells (although it can be used for other purposes). The script block is given three paramaters; an object containing the current worksheet, the Total number of Rows and the number of the last column. + + ScriptBlock + + ScriptBlock + + + None + + + Activate + + If there is already content in the workbook, a new sheet will not be active UNLESS Activate is specified; when a PivotTable is created its sheet will be activated by this switch. + + + SwitchParameter + + + False + + + Now + + The -Now switch is a shortcut that automatically creates a temporary file, enables "AutoSize", "TableName" and "Show", and opens the file immediately. + + + SwitchParameter + + + False + + + ReturnRange + + If specified, Export-Excel returns the range of added cells in the format "A1:Z100". + + + SwitchParameter + + + False + + + PivotTotals + + By default, PivotTables have totals for each row (on the right) and for each column at the bottom. This allows just one or neither to be selected. + + String + + String + + + Both + + + NoTotalsInPivot + + In a PivotTable created from command line parameters, prevents the addition of totals to rows and columns. + + + SwitchParameter + + + False + + + ReZip + + If specified, Export-Excel will expand the contents of the .XLSX file (which is multiple files in a zip archive) and rebuild it. + + + SwitchParameter + + + False + + + + Export-Excel + + ExcelPackage + + An object representing an Excel Package - usually this is returned by specifying -PassThru allowing multiple commands to work on the same workbook without saving and reloading each time. + + ExcelPackage + + ExcelPackage + + + None + + + InputObject + + Date is usually piped into Export-Excel, but it also accepts data through the InputObject parameter + + Object + + Object + + + None + + + Calculate + + If specified, a recalculation of the worksheet will be requested before saving. + + + SwitchParameter + + + False + + + Show + + Opens the Excel file immediately after creation; convenient for viewing the results instantly without having to search for the file first. + + + SwitchParameter + + + False + + + WorksheetName + + The name of a sheet within the workbook - "Sheet1" by default. + + String + + String + + + Sheet1 + + + Password + + Sets password protection on the workbook. + + String + + String + + + None + + + ClearSheet + + If specified Export-Excel will remove any existing worksheet with the selected name. + The default behaviour is to overwrite cells in this sheet as needed (but leaving non-overwritten ones in place). + + + SwitchParameter + + + False + + + Append + + If specified data will be added to the end of an existing sheet, using the same column headings. + + + SwitchParameter + + + False + + + Title + + Text of a title to be placed in the top left cell. + + String + + String + + + None + + + TitleFillPattern + + Sets the fill pattern for the title cell. + + + None + Solid + DarkGray + MediumGray + LightGray + Gray125 + Gray0625 + DarkVertical + DarkHorizontal + DarkDown + DarkUp + DarkGrid + DarkTrellis + LightVertical + LightHorizontal + LightDown + LightUp + LightGrid + LightTrellis + + ExcelFillStyle + + ExcelFillStyle + + + Solid + + + TitleBold + + Sets the title in boldface type. + + + SwitchParameter + + + False + + + TitleSize + + Sets the point size for the title. + + Int32 + + Int32 + + + 22 + + + TitleBackgroundColor + + Sets the cell background color for the title cell. + + Object + + Object + + + None + + + IncludePivotTable + + Adds a PivotTable using the data in the worksheet. + + + SwitchParameter + + + False + + + PivotTableName + + If a PivotTable is created from command line parameters, specifies the name of the new sheet holding the pivot. Defaults to "WorksheetName-PivotTable". + + String + + String + + + None + + + PivotRows + + Name(s) of column(s) from the spreadsheet which will provide the Row name(s) in a PivotTable created from command line parameters. + + String[] + + String[] + + + None + + + PivotColumns + + Name(s) of columns from the spreadsheet which will provide the Column name(s) in a PivotTable created from command line parameters. + + String[] + + String[] + + + None + + + PivotData + + In a PivotTable created from command line parameters, the fields to use in the table body are given as a Hash-table in the form + ColumnName = Average|Count|CountNums|Max|Min|Product|None|StdDev|StdDevP|Sum|Var|VarP. + + Object + + Object + + + None + + + PivotFilter + + Name(s) columns from the spreadsheet which will provide the Filter name(s) in a PivotTable created from command line parameters. + + String[] + + String[] + + + None + + + PivotDataToColumn + + If there are multiple datasets in a PivotTable, by default they are shown as separate rows under the given row heading; this switch makes them separate columns. + + + SwitchParameter + + + False + + + PivotTableDefinition + + Instead of describing a single PivotTable with multiple command-line parameters; you can use a HashTable in the form PivotTableName = Definition; + In this table Definition is itself a Hashtable with Sheet, PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values. The New-PivotTableDefinition command will create the definition from a command line. + + Hashtable + + Hashtable + + + None + + + IncludePivotChart + + Include a chart with the PivotTable - implies -IncludePivotTable. + + + SwitchParameter + + + False + + + ChartType + + The type for PivotChart (one of Excel's defined chart types). + + + Area + Line + Pie + Bubble + ColumnClustered + ColumnStacked + ColumnStacked100 + ColumnClustered3D + ColumnStacked3D + ColumnStacked1003D + BarClustered + BarStacked + BarStacked100 + BarClustered3D + BarStacked3D + BarStacked1003D + LineStacked + LineStacked100 + LineMarkers + LineMarkersStacked + LineMarkersStacked100 + PieOfPie + PieExploded + PieExploded3D + BarOfPie + XYScatterSmooth + XYScatterSmoothNoMarkers + XYScatterLines + XYScatterLinesNoMarkers + AreaStacked + AreaStacked100 + AreaStacked3D + AreaStacked1003D + DoughnutExploded + RadarMarkers + RadarFilled + Surface + SurfaceWireframe + SurfaceTopView + SurfaceTopViewWireframe + Bubble3DEffect + StockHLC + StockOHLC + StockVHLC + StockVOHLC + CylinderColClustered + CylinderColStacked + CylinderColStacked100 + CylinderBarClustered + CylinderBarStacked + CylinderBarStacked100 + CylinderCol + ConeColClustered + ConeColStacked + ConeColStacked100 + ConeBarClustered + ConeBarStacked + ConeBarStacked100 + ConeCol + PyramidColClustered + PyramidColStacked + PyramidColStacked100 + PyramidBarClustered + PyramidBarStacked + PyramidBarStacked100 + PyramidCol + XYScatter + Radar + Doughnut + Pie3D + Line3D + Column3D + Area3D + + eChartType + + eChartType + + + Pie + + + NoLegend + + Exclude the legend from the PivotChart. + + + SwitchParameter + + + False + + + ShowCategory + + Add category labels to the PivotChart. + + + SwitchParameter + + + False + + + ShowPercent + + Add percentage labels to the PivotChart. + + + SwitchParameter + + + False + + + AutoSize + + Sizes the width of the Excel column to the maximum width needed to display all the containing data in that cell. + + + SwitchParameter + + + False + + + MaxAutoSizeRows + + Autosizing can be time consuming, so this sets a maximum number of rows to look at for the Autosize operation. Default is 1000; If 0 is specified ALL rows will be checked + + Object + + Object + + + 1000 + + + NoClobber + + Not used. Left in to avoid problems with older scripts, it may be removed in future versions. + + + SwitchParameter + + + False + + + FreezeTopRow + + Freezes headers etc. in the top row. + + + SwitchParameter + + + False + + + FreezeFirstColumn + + Freezes titles etc. in the left column. + + + SwitchParameter + + + False + + + FreezeTopRowFirstColumn + + Freezes top row and left column (equivalent to Freeze pane 2,2 ). + + + SwitchParameter + + + False + + + FreezePane + + Freezes panes at specified coordinates (in the form RowNumber, ColumnNumber). + + Int32[] + + Int32[] + + + None + + + AutoFilter + + Enables the Excel filter on the complete header row, so users can easily sort, filter and/or search the data in the selected column. + + + SwitchParameter + + + False + + + BoldTopRow + + Makes the top row boldface. + + + SwitchParameter + + + False + + + NoHeader + + Specifies that field names should not be put at the top of columns. + + + SwitchParameter + + + False + + + RangeName + + Makes the data in the worksheet a named range. + + String + + String + + + None + + + TableName + + Makes the data in the worksheet a table with a name, and applies a style to it. The name must not contain spaces. If the -Tablestyle parameter is specified without Tablename, "table1", "table2" etc. will be used. + + Object + + Object + + + None + + + TableStyle + + Selects the style for the named table - if the Tablename parameter is specified without giving a style, 'Medium6' is used as a default. + + + None + Custom + Light1 + Light2 + Light3 + Light4 + Light5 + Light6 + Light7 + Light8 + Light9 + Light10 + Light11 + Light12 + Light13 + Light14 + Light15 + Light16 + Light17 + Light18 + Light19 + Light20 + Light21 + Medium1 + Medium2 + Medium3 + Medium4 + Medium5 + Medium6 + Medium7 + Medium8 + Medium9 + Medium10 + Medium11 + Medium12 + Medium13 + Medium14 + Medium15 + Medium16 + Medium17 + Medium18 + Medium19 + Medium20 + Medium21 + Medium22 + Medium23 + Medium24 + Medium25 + Medium26 + Medium27 + Medium28 + Dark1 + Dark2 + Dark3 + Dark4 + Dark5 + Dark6 + Dark7 + Dark8 + Dark9 + Dark10 + Dark11 + + TableStyles + + TableStyles + + + Medium6 + + + Barchart + + Creates a "quick" bar chart using the first text column as labels and the first numeric column as values. + + + SwitchParameter + + + False + + + PieChart + + Creates a "quick" pie chart using the first text column as labels and the first numeric column as values. + + + SwitchParameter + + + False + + + LineChart + + Creates a "quick" line chart using the first text column as labels and the first numeric column as values. + + + SwitchParameter + + + False + + + ColumnChart + + Creates a "quick" column chart using the first text column as labels and the first numeric column as values. + + + SwitchParameter + + + False + + + ExcelChartDefinition + + A hash-table containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-Pivot] charts. This can be created with the New-ExcelChartDefinition command. + + Object[] + + Object[] + + + None + + + HideSheet + + Name(s) of Sheet(s) to hide in the workbook, supports wildcards. If the selection would cause all sheets to be hidden, the sheet being worked on will be revealed. + + String[] + + String[] + + + None + + + UnHideSheet + + Name(s) of Sheet(s) to reveal in the workbook, supports wildcards. + + String[] + + String[] + + + None + + + MoveToStart + + If specified, the worksheet will be moved to the start of the workbook. + -MoveToStart takes precedence over -MoveToEnd, -Movebefore and -MoveAfter if more than one is specified. + + + SwitchParameter + + + False + + + MoveToEnd + + If specified, the worksheet will be moved to the end of the workbook. (This is the default position for newly created sheets, but the option can be specified to move existing sheets.) + + + SwitchParameter + + + False + + + MoveBefore + + If specified, the worksheet will be moved before the nominated one (which can be a position starting from 1, or a name). + -MoveBefore takes precedence over -MoveAfter if both are specified. + + Object + + Object + + + None + + + MoveAfter + + If specified, the worksheet will be moved after the nominated one (which can be a position starting from 1, or a name or *). + If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically. + + Object + + Object + + + None + + + KillExcel + + Closes Excel without stopping to ask if work should be saved - prevents errors writing to the file because Excel has it open. + + + SwitchParameter + + + False + + + AutoNameRange + + Makes each column a named range. + + + SwitchParameter + + + False + + + StartRow + + Row to start adding data. 1 by default. Row 1 will contain the title, if any is specifed. Then headers will appear (Unless -No header is specified) then the data appears. + + Int32 + + Int32 + + + 1 + + + StartColumn + + Column to start adding data - 1 by default. + + Int32 + + Int32 + + + 1 + + + PassThru + + If specified, Export-Excel returns an object representing the Excel package without saving the package first. To save, you must either use the Close-ExcelPackage command, or send the package object back to Export-Excel which will save and close the file, or use the object's .Save() or SaveAs() method. + + + SwitchParameter + + + False + + + Numberformat + + Formats all values that can be converted to a number to the format specified. For examples: + + '0' integer (not really needed unless you need to round numbers, Excel will use default cell properties). + '#' integer without displaying the number 0 in the cell. + '0.0' number with 1 decimal place. + '0.00' number with 2 decimal places. + '#,##0.00' number with 2 decimal places and thousand-separator. + '€#,##0.00' number with 2 decimal places and thousand-separator and money-symbol. + '0%' number with 2 decimal places and thousand-separator and money-symbol. + '[Blue]$#,##0.00;[Red]-$#,##0.00' + blue for positive numbers and red for negative numbers; Both proceeded by a '$' sign + + String + + String + + + General + + + ExcludeProperty + + Specifies properties which may exist in the target data but should not be placed on the worksheet. + + String[] + + String[] + + + None + + + NoAliasOrScriptPropeties + + Some objects in PowerShell duplicate existing properties by adding aliases, or have Script properties which may take a long time to return a value and slow the export down, if specified this option removes these properties + + + SwitchParameter + + + False + + + DisplayPropertySet + + Many (but not all) objects in PowerShell have a hidden property named psStandardmembers with a child property DefaultDisplayPropertySet ; this parameter reduces the properties exported to those in this set. + + + SwitchParameter + + + False + + + NoNumberConversion + + By default the command will convert all values to numbers if possible, but this isn't always desirable. -NoNumberConversion allows you to add exceptions for the conversion. + The only Wildcard allowed is * for all properties + + String[] + + String[] + + + None + + + ConditionalFormat + + One or more conditional formatting rules defined with New-ConditionalFormattingIconSet. + + Object[] + + Object[] + + + None + + + ConditionalText + + Applies a Conditional formatting rule defined with New-ConditionalText. When specific conditions are met the format is applied. + + Object[] + + Object[] + + + None + + + Style + + Takes style settings as a hash-table (which may be built with the New-ExcelStyle command) and applies them to the worksheet. If the hash-table contains a range the settings apply to the range, otherewise they apply to the whole sheet. + + Object[] + + Object[] + + + None + + + CellStyleSB + + A script block which is run at the end of the export to apply styles to cells (although it can be used for other purposes). The script block is given three paramaters; an object containing the current worksheet, the Total number of Rows and the number of the last column. + + ScriptBlock + + ScriptBlock + + + None + + + Activate + + If there is already content in the workbook, a new sheet will not be active UNLESS Activate is specified; when a PivotTable is created its sheet will be activated by this switch. + + + SwitchParameter + + + False + + + ReturnRange + + If specified, Export-Excel returns the range of added cells in the format "A1:Z100". + + + SwitchParameter + + + False + + + PivotTotals + + By default, PivotTables have totals for each row (on the right) and for each column at the bottom. This allows just one or neither to be selected. + + String + + String + + + Both + + + NoTotalsInPivot + + In a PivotTable created from command line parameters, prevents the addition of totals to rows and columns. + + + SwitchParameter + + + False + + + ReZip + + If specified, Export-Excel will expand the contents of the .XLSX file (which is multiple files in a zip archive) and rebuild it. + + + SwitchParameter + + + False + + + + + + Path + + Path to a new or existing .XLSX file. + + String + + String + + + None + + + ExcelPackage + + An object representing an Excel Package - usually this is returned by specifying -PassThru allowing multiple commands to work on the same workbook without saving and reloading each time. + + ExcelPackage + + ExcelPackage + + + None + + + InputObject + + Date is usually piped into Export-Excel, but it also accepts data through the InputObject parameter + + Object + + Object + + + None + + + Calculate + + If specified, a recalculation of the worksheet will be requested before saving. + + SwitchParameter + + SwitchParameter + + + False + + + Show + + Opens the Excel file immediately after creation; convenient for viewing the results instantly without having to search for the file first. + + SwitchParameter + + SwitchParameter + + + False + + + WorksheetName + + The name of a sheet within the workbook - "Sheet1" by default. + + String + + String + + + Sheet1 + + + Password + + Sets password protection on the workbook. + + String + + String + + + None + + + ClearSheet + + If specified Export-Excel will remove any existing worksheet with the selected name. + The default behaviour is to overwrite cells in this sheet as needed (but leaving non-overwritten ones in place). + + SwitchParameter + + SwitchParameter + + + False + + + Append + + If specified data will be added to the end of an existing sheet, using the same column headings. + + SwitchParameter + + SwitchParameter + + + False + + + Title + + Text of a title to be placed in the top left cell. + + String + + String + + + None + + + TitleFillPattern + + Sets the fill pattern for the title cell. + + ExcelFillStyle + + ExcelFillStyle + + + Solid + + + TitleBold + + Sets the title in boldface type. + + SwitchParameter + + SwitchParameter + + + False + + + TitleSize + + Sets the point size for the title. + + Int32 + + Int32 + + + 22 + + + TitleBackgroundColor + + Sets the cell background color for the title cell. + + Object + + Object + + + None + + + IncludePivotTable + + Adds a PivotTable using the data in the worksheet. + + SwitchParameter + + SwitchParameter + + + False + + + PivotTableName + + If a PivotTable is created from command line parameters, specifies the name of the new sheet holding the pivot. Defaults to "WorksheetName-PivotTable". + + String + + String + + + None + + + PivotRows + + Name(s) of column(s) from the spreadsheet which will provide the Row name(s) in a PivotTable created from command line parameters. + + String[] + + String[] + + + None + + + PivotColumns + + Name(s) of columns from the spreadsheet which will provide the Column name(s) in a PivotTable created from command line parameters. + + String[] + + String[] + + + None + + + PivotData + + In a PivotTable created from command line parameters, the fields to use in the table body are given as a Hash-table in the form + ColumnName = Average|Count|CountNums|Max|Min|Product|None|StdDev|StdDevP|Sum|Var|VarP. + + Object + + Object + + + None + + + PivotFilter + + Name(s) columns from the spreadsheet which will provide the Filter name(s) in a PivotTable created from command line parameters. + + String[] + + String[] + + + None + + + PivotDataToColumn + + If there are multiple datasets in a PivotTable, by default they are shown as separate rows under the given row heading; this switch makes them separate columns. + + SwitchParameter + + SwitchParameter + + + False + + + PivotTableDefinition + + Instead of describing a single PivotTable with multiple command-line parameters; you can use a HashTable in the form PivotTableName = Definition; + In this table Definition is itself a Hashtable with Sheet, PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values. The New-PivotTableDefinition command will create the definition from a command line. + + Hashtable + + Hashtable + + + None + + + IncludePivotChart + + Include a chart with the PivotTable - implies -IncludePivotTable. + + SwitchParameter + + SwitchParameter + + + False + + + ChartType + + The type for PivotChart (one of Excel's defined chart types). + + eChartType + + eChartType + + + Pie + + + NoLegend + + Exclude the legend from the PivotChart. + + SwitchParameter + + SwitchParameter + + + False + + + ShowCategory + + Add category labels to the PivotChart. + + SwitchParameter + + SwitchParameter + + + False + + + ShowPercent + + Add percentage labels to the PivotChart. + + SwitchParameter + + SwitchParameter + + + False + + + AutoSize + + Sizes the width of the Excel column to the maximum width needed to display all the containing data in that cell. + + SwitchParameter + + SwitchParameter + + + False + + + MaxAutoSizeRows + + Autosizing can be time consuming, so this sets a maximum number of rows to look at for the Autosize operation. Default is 1000; If 0 is specified ALL rows will be checked + + Object + + Object + + + 1000 + + + NoClobber + + Not used. Left in to avoid problems with older scripts, it may be removed in future versions. + + SwitchParameter + + SwitchParameter + + + False + + + FreezeTopRow + + Freezes headers etc. in the top row. + + SwitchParameter + + SwitchParameter + + + False + + + FreezeFirstColumn + + Freezes titles etc. in the left column. + + SwitchParameter + + SwitchParameter + + + False + + + FreezeTopRowFirstColumn + + Freezes top row and left column (equivalent to Freeze pane 2,2 ). + + SwitchParameter + + SwitchParameter + + + False + + + FreezePane + + Freezes panes at specified coordinates (in the form RowNumber, ColumnNumber). + + Int32[] + + Int32[] + + + None + + + AutoFilter + + Enables the Excel filter on the complete header row, so users can easily sort, filter and/or search the data in the selected column. + + SwitchParameter + + SwitchParameter + + + False + + + BoldTopRow + + Makes the top row boldface. + + SwitchParameter + + SwitchParameter + + + False + + + NoHeader + + Specifies that field names should not be put at the top of columns. + + SwitchParameter + + SwitchParameter + + + False + + + RangeName + + Makes the data in the worksheet a named range. + + String + + String + + + None + + + TableName + + Makes the data in the worksheet a table with a name, and applies a style to it. The name must not contain spaces. If the -Tablestyle parameter is specified without Tablename, "table1", "table2" etc. will be used. + + Object + + Object + + + None + + + TableStyle + + Selects the style for the named table - if the Tablename parameter is specified without giving a style, 'Medium6' is used as a default. + + TableStyles + + TableStyles + + + Medium6 + + + Barchart + + Creates a "quick" bar chart using the first text column as labels and the first numeric column as values. + + SwitchParameter + + SwitchParameter + + + False + + + PieChart + + Creates a "quick" pie chart using the first text column as labels and the first numeric column as values. + + SwitchParameter + + SwitchParameter + + + False + + + LineChart + + Creates a "quick" line chart using the first text column as labels and the first numeric column as values. + + SwitchParameter + + SwitchParameter + + + False + + + ColumnChart + + Creates a "quick" column chart using the first text column as labels and the first numeric column as values. + + SwitchParameter + + SwitchParameter + + + False + + + ExcelChartDefinition + + A hash-table containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-Pivot] charts. This can be created with the New-ExcelChartDefinition command. + + Object[] + + Object[] + + + None + + + HideSheet + + Name(s) of Sheet(s) to hide in the workbook, supports wildcards. If the selection would cause all sheets to be hidden, the sheet being worked on will be revealed. + + String[] + + String[] + + + None + + + UnHideSheet + + Name(s) of Sheet(s) to reveal in the workbook, supports wildcards. + + String[] + + String[] + + + None + + + MoveToStart + + If specified, the worksheet will be moved to the start of the workbook. + -MoveToStart takes precedence over -MoveToEnd, -Movebefore and -MoveAfter if more than one is specified. + + SwitchParameter + + SwitchParameter + + + False + + + MoveToEnd + + If specified, the worksheet will be moved to the end of the workbook. (This is the default position for newly created sheets, but the option can be specified to move existing sheets.) + + SwitchParameter + + SwitchParameter + + + False + + + MoveBefore + + If specified, the worksheet will be moved before the nominated one (which can be a position starting from 1, or a name). + -MoveBefore takes precedence over -MoveAfter if both are specified. + + Object + + Object + + + None + + + MoveAfter + + If specified, the worksheet will be moved after the nominated one (which can be a position starting from 1, or a name or *). + If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically. + + Object + + Object + + + None + + + KillExcel + + Closes Excel without stopping to ask if work should be saved - prevents errors writing to the file because Excel has it open. + + SwitchParameter + + SwitchParameter + + + False + + + AutoNameRange + + Makes each column a named range. + + SwitchParameter + + SwitchParameter + + + False + + + StartRow + + Row to start adding data. 1 by default. Row 1 will contain the title, if any is specifed. Then headers will appear (Unless -No header is specified) then the data appears. + + Int32 + + Int32 + + + 1 + + + StartColumn + + Column to start adding data - 1 by default. + + Int32 + + Int32 + + + 1 + + + PassThru + + If specified, Export-Excel returns an object representing the Excel package without saving the package first. To save, you must either use the Close-ExcelPackage command, or send the package object back to Export-Excel which will save and close the file, or use the object's .Save() or SaveAs() method. + + SwitchParameter + + SwitchParameter + + + False + + + Numberformat + + Formats all values that can be converted to a number to the format specified. For examples: + + '0' integer (not really needed unless you need to round numbers, Excel will use default cell properties). + '#' integer without displaying the number 0 in the cell. + '0.0' number with 1 decimal place. + '0.00' number with 2 decimal places. + '#,##0.00' number with 2 decimal places and thousand-separator. + '€#,##0.00' number with 2 decimal places and thousand-separator and money-symbol. + '0%' number with 2 decimal places and thousand-separator and money-symbol. + '[Blue]$#,##0.00;[Red]-$#,##0.00' + blue for positive numbers and red for negative numbers; Both proceeded by a '$' sign + + String + + String + + + General + + + ExcludeProperty + + Specifies properties which may exist in the target data but should not be placed on the worksheet. + + String[] + + String[] + + + None + + + NoAliasOrScriptPropeties + + Some objects in PowerShell duplicate existing properties by adding aliases, or have Script properties which may take a long time to return a value and slow the export down, if specified this option removes these properties + + SwitchParameter + + SwitchParameter + + + False + + + DisplayPropertySet + + Many (but not all) objects in PowerShell have a hidden property named psStandardmembers with a child property DefaultDisplayPropertySet ; this parameter reduces the properties exported to those in this set. + + SwitchParameter + + SwitchParameter + + + False + + + NoNumberConversion + + By default the command will convert all values to numbers if possible, but this isn't always desirable. -NoNumberConversion allows you to add exceptions for the conversion. + The only Wildcard allowed is * for all properties + + String[] + + String[] + + + None + + + ConditionalFormat + + One or more conditional formatting rules defined with New-ConditionalFormattingIconSet. + + Object[] + + Object[] + + + None + + + ConditionalText + + Applies a Conditional formatting rule defined with New-ConditionalText. When specific conditions are met the format is applied. + + Object[] + + Object[] + + + None + + + Style + + Takes style settings as a hash-table (which may be built with the New-ExcelStyle command) and applies them to the worksheet. If the hash-table contains a range the settings apply to the range, otherewise they apply to the whole sheet. + + Object[] + + Object[] + + + None + + + CellStyleSB + + A script block which is run at the end of the export to apply styles to cells (although it can be used for other purposes). The script block is given three paramaters; an object containing the current worksheet, the Total number of Rows and the number of the last column. + + ScriptBlock + + ScriptBlock + + + None + + + Activate + + If there is already content in the workbook, a new sheet will not be active UNLESS Activate is specified; when a PivotTable is created its sheet will be activated by this switch. + + SwitchParameter + + SwitchParameter + + + False + + + Now + + The -Now switch is a shortcut that automatically creates a temporary file, enables "AutoSize", "TableName" and "Show", and opens the file immediately. + + SwitchParameter + + SwitchParameter + + + False + + + ReturnRange + + If specified, Export-Excel returns the range of added cells in the format "A1:Z100". + + SwitchParameter + + SwitchParameter + + + False + + + PivotTotals + + By default, PivotTables have totals for each row (on the right) and for each column at the bottom. This allows just one or neither to be selected. + + String + + String + + + Both + + + NoTotalsInPivot + + In a PivotTable created from command line parameters, prevents the addition of totals to rows and columns. + + SwitchParameter + + SwitchParameter + + + False + + + ReZip + + If specified, Export-Excel will expand the contents of the .XLSX file (which is multiple files in a zip archive) and rebuild it. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + OfficeOpenXml.ExcelPackage + + + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> Get-Process | Export-Excel .\Test.xlsx -show + + Export all the processes to the Excel file 'Test.xlsx' and open the file immediately. + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\> $ExcelParams = @{ + Path = $env:TEMP + '\Excel.xlsx' + Show = $true + Verbose = $true +} +PS\> Remove-Item -Path $ExcelParams.Path -Force -EA Ignore +PS\> Write-Output -1 668 34 777 860 -0.5 119 -0.1 234 788 | + Export-Excel @ExcelParams -NumberFormat ' [Blue$#,##0.00; [Red]-$#,##0.00' + + Exports all data to the Excel file 'Excel.xslx' and colors the negative values in Red and the positive values in Blue. + It will also add a dollar sign in front of the numbers which use a thousand seperator and display to two decimal places. + + + + -------------------------- EXAMPLE 3 -------------------------- + PS\> $ExcelParams = @{ + Path = $env:TEMP + '\Excel.xlsx' + Show = $true + Verbose = $true +} +PS\> Remove-Item -Path $ExcelParams.Path -Force -EA Ignore +PS\> [PSCustOmobject][Ordered]@{ + Date = Get-Date + Formula1 = '=SUM(F2:G2)' + String1 = 'My String' + String2 = 'a' + IPAddress = '10.10.25.5' + Number1 = '07670' + Number2 = '0,26' + Number3 = '1.555,83' + Number4 = '1.2' + Number5 = '-31' + PhoneNr1 = '+32 44' + PhoneNr2 = '+32 4 4444 444' + PhoneNr3 = '+3244444444' +} | Export-Excel @ExcelParams -NoNumberConversion IPAddress, Number1 + + Exports all data to the Excel file "Excel.xlsx" and tries to convert all values to numbers where possible except for "IPAddress" and "Number1", which are stored in the sheet 'as is', without being converted to a number. + + + + -------------------------- EXAMPLE 4 -------------------------- + PS\> $ExcelParams = @{ + Path = $env:TEMP + '\Excel.xlsx' + Show = $true + Verbose = $true +} +PS\> Remove-Item -Path $ExcelParams.Path -Force -EA Ignore +PS\> [PSCustOmobject][Ordered]@{ + Date = Get-Date + Formula1 = '=SUM(F2:G2)' + String1 = 'My String' + String2 = 'a' + IPAddress = '10.10.25.5' + Number1 = '07670' + Number2 = '0,26' + Number3 = '1.555,83' + Number4 = '1.2' + Number5 = '-31' + PhoneNr1 = '+32 44' + PhoneNr2 = '+32 4 4444 444' + PhoneNr3 = '+3244444444' +} | Export-Excel @ExcelParams -NoNumberConversion * + + Exports all data to the Excel file 'Excel.xslx' as is, no number conversion will take place. This means that Excel will show the exact same data that you handed over to the 'Export-Excel' function. + + + + -------------------------- EXAMPLE 5 -------------------------- + PS\> $ExcelParams = @{ + Path = $env:TEMP + '\Excel.xlsx' + Show = $true + Verbose = $true +} +PS\> Remove-Item -Path $ExcelParams.Path -Force -EA Ignore +PS\> Write-Output 489 668 299 777 860 151 119 497 234 788 | + Export-Excel @ExcelParams -ConditionalText $( + New-ConditionalText -ConditionalType GreaterThan 525 -ConditionalTextColor DarkRed -BackgroundColor LightPink + ) + + Exports data that will have a Conditional Formatting rule in Excel that will show cells with a value is greater than 525, with a background fill color of "LightPink" and the text in "DarkRed". + Where the condition is not met the color will be the default, black text on a white background. + + + + -------------------------- EXAMPLE 6 -------------------------- + PS\> $ExcelParams = @{ + Path = $env:TEMP + '\Excel.xlsx' + Show = $true + Verbose = $true +} +PS\> Remove-Item -Path $ExcelParams.Path -Force -EA Ignore +PS\> Get-Service | Select-Object -Property Name, Status, DisplayName, ServiceName | + Export-Excel @ExcelParams -ConditionalText $( + New-ConditionalText Stop DarkRed LightPink + New-ConditionalText Running Blue Cyan + ) + + Exports all services to an Excel sheet, setting a Conditional formatting rule that will set the background fill color to "LightPink" and the text color to "DarkRed" when the value contains the word "Stop". + If the value contains the word "Running" it will have a background fill color of "Cyan" and text colored 'Blue'. + If neither condition is met, the color will be the default, black text on a white background. + + + + -------------------------- EXAMPLE 7 -------------------------- + PS\> $ExcelParams = @{ + Path = $env:TEMP + '\Excel.xlsx' + Show = $true + Verbose = $true + } +PS\> Remove-Item -Path $ExcelParams.Path -Force -EA Ignore +PS\> $Array = @() +PS\> $Obj1 = [PSCustomObject]@{ + Member1 = 'First' + Member2 = 'Second' +} + +PS\> $Obj2 = [PSCustomObject]@{ + Member1 = 'First' + Member2 = 'Second' + Member3 = 'Third' +} + + PS\> $Obj3 = [PSCustomObject]@{ + Member1 = 'First' + Member2 = 'Second' + Member3 = 'Third' + Member4 = 'Fourth' +} + +PS\> $Array = $Obj1, $Obj2, $Obj3 +PS\> $Array | Out-GridView -Title 'Not showing Member3 and Member4' +PS\> $Array | Update-FirstObjectProperties | Export-Excel @ExcelParams -WorksheetName Numbers + + Updates the first object of the array by adding property 'Member3' and 'Member4'. Afterwards, all objects are exported to an Excel file and all column headers are visible. + + + + -------------------------- EXAMPLE 8 -------------------------- + PS\> Get-Process | Export-Excel .\test.xlsx -WorksheetName Processes -IncludePivotTable -Show -PivotRows Company -PivotData PM + + + + + + -------------------------- EXAMPLE 9 -------------------------- + PS\> Get-Process | Export-Excel .\test.xlsx -WorksheetName Processes -ChartType PieExploded3D -IncludePivotChart -IncludePivotTable -Show -PivotRows Company -PivotData PM + + + + + + -------------------------- EXAMPLE 10 -------------------------- + PS\> Get-Service | Export-Excel 'c:\temp\test.xlsx' -Show -IncludePivotTable -PivotRows status -PivotData @{status='count'} + + + + + + -------------------------- EXAMPLE 11 -------------------------- + PS\> $pt = [ordered]@{} +PS\> $pt.pt1=@{ + SourceWorkSheet = 'Sheet1'; + PivotRows = 'Status' + PivotData = @{'Status'='count'} + IncludePivotChart = $true + ChartType = 'BarClustered3D' +} +PS\> $pt.pt2=@ + SourceWorkSheet = 'Sheet2'; + PivotRows = 'Company' + PivotData = @{'Company'='count'} + IncludePivotChart = $true + ChartType = 'PieExploded3D' +} +PS\> Remove-Item -Path .\test.xlsx +PS\> Get-Service | Select-Object -Property Status,Name,DisplayName,StartType | Export-Excel -Path .\test.xlsx -AutoSize +PS\> Get-Process | Select-Object -Property Name,Company,Handles,CPU,VM | Export-Excel -Path .\test.xlsx -AutoSize -WorksheetName 'sheet2' +PS\> Export-Excel -Path .\test.xlsx -PivotTableDefinition $pt -Show + + This example defines two PivotTables. + Then it puts Service data on Sheet1 with one call to Export-Excel and Process Data on sheet2 with a second call to Export-Excel. + The third and final call adds the two PivotTables and opens the spreadsheet in Excel. + + + + -------------------------- EXAMPLE 12 -------------------------- + PS\> Remove-Item -Path .\test.xlsx +PS\> $excel = Get-Service | Select-Object -Property Status,Name,DisplayName,StartType | Export-Excel -Path .\test.xlsx -PassThru +PS\> $excel.Workbook.Worksheets ["Sheet1"].Row(1).style.font.bold = $true +PS\> $excel.Workbook.Worksheets ["Sheet1"].Column(3 ).width = 29 +PS\> $excel.Workbook.Worksheets ["Sheet1"].Column(3 ).Style.wraptext = $true +PS\> $excel.Save() +PS\> $excel.Dispose() +PS\> Start-Process .\test.xlsx + + This example uses -PassThru. + It puts service information into sheet1 of the workbook and saves the ExcelPackage object in $Excel. + It then uses the package object to apply formatting, and then saves the workbook and disposes of the object, before loading the document in Excel. + Note: Other commands in the module remove the need to work directly with the package object in this way. + + + + -------------------------- EXAMPLE 13 -------------------------- + PS\> Remove-Item -Path .\test.xlsx -ErrorAction Ignore +PS\> $excel = Get-Process | Select-Object -Property Name,Company,Handles,CPU,PM,NPM,WS | + Export-Excel -Path .\test.xlsx -ClearSheet -WorksheetName "Processes" -PassThru +PS\> $sheet = $excel.Workbook.Worksheets ["Processes"] +PS\> $sheet.Column(1) | Set-ExcelRange -Bold -AutoFit +PS\> $sheet.Column(2) | Set-ExcelRange -Width 29 -WrapText +PS\> $sheet.Column(3) | Set-ExcelRange -HorizontalAlignment Right -NFormat "#,###" +PS\> Set-ExcelRange -Address $sheet.Cells ["E1:H1048576"] -HorizontalAlignment Right -NFormat "#,###" +PS\> Set-ExcelRange -Address $sheet.Column(4) -HorizontalAlignment Right -NFormat "#,##0.0" -Bold +PS\> Set-ExcelRange -Address $sheet.Row(1) -Bold -HorizontalAlignment Center +PS\> Add-ConditionalFormatting -WorkSheet $sheet -Range "D2:D1048576" -DataBarColor Red +PS\> Add-ConditionalFormatting -WorkSheet $sheet -Range "G2:G1048576" -RuleType GreaterThan -ConditionValue "104857600" -ForeGroundColor Red +PS\> foreach ($c in 5..9) {Set-ExcelRange -Address $sheet.Column($c) -AutoFit } +PS\> Export-Excel -ExcelPackage $excel -WorksheetName "Processes" -IncludePivotChart -ChartType ColumnClustered -NoLegend -PivotRows company -PivotData @{'Name'='Count'} -Show + + This a more sophisticated version of the previous example showing different ways of using Set-ExcelRange, and also adding conditional formatting. + In the final command a PivotChart is added and the workbook is opened in Excel. + + + + -------------------------- EXAMPLE 14 -------------------------- + PS\> 0..360 | ForEach-Object {[pscustomobject][ordered]@{X=$_; Sinx="=Sin(Radians(x)) "} } | + Export-Excel -now -LineChart -AutoNameRange + + Creates a line chart showing the value of Sine(x) for values of X between 0 and 360 degrees. + + + + -------------------------- EXAMPLE 15 -------------------------- + PS\> Invoke-Sqlcmd -ServerInstance localhost\DEFAULT -Database AdventureWorks2014 -Query "select * from sys.tables" -OutputAs DataRows | + Export-Excel -Path .\SysTables_AdventureWorks2014.xlsx -WorksheetName Tables + + Runs a query against a SQL Server database and outputs the resulting rows as DataRows using the -OutputAs parameter. The results are then piped to the Export-Excel function. + NOTE: You need to install the SqlServer module from the PowerShell Gallery in order to get the -OutputAs parameter for the Invoke-Sqlcmd cmdlet. + + + + + + https://github.com/dfinke/ImportExcel + https://github.com/dfinke/ImportExcel + + + + + + Get-ExcelSheetInfo + Get + ExcelSheetInfo + + Get worksheet names and their indices of an Excel workbook. + + + + The Get-ExcelSheetInfo cmdlet gets worksheet names and their indices of an Excel workbook. + + + + Get-ExcelSheetInfo + + Path + + Specifies the path to the Excel file. (This parameter is required.) + + Object + + Object + + + None + + + + + + Path + + Specifies the path to the Excel file. (This parameter is required.) + + Object + + Object + + + None + + + + + + + CHANGELOG 2016/01/07 Added Created by Johan Akerstrom (https://github.com/CosmosKey) + + + + + -------------------------- EXAMPLE 1 -------------------------- + Get-ExcelSheetInfo .\Test.xlsx + + + + + + + + https://github.com/dfinke/ImportExcel + https://github.com/dfinke/ImportExcel + + + + + + Get-ExcelWorkbookInfo + Get + ExcelWorkbookInfo + + Retrieve information of an Excel workbook. + + + + The Get-ExcelWorkbookInfo cmdlet retrieves information (LastModifiedBy, LastPrinted, Created, Modified, ...) fron an Excel workbook. These are the same details that are visible in Windows Explorer when right clicking the Excel file, selecting Properties and check the Details tabpage. + + + + Get-ExcelWorkbookInfo + + Path + + Specifies the path to the Excel file. This parameter is required. + + String + + String + + + None + + + + + + Path + + Specifies the path to the Excel file. This parameter is required. + + String + + String + + + None + + + + + + + CHANGELOG 2016/01/07 Added Created by Johan Akerstrom (https://github.com/CosmosKey) + + + + + -------------------------- EXAMPLE 1 -------------------------- + Get-ExcelWorkbookInfo .\Test.xlsx + + CorePropertiesXml : #document Title : Subject : Author : Konica Minolta User Comments : Keywords : LastModifiedBy : Bond, James (London) GBR LastPrinted : 2017-01-21T12:36:11Z Created : 17/01/2017 13:51:32 Category : Status : ExtendedPropertiesXml : #document Application : Microsoft Excel HyperlinkBase : AppVersion : 14.0300 Company : Secret Service Manager : Modified : 10/02/2017 12:45:37 CustomPropertiesXml : #document + + + + + + https://github.com/dfinke/ImportExcel + https://github.com/dfinke/ImportExcel + + + + + + Import-Excel + Import + Excel + + Create custom objects from the rows in an Excel worksheet. + + + + The Import-Excel cmdlet creates custom objects from the rows in an Excel worksheet. Each row is represented as one object. + This is possible without installing Microsoft Excel by using the .NET library 'EPPLus.dll'. + By default, the property names of the objects are retrieved from the column headers. Because an object cannot have a blank property name, only columns with column headers will be imported. + If the default behavior is not desired and you want to import the complete worksheet 'as is', the parameter '-NoHeader' can be used. In case you want to provide your own property names, you can use the parameter '-HeaderName'. + + + + Import-Excel + + Path + + Specifies the path to the Excel file. + + String + + String + + + None + + + WorksheetName + + Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported. + + String + + String + + + None + + + NoHeader + + Automatically generate property names (P1, P2, P3, ..) instead of the ones defined in the column headers of the TopRow. + This switch is best used when you want to import the complete worksheet 'as is' and are not concerned with the property names. + + + SwitchParameter + + + False + + + StartRow + + The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. + When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. If either is provided, the property names are automatically created and this row will be treated as a regular row containing data. + + Int32 + + Int32 + + + 1 + + + EndRow + + By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row. + + Int32 + + Int32 + + + 0 + + + StartColumn + + The number of the first column to read data from (1 by default). + + Int32 + + Int32 + + + 1 + + + EndColumn + + By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number. + + Int32 + + Int32 + + + 0 + + + DataOnly + + Import only rows and columns that contain data, empty rows and empty columns are not imported. + + + SwitchParameter + + + False + + + AsText + + Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. (* is supported as a wildcard.) + + String[] + + String[] + + + None + + + Password + + Accepts a string that will be used to open a password protected Excel file. + + String + + String + + + None + + + + Import-Excel + + Path + + Specifies the path to the Excel file. + + String + + String + + + None + + + WorksheetName + + Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported. + + String + + String + + + None + + + HeaderName + + Specifies custom property names to use, instead of the values defined in the column headers of the TopRow. + If you provide fewer header names than there are columns of data in the worksheet, then data will only be imported from that number of columns - the others will be ignored. + If you provide more header names than there are columns of data in the worksheet, it will result in blank properties being added to the objects returned. + + String[] + + String[] + + + None + + + StartRow + + The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. + When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. If either is provided, the property names are automatically created and this row will be treated as a regular row containing data. + + Int32 + + Int32 + + + 1 + + + EndRow + + By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row. + + Int32 + + Int32 + + + 0 + + + StartColumn + + The number of the first column to read data from (1 by default). + + Int32 + + Int32 + + + 1 + + + EndColumn + + By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number. + + Int32 + + Int32 + + + 0 + + + DataOnly + + Import only rows and columns that contain data, empty rows and empty columns are not imported. + + + SwitchParameter + + + False + + + AsText + + Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. (* is supported as a wildcard.) + + String[] + + String[] + + + None + + + Password + + Accepts a string that will be used to open a password protected Excel file. + + String + + String + + + None + + + + Import-Excel + + Path + + Specifies the path to the Excel file. + + String + + String + + + None + + + WorksheetName + + Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported. + + String + + String + + + None + + + StartRow + + The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. + When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. If either is provided, the property names are automatically created and this row will be treated as a regular row containing data. + + Int32 + + Int32 + + + 1 + + + EndRow + + By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row. + + Int32 + + Int32 + + + 0 + + + StartColumn + + The number of the first column to read data from (1 by default). + + Int32 + + Int32 + + + 1 + + + EndColumn + + By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number. + + Int32 + + Int32 + + + 0 + + + DataOnly + + Import only rows and columns that contain data, empty rows and empty columns are not imported. + + + SwitchParameter + + + False + + + AsText + + Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. (* is supported as a wildcard.) + + String[] + + String[] + + + None + + + Password + + Accepts a string that will be used to open a password protected Excel file. + + String + + String + + + None + + + + Import-Excel + + WorksheetName + + Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported. + + String + + String + + + None + + + ExcelPackage + + Instead of specifying a path, provides an Excel Package object (from Open-ExcelPackage). Using this avoids re-reading the whole file when importing multiple parts of it. + To allow multiple read operations Import-Excel does NOT close the package, and you should use Close-ExcelPackage -noSave to close it. + + ExcelPackage + + ExcelPackage + + + None + + + NoHeader + + Automatically generate property names (P1, P2, P3, ..) instead of the ones defined in the column headers of the TopRow. + This switch is best used when you want to import the complete worksheet 'as is' and are not concerned with the property names. + + + SwitchParameter + + + False + + + StartRow + + The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. + When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. If either is provided, the property names are automatically created and this row will be treated as a regular row containing data. + + Int32 + + Int32 + + + 1 + + + EndRow + + By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row. + + Int32 + + Int32 + + + 0 + + + StartColumn + + The number of the first column to read data from (1 by default). + + Int32 + + Int32 + + + 1 + + + EndColumn + + By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number. + + Int32 + + Int32 + + + 0 + + + DataOnly + + Import only rows and columns that contain data, empty rows and empty columns are not imported. + + + SwitchParameter + + + False + + + AsText + + Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. (* is supported as a wildcard.) + + String[] + + String[] + + + None + + + Password + + Accepts a string that will be used to open a password protected Excel file. + + String + + String + + + None + + + + Import-Excel + + WorksheetName + + Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported. + + String + + String + + + None + + + ExcelPackage + + Instead of specifying a path, provides an Excel Package object (from Open-ExcelPackage). Using this avoids re-reading the whole file when importing multiple parts of it. + To allow multiple read operations Import-Excel does NOT close the package, and you should use Close-ExcelPackage -noSave to close it. + + ExcelPackage + + ExcelPackage + + + None + + + HeaderName + + Specifies custom property names to use, instead of the values defined in the column headers of the TopRow. + If you provide fewer header names than there are columns of data in the worksheet, then data will only be imported from that number of columns - the others will be ignored. + If you provide more header names than there are columns of data in the worksheet, it will result in blank properties being added to the objects returned. + + String[] + + String[] + + + None + + + StartRow + + The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. + When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. If either is provided, the property names are automatically created and this row will be treated as a regular row containing data. + + Int32 + + Int32 + + + 1 + + + EndRow + + By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row. + + Int32 + + Int32 + + + 0 + + + StartColumn + + The number of the first column to read data from (1 by default). + + Int32 + + Int32 + + + 1 + + + EndColumn + + By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number. + + Int32 + + Int32 + + + 0 + + + DataOnly + + Import only rows and columns that contain data, empty rows and empty columns are not imported. + + + SwitchParameter + + + False + + + AsText + + Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. (* is supported as a wildcard.) + + String[] + + String[] + + + None + + + Password + + Accepts a string that will be used to open a password protected Excel file. + + String + + String + + + None + + + + Import-Excel + + WorksheetName + + Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported. + + String + + String + + + None + + + ExcelPackage + + Instead of specifying a path, provides an Excel Package object (from Open-ExcelPackage). Using this avoids re-reading the whole file when importing multiple parts of it. + To allow multiple read operations Import-Excel does NOT close the package, and you should use Close-ExcelPackage -noSave to close it. + + ExcelPackage + + ExcelPackage + + + None + + + StartRow + + The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. + When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. If either is provided, the property names are automatically created and this row will be treated as a regular row containing data. + + Int32 + + Int32 + + + 1 + + + EndRow + + By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row. + + Int32 + + Int32 + + + 0 + + + StartColumn + + The number of the first column to read data from (1 by default). + + Int32 + + Int32 + + + 1 + + + EndColumn + + By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number. + + Int32 + + Int32 + + + 0 + + + DataOnly + + Import only rows and columns that contain data, empty rows and empty columns are not imported. + + + SwitchParameter + + + False + + + AsText + + Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. (* is supported as a wildcard.) + + String[] + + String[] + + + None + + + Password + + Accepts a string that will be used to open a password protected Excel file. + + String + + String + + + None + + + + + + Path + + Specifies the path to the Excel file. + + String + + String + + + None + + + ExcelPackage + + Instead of specifying a path, provides an Excel Package object (from Open-ExcelPackage). Using this avoids re-reading the whole file when importing multiple parts of it. + To allow multiple read operations Import-Excel does NOT close the package, and you should use Close-ExcelPackage -noSave to close it. + + ExcelPackage + + ExcelPackage + + + None + + + WorksheetName + + Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported. + + String + + String + + + None + + + HeaderName + + Specifies custom property names to use, instead of the values defined in the column headers of the TopRow. + If you provide fewer header names than there are columns of data in the worksheet, then data will only be imported from that number of columns - the others will be ignored. + If you provide more header names than there are columns of data in the worksheet, it will result in blank properties being added to the objects returned. + + String[] + + String[] + + + None + + + NoHeader + + Automatically generate property names (P1, P2, P3, ..) instead of the ones defined in the column headers of the TopRow. + This switch is best used when you want to import the complete worksheet 'as is' and are not concerned with the property names. + + SwitchParameter + + SwitchParameter + + + False + + + StartRow + + The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. + When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. If either is provided, the property names are automatically created and this row will be treated as a regular row containing data. + + Int32 + + Int32 + + + 1 + + + EndRow + + By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row. + + Int32 + + Int32 + + + 0 + + + StartColumn + + The number of the first column to read data from (1 by default). + + Int32 + + Int32 + + + 1 + + + EndColumn + + By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number. + + Int32 + + Int32 + + + 0 + + + DataOnly + + Import only rows and columns that contain data, empty rows and empty columns are not imported. + + SwitchParameter + + SwitchParameter + + + False + + + AsText + + Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. (* is supported as a wildcard.) + + String[] + + String[] + + + None + + + Password + + Accepts a string that will be used to open a password protected Excel file. + + String + + String + + + None + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + ---------------------------------------------- +| File: Movies.xlsx - Sheet: Actors | +---------------------------------------------- +| A B C | +|1 First Name Address | +|2 Chuck Norris California | +|3 Jean-Claude Vandamme Brussels | +---------------------------------------------- + +PS C:> Import-Excel -Path 'C:\Movies.xlsx' -WorkSheetname Actors + +First Name: Chuck +Address : California + +First Name: Jean-Claude +Address : Brussels + + Import data from an Excel worksheet. One object is created for each row. The property names of the objects consist of the column names defined in the first row. In case a column doesn't have a column header (usually in row 1 when '-StartRow' is not used), then the unnamed columns will be skipped and the data in those columns will not be imported. + Notice that column 'B' is not imported because there's no value in cell 'B1' that can be used as property name for the objects. + + + + -------------------------- EXAMPLE 2 -------------------------- + ---------------------------------------------- +| File: Movies.xlsx - Sheet: Actors | +---------------------------------------------- +| A B C | +|1 First Name Address | +|2 Chuck Norris California | +|3 Jean-Claude Vandamme Brussels | +---------------------------------------------- + +PS\> Import-Excel -Path 'C:\Movies.xlsx' -WorkSheetname Actors -NoHeader + +P1: First Name +P2: +P3: Address + +P1: Chuck +P2: Norris +P3: California + +P1: Jean-Claude +P2: Vandamme +P3: Brussels + + Imports the complete Excel worksheet 'as is' by using the '-NoHeader' switch. One object is created for each row. The property names of the objects will be automatically generated (P1, P2, P3, ..). + Notice that the column header (row 1) is imported as an object too. + + + + -------------------------- EXAMPLE 3 -------------------------- + ---------------------------------------------------------- +| File: Movies.xlsx - Sheet: Movies | +---------------------------------------------------------- +| A B C D | +|1 The Bodyguard 1992 9 | +|2 The Matrix 1999 8 | +|3 | +|4 Skyfall 2012 9 | +---------------------------------------------------------- + +PS\> Import-Excel -Path 'C:\Movies.xlsx' -WorkSheetname Movies -HeaderName 'Movie name', 'Year', 'Rating', 'Genre' + +Movie name: The Bodyguard +Year : 1992 +Rating : 9 +Genre : + +Movie name: The Matrix +Year : 1999 +Rating : 8 +Genre : + +Movie name: +Year : +Rating : +Genre : + +Movie name: Skyfall +Year : 2012 +Rating : 9 +Genre : + + This imports data from an Excel worksheet, and as before one object is created for each row. The property names for the objects are defined in the parameter '-HeaderName'. The properties are named starting from the most left column (A) to the right. In case no value is present in one of the columns, that property will have an empty value. + Notice that empty rows are imported and that data for the property 'Genre' is not present in the worksheet. As such, the 'Genre' property will be blank for all objects. + + + + -------------------------- EXAMPLE 4 -------------------------- + ---------------------------------------------------------- +| File: Movies.xlsx - Sheet: Movies | +---------------------------------------------------------- +| A B C D | +|1 The Bodyguard 1992 9 | +|2 The Matrix 1999 8 | +|3 | +|4 Skyfall 2012 9 | +---------------------------------------------------------- + +PS\> Import-Excel -Path 'C:\Movies.xlsx' -WorkSheetname Movies -NoHeader -DataOnly + +P1: The Bodyguard +P2: 1992 +P3: 9 + +P1: The Matrix +P2: 1999 +P3: 8 + +P1: Skyfall +P2: 2012 +P3: 9 + + Import data from an Excel worksheet, and one object is created for each non-blank row. The property names of the objects (P1, P2, P3, ..) are automatically generated by using the switch '-NoHeader' . The switch '-DataOnly' will speed up the import because empty rows and empty columns are not imported. + Notice that empty rows and empty columns are not imported. + + + + -------------------------- EXAMPLE 5 -------------------------- + ---------------------------------------------------------- +| File: Movies.xlsx - Sheet: Actors | +---------------------------------------------------------- +| A B C D | +|1 Chuck Norris California | +|2 | +|3 Jean-Claude Vandamme Brussels | +---------------------------------------------------------- + +PS\> Import-Excel -Path 'C:\Movies.xlsx' -WorkSheetname Actors -DataOnly -HeaderName 'FirstName', 'SecondName', 'City' -StartRow 2 + +FirstName : Jean-Claude +SecondName: Vandamme +City : Brussels + + Import data from an Excel worksheet. One object is created for each row. The property names are provided with the '-HeaderName' parameter. The import will start from row 2 and empty columns and rows are not imported. + Notice that only 1 object is imported with only 3 properties. Column B and row 2 are empty and have been disregarded by using the switch '-DataOnly'. The property names have been named with the values provided with the parameter '-HeaderName'. Row number 1 with 'Chuck Norris' has not been imported, because we started the import from row 2 with the parameter '-StartRow 2'. + + + + -------------------------- EXAMPLE 6 -------------------------- + PS\> ,(Import-Excel -Path .\SysTables_AdventureWorks2014.xlsx) | + Write-SqlTableData -ServerInstance localhost\DEFAULT -Database BlankDB -SchemaName dbo -TableName MyNewTable_fromExcel -Force + + Imports data from an Excel file and pipes the result to the Write-SqlTableData command to be INSERTed into a table in a SQL Server database. + The ",( ... )" around the Import-Excel command allows all rows to be imported from the Excel file, prior to pipelining to the Write-SqlTableData cmdlet. This helps prevent a RBAR scenario and is important when trying to import thousands of rows. + The -Force parameter will be ignored if the table already exists. However, if a table is not found that matches the values provided by -SchemaName and -TableName parameters, it will create a new table in SQL Server database. + The Write-SqlTableData cmdlet will inherit the column names & datatypes for the new table from the object being piped in. NOTE: You need to install the SqlServer module from the PowerShell Gallery in oder to get the Write-SqlTableData cmdlet. + + + + + + https://github.com/dfinke/ImportExcel + https://github.com/dfinke/ImportExcel + + + + + + Join-Worksheet + Join + Worksheet + + Combines data on all the sheets in an Excel worksheet onto a single sheet. + + + + Join-Worksheet can work in two main ways, either + *Combining data which has the same layout from many pages into one, or *Combining pages which have nothing in common. In the former case the header row is copied from the first sheet and, by default, each row of data is labelled with the name of the sheet it came from. + In the latter case -NoHeader is specified, and each copied block can have the sheet it came from placed above it as a title. + + + + Join-Worksheet + + Path + + Path to a new or existing .XLSX file. + + String + + String + + + None + + + WorkSheetName + + The name of a sheet within the workbook where the other sheets will be joined together - "Combined" by default. + + Object + + Object + + + Combined + + + Clearsheet + + If specified ,any pre-existing target for the joined data will be deleted and re-created; otherwise data will be appended on this sheet. + + + SwitchParameter + + + False + + + NoHeader + + Join-Worksheet assumes each sheet has identical headers and the headers should be copied to the target sheet, unless -NoHeader is specified. + + + SwitchParameter + + + False + + + FromLabel + + If -NoHeader is NOT specified, then rows of data will be labeled with the name of the sheet they came from. FromLabel is the header for this column. If it is null or empty, the labels will be omitted. + + String + + String + + + From + + + LabelBlocks + + If specified, the copied blocks of data will have the name of the sheet they were copied from inserted above them as a title. + + + SwitchParameter + + + False + + + AutoSize + + Sets the width of the Excel columns to display all the data in their cells. + + + SwitchParameter + + + False + + + FreezeTopRow + + Freezes headers etc. in the top row. + + + SwitchParameter + + + False + + + FreezeFirstColumn + + Freezes titles etc. in the left column. + + + SwitchParameter + + + False + + + FreezeTopRowFirstColumn + + Freezes top row and left column (equivalent to Freeze pane 2,2 ). + + + SwitchParameter + + + False + + + FreezePane + + Freezes panes at specified coordinates (in the formRowNumber , ColumnNumber). + + Int32[] + + Int32[] + + + None + + + AutoFilter + + Enables the Excel filter on the headers of the combined sheet. + + + SwitchParameter + + + False + + + BoldTopRow + + Makes the top row boldface. + + + SwitchParameter + + + False + + + HideSource + + If specified, hides the sheets that the data is copied from. + + + SwitchParameter + + + False + + + Title + + Text of a title to be placed in Cell A1. + + String + + String + + + None + + + TitleFillPattern + + Sets the fill pattern for the title cell. + + + None + Solid + DarkGray + MediumGray + LightGray + Gray125 + Gray0625 + DarkVertical + DarkHorizontal + DarkDown + DarkUp + DarkGrid + DarkTrellis + LightVertical + LightHorizontal + LightDown + LightUp + LightGrid + LightTrellis + + ExcelFillStyle + + ExcelFillStyle + + + Solid + + + TitleBackgroundColor + + Sets the cell background color for the title cell. + + Object + + Object + + + None + + + TitleBold + + Sets the title in boldface type. + + + SwitchParameter + + + False + + + TitleSize + + Sets the point size for the title. + + Int32 + + Int32 + + + 22 + + + PivotTableDefinition + + Hashtable(s) with Sheet PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values to specify a definition for one or morePivotTable(s). + + Hashtable + + Hashtable + + + None + + + ExcelChartDefinition + + A hashtable containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-pivot] charts. + + Object[] + + Object[] + + + None + + + ConditionalFormat + + One or more conditional formatting rules defined with New-ConditionalFormattingIconSet. + + Object[] + + Object[] + + + None + + + ConditionalText + + Applies a Conditional formatting rule defined with New-ConditionalText. + + Object[] + + Object[] + + + None + + + AutoNameRange + + Makes each column a named range. + + + SwitchParameter + + + False + + + RangeName + + Makes the data in the worksheet a named range. + + String + + String + + + None + + + ReturnRange + + If specified, returns the range of cells in the combined sheet, in the format "A1:Z100". + + + SwitchParameter + + + False + + + Show + + Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first. + + + SwitchParameter + + + False + + + PassThru + + If specified, an object representing the unsaved Excel package will be returned, it then needs to be saved. + + + SwitchParameter + + + False + + + + Join-Worksheet + + Path + + Path to a new or existing .XLSX file. + + String + + String + + + None + + + WorkSheetName + + The name of a sheet within the workbook where the other sheets will be joined together - "Combined" by default. + + Object + + Object + + + Combined + + + Clearsheet + + If specified ,any pre-existing target for the joined data will be deleted and re-created; otherwise data will be appended on this sheet. + + + SwitchParameter + + + False + + + NoHeader + + Join-Worksheet assumes each sheet has identical headers and the headers should be copied to the target sheet, unless -NoHeader is specified. + + + SwitchParameter + + + False + + + FromLabel + + If -NoHeader is NOT specified, then rows of data will be labeled with the name of the sheet they came from. FromLabel is the header for this column. If it is null or empty, the labels will be omitted. + + String + + String + + + From + + + LabelBlocks + + If specified, the copied blocks of data will have the name of the sheet they were copied from inserted above them as a title. + + + SwitchParameter + + + False + + + AutoSize + + Sets the width of the Excel columns to display all the data in their cells. + + + SwitchParameter + + + False + + + FreezeTopRow + + Freezes headers etc. in the top row. + + + SwitchParameter + + + False + + + FreezeFirstColumn + + Freezes titles etc. in the left column. + + + SwitchParameter + + + False + + + FreezeTopRowFirstColumn + + Freezes top row and left column (equivalent to Freeze pane 2,2 ). + + + SwitchParameter + + + False + + + FreezePane + + Freezes panes at specified coordinates (in the formRowNumber , ColumnNumber). + + Int32[] + + Int32[] + + + None + + + BoldTopRow + + Makes the top row boldface. + + + SwitchParameter + + + False + + + HideSource + + If specified, hides the sheets that the data is copied from. + + + SwitchParameter + + + False + + + Title + + Text of a title to be placed in Cell A1. + + String + + String + + + None + + + TitleFillPattern + + Sets the fill pattern for the title cell. + + + None + Solid + DarkGray + MediumGray + LightGray + Gray125 + Gray0625 + DarkVertical + DarkHorizontal + DarkDown + DarkUp + DarkGrid + DarkTrellis + LightVertical + LightHorizontal + LightDown + LightUp + LightGrid + LightTrellis + + ExcelFillStyle + + ExcelFillStyle + + + Solid + + + TitleBackgroundColor + + Sets the cell background color for the title cell. + + Object + + Object + + + None + + + TitleBold + + Sets the title in boldface type. + + + SwitchParameter + + + False + + + TitleSize + + Sets the point size for the title. + + Int32 + + Int32 + + + 22 + + + PivotTableDefinition + + Hashtable(s) with Sheet PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values to specify a definition for one or morePivotTable(s). + + Hashtable + + Hashtable + + + None + + + ExcelChartDefinition + + A hashtable containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-pivot] charts. + + Object[] + + Object[] + + + None + + + ConditionalFormat + + One or more conditional formatting rules defined with New-ConditionalFormattingIconSet. + + Object[] + + Object[] + + + None + + + ConditionalText + + Applies a Conditional formatting rule defined with New-ConditionalText. + + Object[] + + Object[] + + + None + + + AutoNameRange + + Makes each column a named range. + + + SwitchParameter + + + False + + + RangeName + + Makes the data in the worksheet a named range. + + String + + String + + + None + + + TableName + + Makes the data in the worksheet a table with a name and applies a style to it. Name must not contain spaces. + + String + + String + + + None + + + TableStyle + + Selects the style for the named table - defaults to "Medium6". + + + None + Custom + Light1 + Light2 + Light3 + Light4 + Light5 + Light6 + Light7 + Light8 + Light9 + Light10 + Light11 + Light12 + Light13 + Light14 + Light15 + Light16 + Light17 + Light18 + Light19 + Light20 + Light21 + Medium1 + Medium2 + Medium3 + Medium4 + Medium5 + Medium6 + Medium7 + Medium8 + Medium9 + Medium10 + Medium11 + Medium12 + Medium13 + Medium14 + Medium15 + Medium16 + Medium17 + Medium18 + Medium19 + Medium20 + Medium21 + Medium22 + Medium23 + Medium24 + Medium25 + Medium26 + Medium27 + Medium28 + Dark1 + Dark2 + Dark3 + Dark4 + Dark5 + Dark6 + Dark7 + Dark8 + Dark9 + Dark10 + Dark11 + + TableStyles + + TableStyles + + + Medium6 + + + ReturnRange + + If specified, returns the range of cells in the combined sheet, in the format "A1:Z100". + + + SwitchParameter + + + False + + + Show + + Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first. + + + SwitchParameter + + + False + + + PassThru + + If specified, an object representing the unsaved Excel package will be returned, it then needs to be saved. + + + SwitchParameter + + + False + + + + Join-Worksheet + + ExcelPackage + + An object representing an Excel Package - either from Open-ExcelPackage or specifying -PassThru to Export-Excel. + + ExcelPackage + + ExcelPackage + + + None + + + WorkSheetName + + The name of a sheet within the workbook where the other sheets will be joined together - "Combined" by default. + + Object + + Object + + + Combined + + + Clearsheet + + If specified ,any pre-existing target for the joined data will be deleted and re-created; otherwise data will be appended on this sheet. + + + SwitchParameter + + + False + + + NoHeader + + Join-Worksheet assumes each sheet has identical headers and the headers should be copied to the target sheet, unless -NoHeader is specified. + + + SwitchParameter + + + False + + + FromLabel + + If -NoHeader is NOT specified, then rows of data will be labeled with the name of the sheet they came from. FromLabel is the header for this column. If it is null or empty, the labels will be omitted. + + String + + String + + + From + + + LabelBlocks + + If specified, the copied blocks of data will have the name of the sheet they were copied from inserted above them as a title. + + + SwitchParameter + + + False + + + AutoSize + + Sets the width of the Excel columns to display all the data in their cells. + + + SwitchParameter + + + False + + + FreezeTopRow + + Freezes headers etc. in the top row. + + + SwitchParameter + + + False + + + FreezeFirstColumn + + Freezes titles etc. in the left column. + + + SwitchParameter + + + False + + + FreezeTopRowFirstColumn + + Freezes top row and left column (equivalent to Freeze pane 2,2 ). + + + SwitchParameter + + + False + + + FreezePane + + Freezes panes at specified coordinates (in the formRowNumber , ColumnNumber). + + Int32[] + + Int32[] + + + None + + + BoldTopRow + + Makes the top row boldface. + + + SwitchParameter + + + False + + + HideSource + + If specified, hides the sheets that the data is copied from. + + + SwitchParameter + + + False + + + Title + + Text of a title to be placed in Cell A1. + + String + + String + + + None + + + TitleFillPattern + + Sets the fill pattern for the title cell. + + + None + Solid + DarkGray + MediumGray + LightGray + Gray125 + Gray0625 + DarkVertical + DarkHorizontal + DarkDown + DarkUp + DarkGrid + DarkTrellis + LightVertical + LightHorizontal + LightDown + LightUp + LightGrid + LightTrellis + + ExcelFillStyle + + ExcelFillStyle + + + Solid + + + TitleBackgroundColor + + Sets the cell background color for the title cell. + + Object + + Object + + + None + + + TitleBold + + Sets the title in boldface type. + + + SwitchParameter + + + False + + + TitleSize + + Sets the point size for the title. + + Int32 + + Int32 + + + 22 + + + PivotTableDefinition + + Hashtable(s) with Sheet PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values to specify a definition for one or morePivotTable(s). + + Hashtable + + Hashtable + + + None + + + ExcelChartDefinition + + A hashtable containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-pivot] charts. + + Object[] + + Object[] + + + None + + + ConditionalFormat + + One or more conditional formatting rules defined with New-ConditionalFormattingIconSet. + + Object[] + + Object[] + + + None + + + ConditionalText + + Applies a Conditional formatting rule defined with New-ConditionalText. + + Object[] + + Object[] + + + None + + + AutoNameRange + + Makes each column a named range. + + + SwitchParameter + + + False + + + RangeName + + Makes the data in the worksheet a named range. + + String + + String + + + None + + + TableName + + Makes the data in the worksheet a table with a name and applies a style to it. Name must not contain spaces. + + String + + String + + + None + + + TableStyle + + Selects the style for the named table - defaults to "Medium6". + + + None + Custom + Light1 + Light2 + Light3 + Light4 + Light5 + Light6 + Light7 + Light8 + Light9 + Light10 + Light11 + Light12 + Light13 + Light14 + Light15 + Light16 + Light17 + Light18 + Light19 + Light20 + Light21 + Medium1 + Medium2 + Medium3 + Medium4 + Medium5 + Medium6 + Medium7 + Medium8 + Medium9 + Medium10 + Medium11 + Medium12 + Medium13 + Medium14 + Medium15 + Medium16 + Medium17 + Medium18 + Medium19 + Medium20 + Medium21 + Medium22 + Medium23 + Medium24 + Medium25 + Medium26 + Medium27 + Medium28 + Dark1 + Dark2 + Dark3 + Dark4 + Dark5 + Dark6 + Dark7 + Dark8 + Dark9 + Dark10 + Dark11 + + TableStyles + + TableStyles + + + Medium6 + + + ReturnRange + + If specified, returns the range of cells in the combined sheet, in the format "A1:Z100". + + + SwitchParameter + + + False + + + Show + + Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first. + + + SwitchParameter + + + False + + + PassThru + + If specified, an object representing the unsaved Excel package will be returned, it then needs to be saved. + + + SwitchParameter + + + False + + + + Join-Worksheet + + ExcelPackage + + An object representing an Excel Package - either from Open-ExcelPackage or specifying -PassThru to Export-Excel. + + ExcelPackage + + ExcelPackage + + + None + + + WorkSheetName + + The name of a sheet within the workbook where the other sheets will be joined together - "Combined" by default. + + Object + + Object + + + Combined + + + Clearsheet + + If specified ,any pre-existing target for the joined data will be deleted and re-created; otherwise data will be appended on this sheet. + + + SwitchParameter + + + False + + + NoHeader + + Join-Worksheet assumes each sheet has identical headers and the headers should be copied to the target sheet, unless -NoHeader is specified. + + + SwitchParameter + + + False + + + FromLabel + + If -NoHeader is NOT specified, then rows of data will be labeled with the name of the sheet they came from. FromLabel is the header for this column. If it is null or empty, the labels will be omitted. + + String + + String + + + From + + + LabelBlocks + + If specified, the copied blocks of data will have the name of the sheet they were copied from inserted above them as a title. + + + SwitchParameter + + + False + + + AutoSize + + Sets the width of the Excel columns to display all the data in their cells. + + + SwitchParameter + + + False + + + FreezeTopRow + + Freezes headers etc. in the top row. + + + SwitchParameter + + + False + + + FreezeFirstColumn + + Freezes titles etc. in the left column. + + + SwitchParameter + + + False + + + FreezeTopRowFirstColumn + + Freezes top row and left column (equivalent to Freeze pane 2,2 ). + + + SwitchParameter + + + False + + + FreezePane + + Freezes panes at specified coordinates (in the formRowNumber , ColumnNumber). + + Int32[] + + Int32[] + + + None + + + AutoFilter + + Enables the Excel filter on the headers of the combined sheet. + + + SwitchParameter + + + False + + + BoldTopRow + + Makes the top row boldface. + + + SwitchParameter + + + False + + + HideSource + + If specified, hides the sheets that the data is copied from. + + + SwitchParameter + + + False + + + Title + + Text of a title to be placed in Cell A1. + + String + + String + + + None + + + TitleFillPattern + + Sets the fill pattern for the title cell. + + + None + Solid + DarkGray + MediumGray + LightGray + Gray125 + Gray0625 + DarkVertical + DarkHorizontal + DarkDown + DarkUp + DarkGrid + DarkTrellis + LightVertical + LightHorizontal + LightDown + LightUp + LightGrid + LightTrellis + + ExcelFillStyle + + ExcelFillStyle + + + Solid + + + TitleBackgroundColor + + Sets the cell background color for the title cell. + + Object + + Object + + + None + + + TitleBold + + Sets the title in boldface type. + + + SwitchParameter + + + False + + + TitleSize + + Sets the point size for the title. + + Int32 + + Int32 + + + 22 + + + PivotTableDefinition + + Hashtable(s) with Sheet PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values to specify a definition for one or morePivotTable(s). + + Hashtable + + Hashtable + + + None + + + ExcelChartDefinition + + A hashtable containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-pivot] charts. + + Object[] + + Object[] + + + None + + + ConditionalFormat + + One or more conditional formatting rules defined with New-ConditionalFormattingIconSet. + + Object[] + + Object[] + + + None + + + ConditionalText + + Applies a Conditional formatting rule defined with New-ConditionalText. + + Object[] + + Object[] + + + None + + + AutoNameRange + + Makes each column a named range. + + + SwitchParameter + + + False + + + RangeName + + Makes the data in the worksheet a named range. + + String + + String + + + None + + + ReturnRange + + If specified, returns the range of cells in the combined sheet, in the format "A1:Z100". + + + SwitchParameter + + + False + + + Show + + Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first. + + + SwitchParameter + + + False + + + PassThru + + If specified, an object representing the unsaved Excel package will be returned, it then needs to be saved. + + + SwitchParameter + + + False + + + + + + Path + + Path to a new or existing .XLSX file. + + String + + String + + + None + + + ExcelPackage + + An object representing an Excel Package - either from Open-ExcelPackage or specifying -PassThru to Export-Excel. + + ExcelPackage + + ExcelPackage + + + None + + + WorkSheetName + + The name of a sheet within the workbook where the other sheets will be joined together - "Combined" by default. + + Object + + Object + + + Combined + + + Clearsheet + + If specified ,any pre-existing target for the joined data will be deleted and re-created; otherwise data will be appended on this sheet. + + SwitchParameter + + SwitchParameter + + + False + + + NoHeader + + Join-Worksheet assumes each sheet has identical headers and the headers should be copied to the target sheet, unless -NoHeader is specified. + + SwitchParameter + + SwitchParameter + + + False + + + FromLabel + + If -NoHeader is NOT specified, then rows of data will be labeled with the name of the sheet they came from. FromLabel is the header for this column. If it is null or empty, the labels will be omitted. + + String + + String + + + From + + + LabelBlocks + + If specified, the copied blocks of data will have the name of the sheet they were copied from inserted above them as a title. + + SwitchParameter + + SwitchParameter + + + False + + + AutoSize + + Sets the width of the Excel columns to display all the data in their cells. + + SwitchParameter + + SwitchParameter + + + False + + + FreezeTopRow + + Freezes headers etc. in the top row. + + SwitchParameter + + SwitchParameter + + + False + + + FreezeFirstColumn + + Freezes titles etc. in the left column. + + SwitchParameter + + SwitchParameter + + + False + + + FreezeTopRowFirstColumn + + Freezes top row and left column (equivalent to Freeze pane 2,2 ). + + SwitchParameter + + SwitchParameter + + + False + + + FreezePane + + Freezes panes at specified coordinates (in the formRowNumber , ColumnNumber). + + Int32[] + + Int32[] + + + None + + + AutoFilter + + Enables the Excel filter on the headers of the combined sheet. + + SwitchParameter + + SwitchParameter + + + False + + + BoldTopRow + + Makes the top row boldface. + + SwitchParameter + + SwitchParameter + + + False + + + HideSource + + If specified, hides the sheets that the data is copied from. + + SwitchParameter + + SwitchParameter + + + False + + + Title + + Text of a title to be placed in Cell A1. + + String + + String + + + None + + + TitleFillPattern + + Sets the fill pattern for the title cell. + + ExcelFillStyle + + ExcelFillStyle + + + Solid + + + TitleBackgroundColor + + Sets the cell background color for the title cell. + + Object + + Object + + + None + + + TitleBold + + Sets the title in boldface type. + + SwitchParameter + + SwitchParameter + + + False + + + TitleSize + + Sets the point size for the title. + + Int32 + + Int32 + + + 22 + + + PivotTableDefinition + + Hashtable(s) with Sheet PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values to specify a definition for one or morePivotTable(s). + + Hashtable + + Hashtable + + + None + + + ExcelChartDefinition + + A hashtable containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-pivot] charts. + + Object[] + + Object[] + + + None + + + ConditionalFormat + + One or more conditional formatting rules defined with New-ConditionalFormattingIconSet. + + Object[] + + Object[] + + + None + + + ConditionalText + + Applies a Conditional formatting rule defined with New-ConditionalText. + + Object[] + + Object[] + + + None + + + AutoNameRange + + Makes each column a named range. + + SwitchParameter + + SwitchParameter + + + False + + + RangeName + + Makes the data in the worksheet a named range. + + String + + String + + + None + + + TableName + + Makes the data in the worksheet a table with a name and applies a style to it. Name must not contain spaces. + + String + + String + + + None + + + TableStyle + + Selects the style for the named table - defaults to "Medium6". + + TableStyles + + TableStyles + + + Medium6 + + + ReturnRange + + If specified, returns the range of cells in the combined sheet, in the format "A1:Z100". + + SwitchParameter + + SwitchParameter + + + False + + + Show + + Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first. + + SwitchParameter + + SwitchParameter + + + False + + + PassThru + + If specified, an object representing the unsaved Excel package will be returned, it then needs to be saved. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> foreach ($computerName in @('Server1', 'Server2', 'Server3', 'Server4')) { + Get-Service -ComputerName $computerName | + Select-Object -Property Status, Name, DisplayName, StartType | + Export-Excel -Path .\test.xlsx -WorkSheetname $computerName -AutoSize +} +PS\> $ptDef = New-PivotTableDefinition -PivotTableName "Pivot1" -SourceWorkSheet "Combined" -PivotRows "Status" -PivotFilter "MachineName" -PivotData @{Status='Count'} -IncludePivotChart -ChartType BarClustered3D +PS\> Join-Worksheet -Path .\test.xlsx -WorkSheetName combined -FromLabel "MachineName" -HideSource-AutoSize -FreezeTopRow -BoldTopRow -PivotTableDefinition $pt -Show + + The foreach command gets a list of services running on four servers and exports each list to its own page in Test.xlsx. And $PtDef=... creates a definition for a PivotTable. + The Join-Worksheet command uses the same file and merges the results into a sheet named "Combined". It sets a column header of "Machinename", this column will contain the name of the sheet the data was copied from; after copying the data to the sheet "Combined", the other sheets will be hidden. Join-Worksheet finishes by calling Export-Excel to AutoSize cells, freeze the top row and make it bold and add thePivotTable. + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\> Get-CimInstance -ClassName win32_logicaldisk | + Select-Object -Property DeviceId,VolumeName, Size,Freespace | + Export-Excel -Path "$env:computerName.xlsx" -WorkSheetname Volumes -NumberFormat "0,000" +PS\> Get-NetAdapter| Select-Object Name,InterfaceDescription,MacAddress,LinkSpeed | + Export-Excel -Path "$env:COMPUTERNAME.xlsx" -WorkSheetname NetAdapter +PS\> Join-Worksheet -Path "$env:COMPUTERNAME.xlsx"-WorkSheetName Summary -Title "Summary" -TitleBold -TitleSize 22 -NoHeader -LabelBlocks -AutoSize -HideSource -show + + The first two commands get logical-disk and network-card information; each type is exported to its own sheet in a workbook. + The Join-Worksheet command copies both onto a page named "Summary".Because the data is dissimilar, -NoHeader is specified, ensuring the whole of each page is copied. Specifying -LabelBlocks causes each sheet's name to become a title on the summary page above the copied data. The source data is hidden, a title is added in 22 point boldface and the columns are sized to fit the data. + + + + + + Online Version: + https://github.com/dfinke/ImportExcel + + + + + + Merge-MultipleSheets + Merge + MultipleSheets + + Merges Worksheets into a single Worksheet with differences marked up. + + + + The Merge Worksheet command combines two sheets. Merge-MultipleSheets is designed to merge more than two. + If asked to merge sheets A,B,C which contain Services, with a Name, Displayname and Start mode, where "Name" is treated as the key, Merge-MultipleSheets: + * Calls Merge-Worksheet to merge "Name", "Displayname" and "Startmode" from sheets A and C; the result has column headings "_Row", "Name", "DisplayName", "Startmode", "C-DisplayName", "C-StartMode", "C-Is" and "C-Row". + * Calls Merge-Worksheet again passing it the intermediate result and sheet B, comparing "Name", "Displayname" and "Start mode" columns on each side, and gets a result with columns "_Row", "Name", "DisplayName", "Startmode", "B-DisplayName", "B-StartMode", "B-Is", "B-Row", "C-DisplayName", "C-StartMode", "C-Is" and "C-Row". + Any columns on the "reference" side which are not used in the comparison are added on the right, which is why we compare the sheets in reverse order. + The "Is" columns hold "Same", "Added", "Removed" or "Changed" and is used for conditional formatting in the output sheet (these columns are hidden by default), and when the data is written to Excel the "reference" columns, in this case "DisplayName" and "Start" are renamed to reflect their source, so they become "A-DisplayName" and "A-Start". + Conditional formatting is also applied to the Key column ("Name" in this case) so the view can be filtered to rows with changes by filtering this column on color. + Note: the processing order can affect what is seen as a change.For example, if there is an extra item in sheet B in the example above, Sheet C will be processed first and that row and will not be seen to be missing. When sheet B is processed it is marked as an addition, and the conditional formatting marks the entries from sheet A to show that a values were added in at least one sheet. + However if Sheet B is the reference sheet, A and C will be seen to have an item removed; and if B is processed before C, the extra item is known when C is processed and so C is considered to be missing that item. + + + + Merge-MultipleSheets + + Path + + Paths to the files to be merged. Files are also accepted + + Object + + Object + + + None + + + KeyFontColor + + Sets the font color for the Key field; this means you can filter by color to get only changed rows. + + Object + + Object + + + [System.Drawing.Color]::Red + + + ChangeBackgroundColor + + Sets the background color for changed rows. + + Object + + Object + + + [System.Drawing.Color]::Orange + + + DeleteBackgroundColor + + Sets the background color for rows in the reference but deleted from the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::LightPink + + + AddBackgroundColor + + Sets the background color for rows not in the reference but added to the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::Orange + + + Startrow + + The row from where we start to import data, all rows above the Start row are disregarded. By default this is the first row. + + Int32 + + Int32 + + + 1 + + + Headername + + Specifies custom property names to use, instead of the values defined in the column headers of the Start row. + + String[] + + String[] + + + None + + + WorksheetName + + Name(s) of Worksheets to compare. + + Object + + Object + + + Sheet1 + + + OutputFile + + File to write output to. + + Object + + Object + + + .\temp.xlsx + + + OutputSheetName + + Name of Worksheet to output - if none specified will use the reference Worksheet name. + + Object + + Object + + + Sheet1 + + + Property + + Properties to include in the comparison - supports wildcards, default is "*". + + Object + + Object + + + * + + + ExcludeProperty + + Properties to exclude from the the comparison - supports wildcards. + + Object + + Object + + + None + + + Key + + Name of a column which is unique used to pair up rows from the reference and difference sides, default is "Name". + + Object + + Object + + + Name + + + NoHeader + + If specified, property names will be automatically generated (P1, P2, P3, ..) instead of using the values from the start row. + + + SwitchParameter + + + False + + + HideRowNumbers + + If specified, hides the columns in the spreadsheet that contain the row numbers. + + + SwitchParameter + + + False + + + Passthru + + If specified, outputs the data to the pipeline (you can add -whatif so it the command only outputs to the pipeline). + + + SwitchParameter + + + False + + + Show + + If specified, opens the output workbook. + + + SwitchParameter + + + False + + + + + + Path + + Paths to the files to be merged. Files are also accepted + + Object + + Object + + + None + + + Startrow + + The row from where we start to import data, all rows above the Start row are disregarded. By default this is the first row. + + Int32 + + Int32 + + + 1 + + + Headername + + Specifies custom property names to use, instead of the values defined in the column headers of the Start row. + + String[] + + String[] + + + None + + + NoHeader + + If specified, property names will be automatically generated (P1, P2, P3, ..) instead of using the values from the start row. + + SwitchParameter + + SwitchParameter + + + False + + + WorksheetName + + Name(s) of Worksheets to compare. + + Object + + Object + + + Sheet1 + + + OutputFile + + File to write output to. + + Object + + Object + + + .\temp.xlsx + + + OutputSheetName + + Name of Worksheet to output - if none specified will use the reference Worksheet name. + + Object + + Object + + + Sheet1 + + + Property + + Properties to include in the comparison - supports wildcards, default is "*". + + Object + + Object + + + * + + + ExcludeProperty + + Properties to exclude from the the comparison - supports wildcards. + + Object + + Object + + + None + + + Key + + Name of a column which is unique used to pair up rows from the reference and difference sides, default is "Name". + + Object + + Object + + + Name + + + KeyFontColor + + Sets the font color for the Key field; this means you can filter by color to get only changed rows. + + Object + + Object + + + [System.Drawing.Color]::Red + + + ChangeBackgroundColor + + Sets the background color for changed rows. + + Object + + Object + + + [System.Drawing.Color]::Orange + + + DeleteBackgroundColor + + Sets the background color for rows in the reference but deleted from the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::LightPink + + + AddBackgroundColor + + Sets the background color for rows not in the reference but added to the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::Orange + + + HideRowNumbers + + If specified, hides the columns in the spreadsheet that contain the row numbers. + + SwitchParameter + + SwitchParameter + + + False + + + Passthru + + If specified, outputs the data to the pipeline (you can add -whatif so it the command only outputs to the pipeline). + + SwitchParameter + + SwitchParameter + + + False + + + Show + + If specified, opens the output workbook. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> dir Server*.xlsx | Merge-MulipleSheets -WorksheetName Services -OutputFile Test2.xlsx -OutputSheetName Services -Show + + Here we are auditing servers and each one has a workbook in the current directory which contains a "Services" Worksheet (the result of Get-WmiObject -Class win32_service | Select-Object -Property Name, Displayname, Startmode). No key is specified so the key is assumed to be the "Name" column. The files are merged and the result is opened on completion. + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\> dir Serv*.xlsx | Merge-MulipleSheets -WorksheetName Software -Key "*" -ExcludeProperty Install* -OutputFile Test2.xlsx -OutputSheetName Software -Show + + The server audit files in the previous example also have "Software" worksheet, but no single field on that sheet works as a key. Specifying "*" for the key produces a compound key using all non-excluded fields (and the installation date and file location are excluded). + + + + -------------------------- EXAMPLE 3 -------------------------- + Merge-MulipleSheets -Path hotfixes.xlsx -WorksheetName Serv* -Key hotfixid -OutputFile test2.xlsx -OutputSheetName hotfixes -HideRowNumbers -Show + + This time all the servers have written their hotfix information to their own worksheets in a shared Excel workbook named "Hotfixes.xlsx" (the information was obtained by running Get-Hotfix | Sort-Object -Property description,hotfixid | Select-Object -Property Description,HotfixID) This ignores any sheets which are not named "Serv*", and uses the HotfixID as the key; in this version the row numbers are hidden. + + + + + + Online Version: + https://github.com/dfinke/ImportExcel + + + + + + Merge-Worksheet + Merge + Worksheet + + Merges two Worksheets (or other objects) into a single Worksheet with differences marked up. + + + + The Compare-Worksheet command takes two Worksheets and marks differences in the source document, and optionally outputs a grid showing the changes. + By contrast the Merge-Worksheet command takes the Worksheets and combines them into a single sheet showing the old and new data side by side. Although it is designed to work with Excel data it can work with arrays of any kind of object; so it can be a merge of Worksheets, or a merge to a Worksheet. + + + + Merge-Worksheet + + Referencefile + + First Excel file to compare. You can compare two Excel files or two other objects or a reference obhct against a difference file, but not a reference file against an object. works with the following parameter sets + * A = Compare two files default headers + * B = Compare two files user supplied headers + * C = Compare two files headers P1, P2, P3 etc + + Object + + Object + + + None + + + Differencefile + + Second Excel file to compare. Works with paramter sets A,B,C as well as the following + * D = Compare two objects; + * E = Compare one object one file that uses default headers + * F = Compare one object one file that uses user supplied headers + * G = Compare one object one file that uses headers P1, P2, P3 etc + + Object + + Object + + + None + + + WorksheetName + + Name(s) of Worksheets to compare. Applies to all parameter sets EXCEPT D which is two objects (no sheets) + + Object + + Object + + + Sheet1 + + + OutputFile + + File to hold merged data. + + Object + + Object + + + None + + + OutputSheetName + + Name of Worksheet to output - if none specified will use the reference Worksheet name. + + Object + + Object + + + Sheet1 + + + Startrow + + The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. Applies to all sets EXCEPT D which is two objects (no sheets, so no start row ) + + Int32 + + Int32 + + + 1 + + + NoHeader + + Automatically generate property names (P1, P2, P3, ..) instead of using the values the top row of the sheet. Works with parameter sets + * C 2 sheets with headers of P1, P2, P3 ... + * G Compare object + sheet + + + SwitchParameter + + + False + + + Property + + Properties to include in the DIFF - supports wildcards, default is "*". + + Object + + Object + + + * + + + ExcludeProperty + + Properties to exclude from the the search - supports wildcards. + + Object + + Object + + + None + + + Key + + Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name". + + Object + + Object + + + Name + + + KeyFontColor + + Sets the font color for the "key" field; this means you can filter by color to get only changed rows. + + Object + + Object + + + [System.Drawing.Color]::DarkRed + + + ChangeBackgroundColor + + Sets the background color for changed rows. + + Object + + Object + + + [System.Drawing.Color]::Orange + + + DeleteBackgroundColor + + Sets the background color for rows in the reference but deleted from the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::LightPink + + + AddBackgroundColor + + Sets the background color for rows not in the reference but added to the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::PaleGreen + + + HideEqual + + if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows. + + + SwitchParameter + + + False + + + Passthru + + If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline). + + + SwitchParameter + + + False + + + Show + + If specified, opens the output workbook. + + + SwitchParameter + + + False + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + + Merge-Worksheet + + Referencefile + + First Excel file to compare. You can compare two Excel files or two other objects or a reference obhct against a difference file, but not a reference file against an object. works with the following parameter sets + * A = Compare two files default headers + * B = Compare two files user supplied headers + * C = Compare two files headers P1, P2, P3 etc + + Object + + Object + + + None + + + Differencefile + + Second Excel file to compare. Works with paramter sets A,B,C as well as the following + * D = Compare two objects; + * E = Compare one object one file that uses default headers + * F = Compare one object one file that uses user supplied headers + * G = Compare one object one file that uses headers P1, P2, P3 etc + + Object + + Object + + + None + + + WorksheetName + + Name(s) of Worksheets to compare. Applies to all parameter sets EXCEPT D which is two objects (no sheets) + + Object + + Object + + + Sheet1 + + + OutputFile + + File to hold merged data. + + Object + + Object + + + None + + + OutputSheetName + + Name of Worksheet to output - if none specified will use the reference Worksheet name. + + Object + + Object + + + Sheet1 + + + Startrow + + The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. Applies to all sets EXCEPT D which is two objects (no sheets, so no start row ) + + Int32 + + Int32 + + + 1 + + + Headername + + Specifies custom property names to use, instead of the values defined in the column headers of the Start Row. Works with the following parameter sets: + * B 2 sheets with user supplied headers + * F Compare object + sheet + + String[] + + String[] + + + None + + + Property + + Properties to include in the DIFF - supports wildcards, default is "*". + + Object + + Object + + + * + + + ExcludeProperty + + Properties to exclude from the the search - supports wildcards. + + Object + + Object + + + None + + + Key + + Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name". + + Object + + Object + + + Name + + + KeyFontColor + + Sets the font color for the "key" field; this means you can filter by color to get only changed rows. + + Object + + Object + + + [System.Drawing.Color]::DarkRed + + + ChangeBackgroundColor + + Sets the background color for changed rows. + + Object + + Object + + + [System.Drawing.Color]::Orange + + + DeleteBackgroundColor + + Sets the background color for rows in the reference but deleted from the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::LightPink + + + AddBackgroundColor + + Sets the background color for rows not in the reference but added to the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::PaleGreen + + + HideEqual + + if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows. + + + SwitchParameter + + + False + + + Passthru + + If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline). + + + SwitchParameter + + + False + + + Show + + If specified, opens the output workbook. + + + SwitchParameter + + + False + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + + Merge-Worksheet + + Referencefile + + First Excel file to compare. You can compare two Excel files or two other objects or a reference obhct against a difference file, but not a reference file against an object. works with the following parameter sets + * A = Compare two files default headers + * B = Compare two files user supplied headers + * C = Compare two files headers P1, P2, P3 etc + + Object + + Object + + + None + + + Differencefile + + Second Excel file to compare. Works with paramter sets A,B,C as well as the following + * D = Compare two objects; + * E = Compare one object one file that uses default headers + * F = Compare one object one file that uses user supplied headers + * G = Compare one object one file that uses headers P1, P2, P3 etc + + Object + + Object + + + None + + + WorksheetName + + Name(s) of Worksheets to compare. Applies to all parameter sets EXCEPT D which is two objects (no sheets) + + Object + + Object + + + Sheet1 + + + OutputFile + + File to hold merged data. + + Object + + Object + + + None + + + OutputSheetName + + Name of Worksheet to output - if none specified will use the reference Worksheet name. + + Object + + Object + + + Sheet1 + + + Startrow + + The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. Applies to all sets EXCEPT D which is two objects (no sheets, so no start row ) + + Int32 + + Int32 + + + 1 + + + Property + + Properties to include in the DIFF - supports wildcards, default is "*". + + Object + + Object + + + * + + + ExcludeProperty + + Properties to exclude from the the search - supports wildcards. + + Object + + Object + + + None + + + Key + + Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name". + + Object + + Object + + + Name + + + KeyFontColor + + Sets the font color for the "key" field; this means you can filter by color to get only changed rows. + + Object + + Object + + + [System.Drawing.Color]::DarkRed + + + ChangeBackgroundColor + + Sets the background color for changed rows. + + Object + + Object + + + [System.Drawing.Color]::Orange + + + DeleteBackgroundColor + + Sets the background color for rows in the reference but deleted from the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::LightPink + + + AddBackgroundColor + + Sets the background color for rows not in the reference but added to the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::PaleGreen + + + HideEqual + + if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows. + + + SwitchParameter + + + False + + + Passthru + + If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline). + + + SwitchParameter + + + False + + + Show + + If specified, opens the output workbook. + + + SwitchParameter + + + False + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + + Merge-Worksheet + + Differencefile + + Second Excel file to compare. Works with paramter sets A,B,C as well as the following + * D = Compare two objects; + * E = Compare one object one file that uses default headers + * F = Compare one object one file that uses user supplied headers + * G = Compare one object one file that uses headers P1, P2, P3 etc + + Object + + Object + + + None + + + WorksheetName + + Name(s) of Worksheets to compare. Applies to all parameter sets EXCEPT D which is two objects (no sheets) + + Object + + Object + + + Sheet1 + + + DiffPrefix + + If there isn't a filename to use to label data from the "Difference" side, DiffPrefix is used, it defaults to "=>" + + Object + + Object + + + => + + + OutputFile + + File to hold merged data. + + Object + + Object + + + None + + + OutputSheetName + + Name of Worksheet to output - if none specified will use the reference Worksheet name. + + Object + + Object + + + Sheet1 + + + Startrow + + The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. Applies to all sets EXCEPT D which is two objects (no sheets, so no start row ) + + Int32 + + Int32 + + + 1 + + + NoHeader + + Automatically generate property names (P1, P2, P3, ..) instead of using the values the top row of the sheet. Works with parameter sets + * C 2 sheets with headers of P1, P2, P3 ... + * G Compare object + sheet + + + SwitchParameter + + + False + + + ReferenceObject + + Reference object to compare if a Worksheet is NOT being used. Reference object can combine with a difference sheet or difference object + + Object + + Object + + + None + + + Property + + Properties to include in the DIFF - supports wildcards, default is "*". + + Object + + Object + + + * + + + ExcludeProperty + + Properties to exclude from the the search - supports wildcards. + + Object + + Object + + + None + + + Key + + Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name". + + Object + + Object + + + Name + + + KeyFontColor + + Sets the font color for the "key" field; this means you can filter by color to get only changed rows. + + Object + + Object + + + [System.Drawing.Color]::DarkRed + + + ChangeBackgroundColor + + Sets the background color for changed rows. + + Object + + Object + + + [System.Drawing.Color]::Orange + + + DeleteBackgroundColor + + Sets the background color for rows in the reference but deleted from the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::LightPink + + + AddBackgroundColor + + Sets the background color for rows not in the reference but added to the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::PaleGreen + + + HideEqual + + if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows. + + + SwitchParameter + + + False + + + Passthru + + If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline). + + + SwitchParameter + + + False + + + Show + + If specified, opens the output workbook. + + + SwitchParameter + + + False + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + + Merge-Worksheet + + Differencefile + + Second Excel file to compare. Works with paramter sets A,B,C as well as the following + * D = Compare two objects; + * E = Compare one object one file that uses default headers + * F = Compare one object one file that uses user supplied headers + * G = Compare one object one file that uses headers P1, P2, P3 etc + + Object + + Object + + + None + + + WorksheetName + + Name(s) of Worksheets to compare. Applies to all parameter sets EXCEPT D which is two objects (no sheets) + + Object + + Object + + + Sheet1 + + + DiffPrefix + + If there isn't a filename to use to label data from the "Difference" side, DiffPrefix is used, it defaults to "=>" + + Object + + Object + + + => + + + OutputFile + + File to hold merged data. + + Object + + Object + + + None + + + OutputSheetName + + Name of Worksheet to output - if none specified will use the reference Worksheet name. + + Object + + Object + + + Sheet1 + + + Startrow + + The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. Applies to all sets EXCEPT D which is two objects (no sheets, so no start row ) + + Int32 + + Int32 + + + 1 + + + Headername + + Specifies custom property names to use, instead of the values defined in the column headers of the Start Row. Works with the following parameter sets: + * B 2 sheets with user supplied headers + * F Compare object + sheet + + String[] + + String[] + + + None + + + ReferenceObject + + Reference object to compare if a Worksheet is NOT being used. Reference object can combine with a difference sheet or difference object + + Object + + Object + + + None + + + Property + + Properties to include in the DIFF - supports wildcards, default is "*". + + Object + + Object + + + * + + + ExcludeProperty + + Properties to exclude from the the search - supports wildcards. + + Object + + Object + + + None + + + Key + + Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name". + + Object + + Object + + + Name + + + KeyFontColor + + Sets the font color for the "key" field; this means you can filter by color to get only changed rows. + + Object + + Object + + + [System.Drawing.Color]::DarkRed + + + ChangeBackgroundColor + + Sets the background color for changed rows. + + Object + + Object + + + [System.Drawing.Color]::Orange + + + DeleteBackgroundColor + + Sets the background color for rows in the reference but deleted from the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::LightPink + + + AddBackgroundColor + + Sets the background color for rows not in the reference but added to the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::PaleGreen + + + HideEqual + + if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows. + + + SwitchParameter + + + False + + + Passthru + + If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline). + + + SwitchParameter + + + False + + + Show + + If specified, opens the output workbook. + + + SwitchParameter + + + False + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + + Merge-Worksheet + + Differencefile + + Second Excel file to compare. Works with paramter sets A,B,C as well as the following + * D = Compare two objects; + * E = Compare one object one file that uses default headers + * F = Compare one object one file that uses user supplied headers + * G = Compare one object one file that uses headers P1, P2, P3 etc + + Object + + Object + + + None + + + WorksheetName + + Name(s) of Worksheets to compare. Applies to all parameter sets EXCEPT D which is two objects (no sheets) + + Object + + Object + + + Sheet1 + + + DiffPrefix + + If there isn't a filename to use to label data from the "Difference" side, DiffPrefix is used, it defaults to "=>" + + Object + + Object + + + => + + + OutputFile + + File to hold merged data. + + Object + + Object + + + None + + + OutputSheetName + + Name of Worksheet to output - if none specified will use the reference Worksheet name. + + Object + + Object + + + Sheet1 + + + Startrow + + The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. Applies to all sets EXCEPT D which is two objects (no sheets, so no start row ) + + Int32 + + Int32 + + + 1 + + + ReferenceObject + + Reference object to compare if a Worksheet is NOT being used. Reference object can combine with a difference sheet or difference object + + Object + + Object + + + None + + + Property + + Properties to include in the DIFF - supports wildcards, default is "*". + + Object + + Object + + + * + + + ExcludeProperty + + Properties to exclude from the the search - supports wildcards. + + Object + + Object + + + None + + + Key + + Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name". + + Object + + Object + + + Name + + + KeyFontColor + + Sets the font color for the "key" field; this means you can filter by color to get only changed rows. + + Object + + Object + + + [System.Drawing.Color]::DarkRed + + + ChangeBackgroundColor + + Sets the background color for changed rows. + + Object + + Object + + + [System.Drawing.Color]::Orange + + + DeleteBackgroundColor + + Sets the background color for rows in the reference but deleted from the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::LightPink + + + AddBackgroundColor + + Sets the background color for rows not in the reference but added to the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::PaleGreen + + + HideEqual + + if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows. + + + SwitchParameter + + + False + + + Passthru + + If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline). + + + SwitchParameter + + + False + + + Show + + If specified, opens the output workbook. + + + SwitchParameter + + + False + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + + Merge-Worksheet + + DifferenceObject + + Difference object to compare if a Worksheet is NOT being used for either half. Can't have a reference sheet and difference object. + + Object + + Object + + + None + + + DiffPrefix + + If there isn't a filename to use to label data from the "Difference" side, DiffPrefix is used, it defaults to "=>" + + Object + + Object + + + => + + + OutputFile + + File to hold merged data. + + Object + + Object + + + None + + + OutputSheetName + + Name of Worksheet to output - if none specified will use the reference Worksheet name. + + Object + + Object + + + Sheet1 + + + ReferenceObject + + Reference object to compare if a Worksheet is NOT being used. Reference object can combine with a difference sheet or difference object + + Object + + Object + + + None + + + Property + + Properties to include in the DIFF - supports wildcards, default is "*". + + Object + + Object + + + * + + + ExcludeProperty + + Properties to exclude from the the search - supports wildcards. + + Object + + Object + + + None + + + Key + + Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name". + + Object + + Object + + + Name + + + KeyFontColor + + Sets the font color for the "key" field; this means you can filter by color to get only changed rows. + + Object + + Object + + + [System.Drawing.Color]::DarkRed + + + ChangeBackgroundColor + + Sets the background color for changed rows. + + Object + + Object + + + [System.Drawing.Color]::Orange + + + DeleteBackgroundColor + + Sets the background color for rows in the reference but deleted from the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::LightPink + + + AddBackgroundColor + + Sets the background color for rows not in the reference but added to the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::PaleGreen + + + HideEqual + + if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows. + + + SwitchParameter + + + False + + + Passthru + + If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline). + + + SwitchParameter + + + False + + + Show + + If specified, opens the output workbook. + + + SwitchParameter + + + False + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + + + + Referencefile + + First Excel file to compare. You can compare two Excel files or two other objects or a reference obhct against a difference file, but not a reference file against an object. works with the following parameter sets + * A = Compare two files default headers + * B = Compare two files user supplied headers + * C = Compare two files headers P1, P2, P3 etc + + Object + + Object + + + None + + + Differencefile + + Second Excel file to compare. Works with paramter sets A,B,C as well as the following + * D = Compare two objects; + * E = Compare one object one file that uses default headers + * F = Compare one object one file that uses user supplied headers + * G = Compare one object one file that uses headers P1, P2, P3 etc + + Object + + Object + + + None + + + WorksheetName + + Name(s) of Worksheets to compare. Applies to all parameter sets EXCEPT D which is two objects (no sheets) + + Object + + Object + + + Sheet1 + + + Startrow + + The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. Applies to all sets EXCEPT D which is two objects (no sheets, so no start row ) + + Int32 + + Int32 + + + 1 + + + Headername + + Specifies custom property names to use, instead of the values defined in the column headers of the Start Row. Works with the following parameter sets: + * B 2 sheets with user supplied headers + * F Compare object + sheet + + String[] + + String[] + + + None + + + NoHeader + + Automatically generate property names (P1, P2, P3, ..) instead of using the values the top row of the sheet. Works with parameter sets + * C 2 sheets with headers of P1, P2, P3 ... + * G Compare object + sheet + + SwitchParameter + + SwitchParameter + + + False + + + ReferenceObject + + Reference object to compare if a Worksheet is NOT being used. Reference object can combine with a difference sheet or difference object + + Object + + Object + + + None + + + DifferenceObject + + Difference object to compare if a Worksheet is NOT being used for either half. Can't have a reference sheet and difference object. + + Object + + Object + + + None + + + DiffPrefix + + If there isn't a filename to use to label data from the "Difference" side, DiffPrefix is used, it defaults to "=>" + + Object + + Object + + + => + + + OutputFile + + File to hold merged data. + + Object + + Object + + + None + + + OutputSheetName + + Name of Worksheet to output - if none specified will use the reference Worksheet name. + + Object + + Object + + + Sheet1 + + + Property + + Properties to include in the DIFF - supports wildcards, default is "*". + + Object + + Object + + + * + + + ExcludeProperty + + Properties to exclude from the the search - supports wildcards. + + Object + + Object + + + None + + + Key + + Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name". + + Object + + Object + + + Name + + + KeyFontColor + + Sets the font color for the "key" field; this means you can filter by color to get only changed rows. + + Object + + Object + + + [System.Drawing.Color]::DarkRed + + + ChangeBackgroundColor + + Sets the background color for changed rows. + + Object + + Object + + + [System.Drawing.Color]::Orange + + + DeleteBackgroundColor + + Sets the background color for rows in the reference but deleted from the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::LightPink + + + AddBackgroundColor + + Sets the background color for rows not in the reference but added to the difference sheet. + + Object + + Object + + + [System.Drawing.Color]::PaleGreen + + + HideEqual + + if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows. + + SwitchParameter + + SwitchParameter + + + False + + + Passthru + + If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline). + + SwitchParameter + + SwitchParameter + + + False + + + Show + + If specified, opens the output workbook. + + SwitchParameter + + SwitchParameter + + + False + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + SwitchParameter + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> Merge-Worksheet "Server54.xlsx" "Server55.xlsx" -WorksheetName services -OutputFile Services.xlsx -OutputSheetName 54-55 -show + + The workbooks contain audit information for two servers, one sheet contains a list of services. + This command creates a worksheet named "54-55" in a workbook named "services.xlsx" which shows all the services and their differences, and opens the new workbook in Excel. + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\> Merge-Worksheet "Server54.xlsx" "Server55.xlsx" -WorksheetName services -OutputFile Services.xlsx -OutputSheetName 54-55 -HideEqual -AddBackgroundColor LightBlue -show + + This modifies the previous command to hide the equal rows in the output sheet and changes the color used to mark rows added to the second file. + + + + -------------------------- EXAMPLE 3 -------------------------- + PS\> Merge-Worksheet -OutputFile .\j1.xlsx -OutputSheetName test11 -ReferenceObject (dir .\ImportExcel\4.0.7) -DifferenceObject (dir .\ImportExcel\4.0.8) -Property Length -Show + + This version compares two directories, and marks what has changed. Because no "Key" property is given, "Name" is assumed to be the key and the only other property examined is length. Files which are added or deleted or have changed size will be highlighed in the output sheet. Changes to dates or other attributes will be ignored. + + + + -------------------------- EXAMPLE 4 -------------------------- + PS\> Merge-Worksheet -RefO (dir .\ImportExcel\4.0.7) -DiffO (dir .\ImportExcel\4.0.8) -Pr Length | Out-GridView + + This time no file is written and the results - which include all properties, not just length, are output and sent to Out-Gridview. + This version uses aliases to shorten the parameters, (OutputFileName can be "outFile" and the Sheet can be"OutSheet"; DifferenceObject & ReferenceObject can be DiffObject & RefObject respectively). + + + + + + Online Version: + https://github.com/dfinke/ImportExcel + + + + + + New-ConditionalFormattingIconSet + New + ConditionalFormattingIconSet + + Creates an object which describes a conditional formatting rule a for 3,4 or 5 icon set. + + + + Export-Excel takes a -ConditionalFormat parameter which can hold one or more descriptions for conditional formats; this command builds the defintion of a Conditional formatting rule for an icon set. + + + + New-ConditionalFormattingIconSet + + Range + + The range of cells that the conditional format applies to. + + Object + + Object + + + None + + + ConditionalFormat + + The type of rule: one of "ThreeIconSet","FourIconSet" or "FiveIconSet" + + Object + + Object + + + None + + + Reverse + + Use the icons in the reverse order. + + + SwitchParameter + + + False + + + + + + Range + + The range of cells that the conditional format applies to. + + Object + + Object + + + None + + + ConditionalFormat + + The type of rule: one of "ThreeIconSet","FourIconSet" or "FiveIconSet" + + Object + + Object + + + None + + + Reverse + + Use the icons in the reverse order. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> $cfRange = [OfficeOpenXml.ExcelAddress]::new($topRow, $column, $lastDataRow, $column) +PS\> $cfdef = New-ConditionalFormattingIconSet -Range $cfrange -ConditionalFormat ThreeIconSet -IconType Arrows +PS\> Export-Excel -ExcelPackage $excel -ConditionalFormat $cfdef -show + + The first line creates a range - one column wide in the column $column, running from $topRow to $lastDataRow. The second line creates a definition object using this range and the third uses Export-Excel with an open package to apply the format and save and open the file. + + + + + + Add-Add-ConditionalFormatting + + + + New-ConditionalText + + + + + + + New-ConditionalText + New + ConditionalText + + Creates an object which describes a conditional formatting rule for single valued rules. + + + + Some Conditional formatting rules don't apply styles to a cell (IconSets and Databars); some take two parameters (Between); some take none (ThisWeek, ContainsErrors, AboveAverage etc).The others take a single parameter (Top, BottomPercent, GreaterThan, Contains etc). + This command creates an object to describe the last two categories, which can then be passed to Export-Excel. + + + + New-ConditionalText + + Text + + The text (or other value) to use in the rule. Note that Equals, GreaterThan/LessThan rules require text to wrapped in double quotes. + + Object + + Object + + + None + + + ConditionalTextColor + + The font color for the cell - by default: "DarkRed". + + Object + + Object + + + [System.Drawing.Color]::DarkRed + + + BackgroundColor + + The fill color for the cell - by default: "LightPink". + + Object + + Object + + + [System.Drawing.Color]::LightPink + + + Range + + The range of cells that the conditional format applies to; if none is specified the range will be apply to all the data in the sheet. + + String + + String + + + None + + + PatternType + + The background pattern for the cell - by default: "Solid" + + + None + Solid + DarkGray + MediumGray + LightGray + Gray125 + Gray0625 + DarkVertical + DarkHorizontal + DarkDown + DarkUp + DarkGrid + DarkTrellis + LightVertical + LightHorizontal + LightDown + LightUp + LightGrid + LightTrellis + + ExcelFillStyle + + ExcelFillStyle + + + Solid + + + ConditionalType + + One of the supported rules; by default "ContainsText" is selected. + + Object + + Object + + + ContainsText + + + + + + Text + + The text (or other value) to use in the rule. Note that Equals, GreaterThan/LessThan rules require text to wrapped in double quotes. + + Object + + Object + + + None + + + ConditionalTextColor + + The font color for the cell - by default: "DarkRed". + + Object + + Object + + + [System.Drawing.Color]::DarkRed + + + BackgroundColor + + The fill color for the cell - by default: "LightPink". + + Object + + Object + + + [System.Drawing.Color]::LightPink + + + Range + + The range of cells that the conditional format applies to; if none is specified the range will be apply to all the data in the sheet. + + String + + String + + + None + + + PatternType + + The background pattern for the cell - by default: "Solid" + + ExcelFillStyle + + ExcelFillStyle + + + Solid + + + ConditionalType + + One of the supported rules; by default "ContainsText" is selected. + + Object + + Object + + + ContainsText + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> $ct = New-ConditionalText -Text 'Ferrari' +PS\> Export-Excel -ExcelPackage $excel -ConditionalTest $ct -show + + The first line creates a definition object which will highlight the word "Ferrari" in any cell. and the second uses Export-Excel with an open package to apply the format and save and open the file. + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\> $ct = New-ConditionalText -Text "Ferrari" +PS\> $ct2 = New-ConditionalText -Range $worksheet.Names\["FinishPosition"\].Address -ConditionalType LessThanOrEqual -Text 3 -ConditionalTextColor Red -BackgroundColor White +PS\> Export-Excel -ExcelPackage $excel -ConditionalText $ct,$ct2 -show + + This builds on the previous example, and specifies a condition of <=3 with a format of red text on a white background; this applies to a named range "Finish Position". + The range could be written -Range "C:C" to specify a named column, or -Range "C2:C102" to specify certain cells in the column. + + + + + + Add-ConditionalFormatting + + + + New-ConditionalFormattingIconSet + + + + + + + New-ExcelChartDefinition + New + ExcelChartDefinition + + Creates a Definition of a chart which can be added using Export-Excel, or Add-PivotTable + + + + All the parameters which are passed to Add-ExcelChart can be added to a chart-definition object and passed to Export-Excel with the -ExcelChartDefinition parameter, or to Add-PivotTable with the -PivotChartDefinition parameter. This command sets up those definition objects. + + + + New-ExcelChartDefinition + + Title + + The title for the chart. + + Object + + Object + + + Chart Title + + + RowOffSetPixels + + Offset to position the chart by a fraction of a row. + + Object + + Object + + + 10 + + + Column + + Column position of the top left corner of the chart. 0 places it at the edge of the sheet, 1 to the right of column A and so on. + + Object + + Object + + + 6 + + + ColumnOffSetPixels + + Offset to position the chart by a fraction of a column. + + Object + + Object + + + 5 + + + LegendPosition + + Location of the key, either "Left", "Right", "Top", "Bottom" or "TopRight". + + + Top + Left + Right + Bottom + TopRight + + eLegendPosition + + eLegendPosition + + + None + + + LegendSize + + Font size for the key. + + Object + + Object + + + None + + + SeriesHeader + + Specifies explicit name(s) for the data series, which will appear in the legend/key + + Object + + Object + + + None + + + TitleSize + + Sets the point size for the title. + + Int32 + + Int32 + + + 0 + + + XAxisTitleText + + Specifies a title for the X-axis. + + String + + String + + + None + + + XAxisTitleSize + + Sets the font size for the axis title. + + Object + + Object + + + None + + + XAxisNumberformat + + A number formatting string, like "#,##0.00", for numbers along the X-axis. + + String + + String + + + None + + + Header + + No longer used. This may be removed in future versions. + + Object + + Object + + + None + + + XMajorUnit + + Spacing for the major gridlines / tick marks along the X-axis. + + Object + + Object + + + None + + + XMinorUnit + + Spacing for the minor gridlines / tick marks along the X-axis. + + Object + + Object + + + None + + + XMaxValue + + Maximum value for the scale along the X-axis. + + Object + + Object + + + None + + + XMinValue + + Minimum value for the scale along the X-axis. + + Object + + Object + + + None + + + XAxisPosition + + Position for the X-axis ("Top" or" Bottom"). + + + Left + Bottom + Right + Top + + eAxisPosition + + eAxisPosition + + + None + + + YAxisTitleText + + Specifies a title for the Y-axis. + + String + + String + + + None + + + YAxisTitleSize + + Sets the font size for the Y-axis title. + + Object + + Object + + + None + + + YAxisNumberformat + + A number formatting string, like "#,##0.00", for numbers on the Y-axis + + String + + String + + + None + + + YMajorUnit + + Spacing for the major gridlines / tick marks on the Y-axis. + + Object + + Object + + + None + + + YMinorUnit + + Spacing for the minor gridlines / tick marks on the Y-axis. + + Object + + Object + + + None + + + ChartType + + One of the built-in chart types, such as Pie, ClusteredColumn, Line etc. Defaults to "ColumnStacked". + + + Area + Line + Pie + Bubble + ColumnClustered + ColumnStacked + ColumnStacked100 + ColumnClustered3D + ColumnStacked3D + ColumnStacked1003D + BarClustered + BarStacked + BarStacked100 + BarClustered3D + BarStacked3D + BarStacked1003D + LineStacked + LineStacked100 + LineMarkers + LineMarkersStacked + LineMarkersStacked100 + PieOfPie + PieExploded + PieExploded3D + BarOfPie + XYScatterSmooth + XYScatterSmoothNoMarkers + XYScatterLines + XYScatterLinesNoMarkers + AreaStacked + AreaStacked100 + AreaStacked3D + AreaStacked1003D + DoughnutExploded + RadarMarkers + RadarFilled + Surface + SurfaceWireframe + SurfaceTopView + SurfaceTopViewWireframe + Bubble3DEffect + StockHLC + StockOHLC + StockVHLC + StockVOHLC + CylinderColClustered + CylinderColStacked + CylinderColStacked100 + CylinderBarClustered + CylinderBarStacked + CylinderBarStacked100 + CylinderCol + ConeColClustered + ConeColStacked + ConeColStacked100 + ConeBarClustered + ConeBarStacked + ConeBarStacked100 + ConeCol + PyramidColClustered + PyramidColStacked + PyramidColStacked100 + PyramidBarClustered + PyramidBarStacked + PyramidBarStacked100 + PyramidCol + XYScatter + Radar + Doughnut + Pie3D + Line3D + Column3D + Area3D + + eChartType + + eChartType + + + ColumnStacked + + + YMaxValue + + Maximum value on the Y-axis. + + Object + + Object + + + None + + + YMinValue + + Minimum value on the Y-axis. + + Object + + Object + + + None + + + YAxisPosition + + Position for the Y-axis ("Left" or "Right"). + + + Left + Bottom + Right + Top + + eAxisPosition + + eAxisPosition + + + None + + + ChartTrendLine + + Superimposes one of Excel's trenline types on the chart. + + + Exponential + Linear + Logarithmic + MovingAvgerage + Polynomial + Power + + eTrendLine[] + + eTrendLine[] + + + None + + + XRange + + The range of cells containing values for the X-Axis - usually labels. + + Object + + Object + + + None + + + YRange + + The range(s) of cells holding values for the Y-Axis - usually "data". + + Object + + Object + + + None + + + Width + + Width of the chart in pixels. Defaults to 500. + + Object + + Object + + + 500 + + + Height + + Height of the chart in pixels. Defaults to 350. + + Object + + Object + + + 350 + + + Row + + Row position of the top left corner of the chart. 0 places it at the top of the sheet, 1 below row 1 and so on. + + Object + + Object + + + 0 + + + LegendBold + + Sets the key in bold type. + + + SwitchParameter + + + False + + + NoLegend + + If specified, turns off display of the key. If you only have one data series it may be preferable to use the title to say what the chart is. + + + SwitchParameter + + + False + + + ShowCategory + + Attaches a category label in charts which support this. + + + SwitchParameter + + + False + + + ShowPercent + + Attaches a percentage label in charts which support this. + + + SwitchParameter + + + False + + + TitleBold + + Sets the title in bold face. + + + SwitchParameter + + + False + + + XAxisTitleBold + + Sets the X-axis title in bold face. + + + SwitchParameter + + + False + + + YAxisTitleBold + + Sets the Y-axis title in bold face. + + + SwitchParameter + + + False + + + + + + Title + + The title for the chart. + + Object + + Object + + + Chart Title + + + Header + + No longer used. This may be removed in future versions. + + Object + + Object + + + None + + + ChartType + + One of the built-in chart types, such as Pie, ClusteredColumn, Line etc. Defaults to "ColumnStacked". + + eChartType + + eChartType + + + ColumnStacked + + + ChartTrendLine + + Superimposes one of Excel's trenline types on the chart. + + eTrendLine[] + + eTrendLine[] + + + None + + + XRange + + The range of cells containing values for the X-Axis - usually labels. + + Object + + Object + + + None + + + YRange + + The range(s) of cells holding values for the Y-Axis - usually "data". + + Object + + Object + + + None + + + Width + + Width of the chart in pixels. Defaults to 500. + + Object + + Object + + + 500 + + + Height + + Height of the chart in pixels. Defaults to 350. + + Object + + Object + + + 350 + + + Row + + Row position of the top left corner of the chart. 0 places it at the top of the sheet, 1 below row 1 and so on. + + Object + + Object + + + 0 + + + RowOffSetPixels + + Offset to position the chart by a fraction of a row. + + Object + + Object + + + 10 + + + Column + + Column position of the top left corner of the chart. 0 places it at the edge of the sheet, 1 to the right of column A and so on. + + Object + + Object + + + 6 + + + ColumnOffSetPixels + + Offset to position the chart by a fraction of a column. + + Object + + Object + + + 5 + + + LegendPosition + + Location of the key, either "Left", "Right", "Top", "Bottom" or "TopRight". + + eLegendPosition + + eLegendPosition + + + None + + + LegendSize + + Font size for the key. + + Object + + Object + + + None + + + LegendBold + + Sets the key in bold type. + + SwitchParameter + + SwitchParameter + + + False + + + NoLegend + + If specified, turns off display of the key. If you only have one data series it may be preferable to use the title to say what the chart is. + + SwitchParameter + + SwitchParameter + + + False + + + ShowCategory + + Attaches a category label in charts which support this. + + SwitchParameter + + SwitchParameter + + + False + + + ShowPercent + + Attaches a percentage label in charts which support this. + + SwitchParameter + + SwitchParameter + + + False + + + SeriesHeader + + Specifies explicit name(s) for the data series, which will appear in the legend/key + + Object + + Object + + + None + + + TitleBold + + Sets the title in bold face. + + SwitchParameter + + SwitchParameter + + + False + + + TitleSize + + Sets the point size for the title. + + Int32 + + Int32 + + + 0 + + + XAxisTitleText + + Specifies a title for the X-axis. + + String + + String + + + None + + + XAxisTitleBold + + Sets the X-axis title in bold face. + + SwitchParameter + + SwitchParameter + + + False + + + XAxisTitleSize + + Sets the font size for the axis title. + + Object + + Object + + + None + + + XAxisNumberformat + + A number formatting string, like "#,##0.00", for numbers along the X-axis. + + String + + String + + + None + + + XMajorUnit + + Spacing for the major gridlines / tick marks along the X-axis. + + Object + + Object + + + None + + + XMinorUnit + + Spacing for the minor gridlines / tick marks along the X-axis. + + Object + + Object + + + None + + + XMaxValue + + Maximum value for the scale along the X-axis. + + Object + + Object + + + None + + + XMinValue + + Minimum value for the scale along the X-axis. + + Object + + Object + + + None + + + XAxisPosition + + Position for the X-axis ("Top" or" Bottom"). + + eAxisPosition + + eAxisPosition + + + None + + + YAxisTitleText + + Specifies a title for the Y-axis. + + String + + String + + + None + + + YAxisTitleBold + + Sets the Y-axis title in bold face. + + SwitchParameter + + SwitchParameter + + + False + + + YAxisTitleSize + + Sets the font size for the Y-axis title. + + Object + + Object + + + None + + + YAxisNumberformat + + A number formatting string, like "#,##0.00", for numbers on the Y-axis + + String + + String + + + None + + + YMajorUnit + + Spacing for the major gridlines / tick marks on the Y-axis. + + Object + + Object + + + None + + + YMinorUnit + + Spacing for the minor gridlines / tick marks on the Y-axis. + + Object + + Object + + + None + + + YMaxValue + + Maximum value on the Y-axis. + + Object + + Object + + + None + + + YMinValue + + Minimum value on the Y-axis. + + Object + + Object + + + None + + + YAxisPosition + + Position for the Y-axis ("Left" or "Right"). + + eAxisPosition + + eAxisPosition + + + None + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> $cDef = New-ExcelChartDefinition -ChartType line -XRange "X" -YRange "Sinx" -Title "Graph of Sine X" -TitleBold -TitleSize 14 -Column 2 -ColumnOffSetPixels 35 -Width 800 -XAxisTitleText "Degrees" -XAxisTitleBold -XAxisTitleSize 12 -XMajorUnit 30 -XMinorUnit 10 -XMinValue 0 -XMaxValue 361 -XAxisNumberformat "000" -YMinValue -1.25 -YMaxValue 1.25 -YMajorUnit 0.25 -YAxisNumberformat "0.00" -YAxisTitleText "Sine" -YAxisTitleBold -YAxisTitleSize 12 -SeriesHeader "Sin(x)" -LegendSize 8 -legendBold -LegendPosition Bottom +PS\> 0..360 | ForEach-Object {[pscustomobject][ordered]@{x = $_; Sinx = "=Sin(Radians(x)) "}} | Export-Excel -AutoNameRange -now -WorkSheetname SinX -ExcelChartDefinition $cDef -Show + + This reworks an example from Add-Excel-Chart but here the chart is defined and the defintion stored in $cDef and then Export-Excel uses $cDef . + + + + + + + + New-PivotTableDefinition + New + PivotTableDefinition + + Creates PivotTable definitons for Export-Excel + + + + Export-Excel allows a single PivotTable to be defined using the parameters -IncludePivotTable, -PivotColumns, -PivotRows, -PivotData, -PivotFilter, -PivotTotals, -PivotDataToColumn, -IncludePivotChart and -ChartType. + Its -PivotTableDefintion paramater allows multiple PivotTables to be defined, with additional parameters. New-PivotTableDefinition is a convenient way to build these definitions. + + + + New-PivotTableDefinition + + PivotTableName + + Name for the new pivot table + This command previously had a typo - and has an alias to avoid breaking scripts This will be removed in a future release + + Object + + Object + + + None + + + SourceWorkSheet + + Worksheet where the data is found + + Object + + Object + + + None + + + SourceRange + + Address range in the worksheet e.g "A10:F20" - the first row must contain the column names to pivot by: if the range is not specified the whole source sheet will be used. + + Object + + Object + + + None + + + PivotRows + + Fields to set as rows in the PivotTable + + Object + + Object + + + None + + + PivotData + + A hash-table in form "FieldName"="Function", where function is one of Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP + + Hashtable + + Hashtable + + + None + + + PivotColumns + + Fields to set as columns in the PivotTable + + Object + + Object + + + None + + + PivotFilter + + Fields to use to filter in the PivotTable + + Object + + Object + + + None + + + PivotDataToColumn + + If there are multiple datasets in a PivotTable, by default they are shown seperatate rows under the given row heading; this switch makes them seperate columns. + + + SwitchParameter + + + False + + + PivotTotals + + By default PivotTables have Totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected. + + String + + String + + + Both + + + NoTotalsInPivot + + Included for compatibility - equivalent to -PivotTotals "None" + + + SwitchParameter + + + False + + + GroupDateRow + + The name of a row field which should be grouped by parts of the date/time (ignored if GroupDateRow is not specified) + + String + + String + + + None + + + GroupDatePart + + The Part(s) of the date to use in the grouping (ignored if GroupDateRow is not specified) + + + Years + Quarters + Months + Days + Hours + Minutes + Seconds + + eDateGroupBy[] + + eDateGroupBy[] + + + None + + + GroupNumericRow + + The name of a row field which should be grouped by Number (e.g 0-99, 100-199, 200-299 ) + + String + + String + + + None + + + GroupNumericMin + + The starting point for grouping + + Double + + Double + + + 0 + + + GroupNumericMax + + The endpoint for grouping + + Double + + Double + + + 1.79769313486232E+308 + + + GroupNumericInterval + + The interval for grouping + + Double + + Double + + + 100 + + + PivotNumberFormat + + Number format to apply to the data cells in the PivotTable + + String + + String + + + None + + + PivotTableStyle + + Apply a table style to the PivotTable + + + None + Custom + Light1 + Light2 + Light3 + Light4 + Light5 + Light6 + Light7 + Light8 + Light9 + Light10 + Light11 + Light12 + Light13 + Light14 + Light15 + Light16 + Light17 + Light18 + Light19 + Light20 + Light21 + Medium1 + Medium2 + Medium3 + Medium4 + Medium5 + Medium6 + Medium7 + Medium8 + Medium9 + Medium10 + Medium11 + Medium12 + Medium13 + Medium14 + Medium15 + Medium16 + Medium17 + Medium18 + Medium19 + Medium20 + Medium21 + Medium22 + Medium23 + Medium24 + Medium25 + Medium26 + Medium27 + Medium28 + Dark1 + Dark2 + Dark3 + Dark4 + Dark5 + Dark6 + Dark7 + Dark8 + Dark9 + Dark10 + Dark11 + + TableStyles + + TableStyles + + + None + + + PivotChartDefinition + + Use a chart definition instead of specifying chart settings one by one + + Object + + Object + + + None + + + Activate + + If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified + + + SwitchParameter + + + False + + + + New-PivotTableDefinition + + PivotTableName + + Name for the new pivot table + This command previously had a typo - and has an alias to avoid breaking scripts This will be removed in a future release + + Object + + Object + + + None + + + SourceWorkSheet + + Worksheet where the data is found + + Object + + Object + + + None + + + SourceRange + + Address range in the worksheet e.g "A10:F20" - the first row must contain the column names to pivot by: if the range is not specified the whole source sheet will be used. + + Object + + Object + + + None + + + PivotRows + + Fields to set as rows in the PivotTable + + Object + + Object + + + None + + + PivotData + + A hash-table in form "FieldName"="Function", where function is one of Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP + + Hashtable + + Hashtable + + + None + + + PivotColumns + + Fields to set as columns in the PivotTable + + Object + + Object + + + None + + + PivotFilter + + Fields to use to filter in the PivotTable + + Object + + Object + + + None + + + PivotDataToColumn + + If there are multiple datasets in a PivotTable, by default they are shown seperatate rows under the given row heading; this switch makes them seperate columns. + + + SwitchParameter + + + False + + + PivotTotals + + By default PivotTables have Totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected. + + String + + String + + + Both + + + NoTotalsInPivot + + Included for compatibility - equivalent to -PivotTotals "None" + + + SwitchParameter + + + False + + + GroupDateRow + + The name of a row field which should be grouped by parts of the date/time (ignored if GroupDateRow is not specified) + + String + + String + + + None + + + GroupDatePart + + The Part(s) of the date to use in the grouping (ignored if GroupDateRow is not specified) + + + Years + Quarters + Months + Days + Hours + Minutes + Seconds + + eDateGroupBy[] + + eDateGroupBy[] + + + None + + + GroupNumericRow + + The name of a row field which should be grouped by Number (e.g 0-99, 100-199, 200-299 ) + + String + + String + + + None + + + GroupNumericMin + + The starting point for grouping + + Double + + Double + + + 0 + + + GroupNumericMax + + The endpoint for grouping + + Double + + Double + + + 1.79769313486232E+308 + + + GroupNumericInterval + + The interval for grouping + + Double + + Double + + + 100 + + + PivotNumberFormat + + Number format to apply to the data cells in the PivotTable + + String + + String + + + None + + + PivotTableStyle + + Apply a table style to the PivotTable + + + None + Custom + Light1 + Light2 + Light3 + Light4 + Light5 + Light6 + Light7 + Light8 + Light9 + Light10 + Light11 + Light12 + Light13 + Light14 + Light15 + Light16 + Light17 + Light18 + Light19 + Light20 + Light21 + Medium1 + Medium2 + Medium3 + Medium4 + Medium5 + Medium6 + Medium7 + Medium8 + Medium9 + Medium10 + Medium11 + Medium12 + Medium13 + Medium14 + Medium15 + Medium16 + Medium17 + Medium18 + Medium19 + Medium20 + Medium21 + Medium22 + Medium23 + Medium24 + Medium25 + Medium26 + Medium27 + Medium28 + Dark1 + Dark2 + Dark3 + Dark4 + Dark5 + Dark6 + Dark7 + Dark8 + Dark9 + Dark10 + Dark11 + + TableStyles + + TableStyles + + + None + + + IncludePivotChart + + If specified a chart Will be included. + + + SwitchParameter + + + False + + + ChartTitle + + Optional title for the pivot chart, by default the title omitted. + + String + + String + + + None + + + ChartHeight + + Height of the chart in Pixels (400 by default) + + Int32 + + Int32 + + + 400 + + + ChartWidth + + Width of the chart in Pixels (600 by default) + + Int32 + + Int32 + + + 600 + + + ChartRow + + Cell position of the top left corner of the chart, there will be this number of rows above the top edge of the chart (default is 0, chart starts at top edge of row 1). + + Int32 + + Int32 + + + 0 + + + ChartColumn + + Cell position of the top left corner of the chart, there will be this number of cells to the left of the chart (default is 4, chart starts at left edge of column E) + + Int32 + + Int32 + + + 4 + + + ChartRowOffSetPixels + + Vertical offset of the chart from the cell corner. + + Int32 + + Int32 + + + 0 + + + ChartColumnOffSetPixels + + Horizontal offset of the chart from the cell corner. + + Int32 + + Int32 + + + 0 + + + ChartType + + Type of chart + + + Area + Line + Pie + Bubble + ColumnClustered + ColumnStacked + ColumnStacked100 + ColumnClustered3D + ColumnStacked3D + ColumnStacked1003D + BarClustered + BarStacked + BarStacked100 + BarClustered3D + BarStacked3D + BarStacked1003D + LineStacked + LineStacked100 + LineMarkers + LineMarkersStacked + LineMarkersStacked100 + PieOfPie + PieExploded + PieExploded3D + BarOfPie + XYScatterSmooth + XYScatterSmoothNoMarkers + XYScatterLines + XYScatterLinesNoMarkers + AreaStacked + AreaStacked100 + AreaStacked3D + AreaStacked1003D + DoughnutExploded + RadarMarkers + RadarFilled + Surface + SurfaceWireframe + SurfaceTopView + SurfaceTopViewWireframe + Bubble3DEffect + StockHLC + StockOHLC + StockVHLC + StockVOHLC + CylinderColClustered + CylinderColStacked + CylinderColStacked100 + CylinderBarClustered + CylinderBarStacked + CylinderBarStacked100 + CylinderCol + ConeColClustered + ConeColStacked + ConeColStacked100 + ConeBarClustered + ConeBarStacked + ConeBarStacked100 + ConeCol + PyramidColClustered + PyramidColStacked + PyramidColStacked100 + PyramidBarClustered + PyramidBarStacked + PyramidBarStacked100 + PyramidCol + XYScatter + Radar + Doughnut + Pie3D + Line3D + Column3D + Area3D + + eChartType + + eChartType + + + Pie + + + NoLegend + + If specified hides the chart legend + + + SwitchParameter + + + False + + + ShowCategory + + if specified attaches the category to slices in a pie chart : not supported on all chart types, this may give errors if applied to an unsupported type. + + + SwitchParameter + + + False + + + ShowPercent + + If specified attaches percentages to slices in a pie chart. + + + SwitchParameter + + + False + + + Activate + + If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified + + + SwitchParameter + + + False + + + + + + PivotTableName + + Name for the new pivot table + This command previously had a typo - and has an alias to avoid breaking scripts This will be removed in a future release + + Object + + Object + + + None + + + SourceWorkSheet + + Worksheet where the data is found + + Object + + Object + + + None + + + SourceRange + + Address range in the worksheet e.g "A10:F20" - the first row must contain the column names to pivot by: if the range is not specified the whole source sheet will be used. + + Object + + Object + + + None + + + PivotRows + + Fields to set as rows in the PivotTable + + Object + + Object + + + None + + + PivotData + + A hash-table in form "FieldName"="Function", where function is one of Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP + + Hashtable + + Hashtable + + + None + + + PivotColumns + + Fields to set as columns in the PivotTable + + Object + + Object + + + None + + + PivotFilter + + Fields to use to filter in the PivotTable + + Object + + Object + + + None + + + PivotDataToColumn + + If there are multiple datasets in a PivotTable, by default they are shown seperatate rows under the given row heading; this switch makes them seperate columns. + + SwitchParameter + + SwitchParameter + + + False + + + PivotTotals + + By default PivotTables have Totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected. + + String + + String + + + Both + + + NoTotalsInPivot + + Included for compatibility - equivalent to -PivotTotals "None" + + SwitchParameter + + SwitchParameter + + + False + + + GroupDateRow + + The name of a row field which should be grouped by parts of the date/time (ignored if GroupDateRow is not specified) + + String + + String + + + None + + + GroupDatePart + + The Part(s) of the date to use in the grouping (ignored if GroupDateRow is not specified) + + eDateGroupBy[] + + eDateGroupBy[] + + + None + + + GroupNumericRow + + The name of a row field which should be grouped by Number (e.g 0-99, 100-199, 200-299 ) + + String + + String + + + None + + + GroupNumericMin + + The starting point for grouping + + Double + + Double + + + 0 + + + GroupNumericMax + + The endpoint for grouping + + Double + + Double + + + 1.79769313486232E+308 + + + GroupNumericInterval + + The interval for grouping + + Double + + Double + + + 100 + + + PivotNumberFormat + + Number format to apply to the data cells in the PivotTable + + String + + String + + + None + + + PivotTableStyle + + Apply a table style to the PivotTable + + TableStyles + + TableStyles + + + None + + + PivotChartDefinition + + Use a chart definition instead of specifying chart settings one by one + + Object + + Object + + + None + + + IncludePivotChart + + If specified a chart Will be included. + + SwitchParameter + + SwitchParameter + + + False + + + ChartTitle + + Optional title for the pivot chart, by default the title omitted. + + String + + String + + + None + + + ChartHeight + + Height of the chart in Pixels (400 by default) + + Int32 + + Int32 + + + 400 + + + ChartWidth + + Width of the chart in Pixels (600 by default) + + Int32 + + Int32 + + + 600 + + + ChartRow + + Cell position of the top left corner of the chart, there will be this number of rows above the top edge of the chart (default is 0, chart starts at top edge of row 1). + + Int32 + + Int32 + + + 0 + + + ChartColumn + + Cell position of the top left corner of the chart, there will be this number of cells to the left of the chart (default is 4, chart starts at left edge of column E) + + Int32 + + Int32 + + + 4 + + + ChartRowOffSetPixels + + Vertical offset of the chart from the cell corner. + + Int32 + + Int32 + + + 0 + + + ChartColumnOffSetPixels + + Horizontal offset of the chart from the cell corner. + + Int32 + + Int32 + + + 0 + + + ChartType + + Type of chart + + eChartType + + eChartType + + + Pie + + + NoLegend + + If specified hides the chart legend + + SwitchParameter + + SwitchParameter + + + False + + + ShowCategory + + if specified attaches the category to slices in a pie chart : not supported on all chart types, this may give errors if applied to an unsupported type. + + SwitchParameter + + SwitchParameter + + + False + + + ShowPercent + + If specified attaches percentages to slices in a pie chart. + + SwitchParameter + + SwitchParameter + + + False + + + Activate + + If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified + + SwitchParameter + + SwitchParameter + + + False + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> $pt = New-PivotTableDefinition -PivotTableName "PT1" -SourceWorkSheet "Sheet1" -PivotRows "Status" -PivotData @{Status='Count'} -PivotFilter 'StartType' -IncludePivotChart -ChartType BarClustered3D +PS\> $Pt += New-PivotTableDefinition -PivotTableName "PT2" -SourceWorkSheet "Sheet2" -PivotRows "Company" -PivotData @{Company='Count'} -IncludePivotChart -ChartType PieExploded3D -ShowPercent -ChartTitle "Breakdown of processes by company" +PS\> Get-Service | Select-Object -Property Status,Name,DisplayName,StartType | Export-Excel -Path .\test.xlsx -AutoSize +PS\> Get-Process | Select-Object -Property Name,Company,Handles,CPU,VM | Export-Excel -Path .\test.xlsx -AutoSize -WorksheetName 'sheet2' +PS\> $excel = Export-Excel -Path .\test.xlsx -PivotTableDefinition $pt -Show + + This is a re-work of one of the examples in Export-Excel - instead of writing out the pivot definition hash-table, it is built by calling New-PivotTableDefinition. + + + + + + + + Open-ExcelPackage + Open + ExcelPackage + + Returns an ExcelPackage object for the specified XLSX fil.e + + + + Import-Excel and Export-Excel open an Excel file, carry out their tasks and close it again. + Sometimes it is necessary to open a file and do other work on it. Open-ExcelPackage allows the file to be opened for these tasks. + It takes a -KillExcel switch to make sure Excel is not holding the file open; a -Password parameter for existing protected files, and a -Create switch to set-up a new file if no file already exists. + + + + Open-ExcelPackage + + Path + + The path to the file to open. + + Object + + Object + + + None + + + Password + + The password for a protected worksheet, as a [normal] string (not a secure string). + + String + + String + + + None + + + KillExcel + + If specified, any running instances of Excel will be terminated before opening the file. This may result in lost work, so should be used with caution. + + + SwitchParameter + + + False + + + Create + + By default Open-ExcelPackage will only open an existing file; -Create instructs it to create a new file if required. + + + SwitchParameter + + + False + + + + + + Path + + The path to the file to open. + + Object + + Object + + + None + + + KillExcel + + If specified, any running instances of Excel will be terminated before opening the file. This may result in lost work, so should be used with caution. + + SwitchParameter + + SwitchParameter + + + False + + + Password + + The password for a protected worksheet, as a [normal] string (not a secure string). + + String + + String + + + None + + + Create + + By default Open-ExcelPackage will only open an existing file; -Create instructs it to create a new file if required. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + OfficeOpenXml.ExcelPackage + + + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> $excel = Open-ExcelPackage -Path "$env:TEMP\test99.xlsx" -Create +PS\> $ws = Add-WorkSheet -ExcelPackage $excel + + This will create a new file in the temp folder if it doesn't already exist. It then adds a worksheet - because no name is specified it will use the default name of "Sheet1" + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\> $excela= Open-ExcelPackage -path "$xlPath" -Password $password +PS\> $sheet1 = $excel.Workbook.Worksheetsa"sheet1" ] +PS\> Set-ExcelRange -Range $sheet1.Cells ["E1:S1048576" ], $sheet1.Cells ["V1:V1048576" ] -NFormat ( [cultureinfo ]::CurrentCulture.DateTimeFormat.ShortDatePattern) +PS\> Close-ExcelPackage $excel -Show + + This will open the password protected file at $xlPath using the password stored in $Password. Sheet1 is selected and formatting applied to two blocks of the sheet; then the file is and saved and loaded into Excel. + + + + + + + + Remove-WorkSheet + Remove + WorkSheet + + Removes one or more worksheets from one or more workbooks + + + + + + Remove-WorkSheet + + FullName + + The fully qualified path to the XLSX file(s) + + Object + + Object + + + None + + + WorksheetName + + The worksheet to be removed (sheet1 by default) + + String[] + + String[] + + + Sheet1 + + + Show + + If specified the file will be opened in excel after the sheet is removed. + + + SwitchParameter + + + False + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + + + + FullName + + The fully qualified path to the XLSX file(s) + + Object + + Object + + + None + + + WorksheetName + + The worksheet to be removed (sheet1 by default) + + String[] + + String[] + + + Sheet1 + + + Show + + If specified the file will be opened in excel after the sheet is removed. + + SwitchParameter + + SwitchParameter + + + False + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + SwitchParameter + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> Remove-WorkSheet -Path Test1.xlsx -WorksheetName Sheet1 + + Removes the worksheet named 'Sheet1' from 'Test1.xlsx' + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\> Remove-WorkSheet -Path Test1.xlsx -WorksheetName Sheet1,Target1 + + Removes the worksheet named 'Sheet1' and 'Target1' from 'Test1.xlsx' + + + + -------------------------- EXAMPLE 3 -------------------------- + PS\> Remove-WorkSheet -Path Test1.xlsx -WorksheetName Sheet1,Target1 -Show + + Removes the worksheets and then launches the xlsx in Excel + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> dir c:\reports\*.xlsx | Remove-WorkSheet + + Removes 'Sheet1' from all the xlsx files in the c:\reports directory + + + + + + + + Select-Worksheet + Select + Worksheet + + Sets the selected tab in an Excel workbook to be the chosen sheet and unselects all the others. + + + + Sometimes when a sheet is added we want it to be the active sheet, sometimes we want the active sheet to be left as it was. Select-Worksheet exists to change which sheet is the selected tab when Excel opens the file. + + + + Select-Worksheet + + ExcelPackage + + An object representing an ExcelPackage. + + ExcelPackage + + ExcelPackage + + + None + + + WorksheetName + + The name of the worksheet "Sheet1" by default. + + String + + String + + + None + + + + Select-Worksheet + + ExcelWorkbook + + An Excel workbook to which the Worksheet will be added - a package contains one Workbook so you can use workbook or package as it suits. + + ExcelWorkbook + + ExcelWorkbook + + + None + + + WorksheetName + + The name of the worksheet "Sheet1" by default. + + String + + String + + + None + + + + Select-Worksheet + + ExcelWorksheet + + An object representing an Excel worksheet. + + ExcelWorksheet + + ExcelWorksheet + + + None + + + + + + ExcelPackage + + An object representing an ExcelPackage. + + ExcelPackage + + ExcelPackage + + + None + + + ExcelWorkbook + + An Excel workbook to which the Worksheet will be added - a package contains one Workbook so you can use workbook or package as it suits. + + ExcelWorkbook + + ExcelWorkbook + + + None + + + WorksheetName + + The name of the worksheet "Sheet1" by default. + + String + + String + + + None + + + ExcelWorksheet + + An object representing an Excel worksheet. + + ExcelWorksheet + + ExcelWorksheet + + + None + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> Select-Worksheet -ExcelWorkbook $ExcelWorkbook -WorksheetName "NewSheet" + + $ExcelWorkbook holds a workbook object containing a sheet named "NewSheet"; This sheet will become the [only] active sheet in the workbook + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\> Select-Worksheet -ExcelPackage $Pkg -WorksheetName "NewSheet2" + + $pkg holds an Excel Package, whose workbook contains a sheet named "NewSheet2" This sheet will become the [only] active sheet in the workbook. + + + + -------------------------- EXAMPLE 3 -------------------------- + PS\> Select-Worksheet -ExcelWorksheet $ws + + $ws holds an Excel worksheet which will become the [only] active sheet in its workbook. + + + + + + + + Send-SQLDataToExcel + Send + SQLDataToExcel + + Inserts a DataTable - returned by a SQL query - into an ExcelSheet + + + + This command takes a SQL statement and run it against a database connection; for the connection it accepts either + * an object representing a session with a SQL server or ODBC database, or + * a connection string to make a session (if -MSSQLServer is specified it uses the SQL Native client, + and -Connection can be a server name instead of a detailed connection string. Without this switch it uses ODBC) + The command takes all the parameters of Export-Excel, except for -InputObject (alias TargetData); after fetching the data it calls Export-Excel with the data as the value of InputParameter and whichever of Export-Excel's parameters it was passed; for details of these parameters see the help for Export-Excel. + + + + Send-SQLDataToExcel + + Connection + + A database connection string to be used to create a database session; either + * A Data source name written in the form DSN=ODBC_Data_Source_Name, or + * A full ODBC or SQL Native Client Connection string, or + * The name of a SQL server. + + Object + + Object + + + None + + + SQL + + The SQL query to run against the session which was passed in -Session or set up from -Connection. + + String + + String + + + None + + + QueryTimeout + + Override the default query time of 30 seconds. + + Int32 + + Int32 + + + 0 + + + Force + + If specified Export-Excel will be called with parameters specified, even if there is no data to send + + + SwitchParameter + + + False + + + + Send-SQLDataToExcel + + Connection + + A database connection string to be used to create a database session; either + * A Data source name written in the form DSN=ODBC_Data_Source_Name, or + * A full ODBC or SQL Native Client Connection string, or + * The name of a SQL server. + + Object + + Object + + + None + + + MsSQLserver + + Specifies the connection string is for SQL server, not ODBC. + + + SwitchParameter + + + False + + + DataBase + + Switches to a specific database on a SQL server. + + String + + String + + + None + + + SQL + + The SQL query to run against the session which was passed in -Session or set up from -Connection. + + String + + String + + + None + + + QueryTimeout + + Override the default query time of 30 seconds. + + Int32 + + Int32 + + + 0 + + + Force + + If specified Export-Excel will be called with parameters specified, even if there is no data to send + + + SwitchParameter + + + False + + + + Send-SQLDataToExcel + + Session + + An active ODBC Connection or SQL connection object representing a session with a database which will be queried to get the data . + + Object + + Object + + + None + + + SQL + + The SQL query to run against the session which was passed in -Session or set up from -Connection. + + String + + String + + + None + + + QueryTimeout + + Override the default query time of 30 seconds. + + Int32 + + Int32 + + + 0 + + + Force + + If specified Export-Excel will be called with parameters specified, even if there is no data to send + + + SwitchParameter + + + False + + + + Send-SQLDataToExcel + + QueryTimeout + + Override the default query time of 30 seconds. + + Int32 + + Int32 + + + 0 + + + DataTable + + A System.Data.DataTable object containing the data to be inserted into the spreadsheet without running a query. This remains supported to avoid breaking older scripts, but if you have a DataTable object you can pass the it into Export-Excel using -InputObject. + + DataTable + + DataTable + + + None + + + Force + + If specified Export-Excel will be called with parameters specified, even if there is no data to send + + + SwitchParameter + + + False + + + + + + Connection + + A database connection string to be used to create a database session; either + * A Data source name written in the form DSN=ODBC_Data_Source_Name, or + * A full ODBC or SQL Native Client Connection string, or + * The name of a SQL server. + + Object + + Object + + + None + + + Session + + An active ODBC Connection or SQL connection object representing a session with a database which will be queried to get the data . + + Object + + Object + + + None + + + MsSQLserver + + Specifies the connection string is for SQL server, not ODBC. + + SwitchParameter + + SwitchParameter + + + False + + + DataBase + + Switches to a specific database on a SQL server. + + String + + String + + + None + + + SQL + + The SQL query to run against the session which was passed in -Session or set up from -Connection. + + String + + String + + + None + + + QueryTimeout + + Override the default query time of 30 seconds. + + Int32 + + Int32 + + + 0 + + + DataTable + + A System.Data.DataTable object containing the data to be inserted into the spreadsheet without running a query. This remains supported to avoid breaking older scripts, but if you have a DataTable object you can pass the it into Export-Excel using -InputObject. + + DataTable + + DataTable + + + None + + + Force + + If specified Export-Excel will be called with parameters specified, even if there is no data to send + + SwitchParameter + + SwitchParameter + + + False + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> Send-SQLDataToExcel -MsSQLserver -Connection localhost -SQL "select name,type,type_desc from [master].[sys].[all_objects]" -Path .\temp.xlsx -WorkSheetname master -AutoSize -FreezeTopRow -AutoFilter -BoldTopRow + + Connects to the local SQL server and selects 3 columns from [Sys].[all_objects] and exports then to a sheet named master with some basic header management + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\> $dbPath = 'C:\Users\James\Documents\Database1.accdb' +PS\> $Connection = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=$dbPath;" +PS\> $SQL="SELECT top 25 Name,Length From TestData ORDER BY Length DESC" +PS\> Send-SQLDataToExcel -Connection $connection -SQL $sql -path .\demo1.xlsx -WorkSheetname "Sizes" -AutoSize + + This creates an ODBC connection string to read from an Access file and a SQL Statement to extracts data from it, and sends the resulting data to a new worksheet + + + + -------------------------- EXAMPLE 3 -------------------------- + PS\> $dbPath = 'C:\users\James\Documents\f1Results.xlsx' + +PS\> $Connection = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};Dbq=$dbPath;" +PS\> $SQL="SELECT top 25 DriverName, Count(RaceDate) as Races, Count(Win) as Wins, Count(Pole) as Poles, Count(FastestLap) as Fastlaps " + + " FROM Results GROUP BY DriverName ORDER BY (count(win)) DESC" + +PS\>Send-SQLDataToExcel -Connection $connection -SQL $sql -path .\demo2.xlsx -WorkSheetname "Winners" -AutoSize -AutoNameRange -ConditionalFormat @{DataBarColor="Blue"; Range="Wins"} + + Similar to the previous example, this creates a connection string, this time for an Excel file, and runs a SQL statement to get a list of motor-racing results, outputting the resulting data to a new spreadsheet. The spreadsheet is formatted and a data bar added to show make the drivers' wins clearer. (The F1 results database is available from https://1drv.ms/x/s!AhfYu7-CJv4ehNdZWxJE9LMAX_N5sg ) + + + + -------------------------- EXAMPLE 4 -------------------------- + PS\> $dbPath = 'C:\users\James\Documents\f1Results.xlsx' + +PS\> $SQL = "SELECT top 25 DriverName, Count(RaceDate) as Races, Count(Win) as Wins, Count(Pole) as Poles, Count(FastestLap) as Fastlaps " + + " FROM Results GROUP BY DriverName ORDER BY (count(win)) DESC" +PS\> $null = Get-SQL -Session F1 -excel -Connection $dbPath -sql $sql -OutputVariable Table + +PS\> Send-SQLDataToExcel -DataTable $Table -Path ".\demo3.xlsx" -WorkSheetname Gpwinners -autosize -TableName winners -TableStyle Light6 -show + + This uses Get-SQL (at least V1.1 - download from the PowerShell gallery with Install-Module -Name GetSQL - (note the function is Get-SQL the module is GetSQL without the "-" ) + Get-SQL simplifies making database connections and building /submitting SQL statements. Here Get-SQL uses the same SQL statement as before; -OutputVariable leaves a System.Data.DataTable object in $table and Send-SQLDataToExcel puts $table into the worksheet and sets it as an Excel table. The command is equivalent to running + PS> Export-Excel -inputObject $Table -Path ".\demo3.xlsx" -WorkSheetname Gpwinners -autosize -TableName winners -TableStyle Light6 -show + This is quicker than using PS> Get-SQL <parameters> | export-excel -ExcludeProperty rowerror,rowstate,table,itemarray,haserrors <parameters> + (the F1 results database is available from https://1drv.ms/x/s!AhfYu7-CJv4ehNdZWxJE9LMAX_N5sg ) + + + + -------------------------- EXAMPLE 5 -------------------------- + PS\>$SQL = "SELECT top 25 DriverName, Count(Win) as Wins FROM Results GROUP BY DriverName ORDER BY (count(win)) DESC" +PS\> Send-SQLDataToExcel -Session $DbSessions\["f1"\] -SQL $sql -Path ".\demo3.xlsx" -WorkSheetname Gpwinners -ClearSheet -autosize -ColumnChart + + Like the previous example, this uses Get-SQL (download from the gallery with Install-Module -Name GetSQL). It uses the database session which Get-SQL created, rather than an ODBC connection string. The Session parameter can either be a object (as shown here), or the name used by Get-SQL ("F1" in this case). + Here the data is presented as a quick chart. + + + + -------------------------- EXAMPLE 6 -------------------------- + Send-SQLDataToExcel -path .\demo4.xlsx -WorkSheetname "LR" -Connection "DSN=LR" -sql "SELECT name AS CollectionName FROM AgLibraryCollection Collection ORDER BY CollectionName" + + This example uses an Existing ODBC datasource name "LR" which maps to an adobe lightroom database and gets a list of collection names into a worksheet + + + + + + Export-Excel + + + + + + + Set-ExcelColumn + Set + ExcelColumn + + Adds or modifies a column in an Excel worksheet, filling values, setting formatting and/or creating named ranges. + + + + Set-ExcelColumn can take a value which is either a string containing a value or formula or a scriptblock which evaluates to a string, and optionally a column number and fills that value down the column. + A column heading can be specified, and the column can be made a named range. + The column can be formatted in the same operation. + + + + Set-ExcelColumn + + ExcelPackage + + If specifying the worksheet by name, the ExcelPackage object which contains the worksheet also needs to be passed. + + ExcelPackage + + ExcelPackage + + + None + + + Worksheetname + + The sheet to update can be given as a name or an Excel Worksheet object - this sets it by name. + + String + + String + + + Sheet1 + + + Column + + Column to fill down - the first column is 1. 0 will be interpreted as first empty column. + + Object + + Object + + + 0 + + + StartRow + + First row to fill data in. + + Int32 + + Int32 + + + 0 + + + Value + + A value, formula or scriptblock to fill in. A script block can use $worksheet, $row, $column [number], $columnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn. + + Object + + Object + + + None + + + Heading + + Optional column heading. + + Object + + Object + + + None + + + NumberFormat + + Number format to apply to cells for example "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" or "0.0E+0" etc. + + Object + + Object + + + None + + + BorderAround + + Style of border to draw around the row. + + + None + Hair + Dotted + DashDot + Thin + DashDotDot + Dashed + MediumDashDotDot + MediumDashed + MediumDashDot + Thick + Medium + Double + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + FontColor + + Colour for the text - if none specified it will be left as it it is. + + Object + + Object + + + None + + + Bold + + Make text bold; use -Bold:$false to remove bold. + + + SwitchParameter + + + False + + + Italic + + Make text italic; use -Italic:$false to remove italic. + + + SwitchParameter + + + False + + + Underline + + Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. + + + SwitchParameter + + + False + + + UnderLineType + + Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". + + + None + Single + Double + SingleAccounting + DoubleAccounting + + ExcelUnderLineType + + ExcelUnderLineType + + + Single + + + StrikeThru + + Strike through text; use -StrikeThru:$false to remove strike through. + + + SwitchParameter + + + False + + + FontShift + + Subscript or Superscript (or None). + + + None + Baseline + Subscript + Superscript + + ExcelVerticalAlignmentFont + + ExcelVerticalAlignmentFont + + + None + + + FontName + + Font to use - Excel defaults to Calibri. + + String + + String + + + None + + + FontSize + + Point size for the text. + + Single + + Single + + + 0 + + + BackgroundColor + + Change background color. + + Object + + Object + + + None + + + BackgroundPattern + + Background pattern - "Solid" by default. + + + None + Solid + DarkGray + MediumGray + LightGray + Gray125 + Gray0625 + DarkVertical + DarkHorizontal + DarkDown + DarkUp + DarkGrid + DarkTrellis + LightVertical + LightHorizontal + LightDown + LightUp + LightGrid + LightTrellis + + ExcelFillStyle + + ExcelFillStyle + + + Solid + + + PatternColor + + Secondary color for background pattern. + + Object + + Object + + + None + + + WrapText + + Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. + + + SwitchParameter + + + False + + + HorizontalAlignment + + Position cell contents to Left, Right, Center etc. Default is "General". + + + General + Left + Center + CenterContinuous + Right + Fill + Distributed + Justify + + ExcelHorizontalAlignment + + ExcelHorizontalAlignment + + + None + + + VerticalAlignment + + Position cell contents to Top, Bottom or Center. + + + Top + Center + Bottom + Distributed + Justify + + ExcelVerticalAlignment + + ExcelVerticalAlignment + + + None + + + TextRotation + + Degrees to rotate text; up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise. + + Int32 + + Int32 + + + 0 + + + AutoSize + + Attempt to auto-fit cells to the width their contents. + + + SwitchParameter + + + False + + + Width + + Set cells to a fixed width, ignored if -AutoSize is specified. + + Single + + Single + + + 0 + + + AutoNameRange + + Set the inserted data to be a named range. + + + SwitchParameter + + + False + + + Hide + + Hide the column. + + + SwitchParameter + + + False + + + Specified + + If specified, returns the range of cells which were affected. + + + SwitchParameter + + + False + + + PassThru + + If specified, return an object representing the Column, to allow further work to be done on it. + + + SwitchParameter + + + False + + + + Set-ExcelColumn + + Worksheet + + This passes the worksheet object instead of passing a sheet name and an Excelpackage object. + + ExcelWorksheet + + ExcelWorksheet + + + None + + + Column + + Column to fill down - the first column is 1. 0 will be interpreted as first empty column. + + Object + + Object + + + 0 + + + StartRow + + First row to fill data in. + + Int32 + + Int32 + + + 0 + + + Value + + A value, formula or scriptblock to fill in. A script block can use $worksheet, $row, $column [number], $columnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn. + + Object + + Object + + + None + + + Heading + + Optional column heading. + + Object + + Object + + + None + + + NumberFormat + + Number format to apply to cells for example "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" or "0.0E+0" etc. + + Object + + Object + + + None + + + BorderAround + + Style of border to draw around the row. + + + None + Hair + Dotted + DashDot + Thin + DashDotDot + Dashed + MediumDashDotDot + MediumDashed + MediumDashDot + Thick + Medium + Double + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + FontColor + + Colour for the text - if none specified it will be left as it it is. + + Object + + Object + + + None + + + Bold + + Make text bold; use -Bold:$false to remove bold. + + + SwitchParameter + + + False + + + Italic + + Make text italic; use -Italic:$false to remove italic. + + + SwitchParameter + + + False + + + Underline + + Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. + + + SwitchParameter + + + False + + + UnderLineType + + Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". + + + None + Single + Double + SingleAccounting + DoubleAccounting + + ExcelUnderLineType + + ExcelUnderLineType + + + Single + + + StrikeThru + + Strike through text; use -StrikeThru:$false to remove strike through. + + + SwitchParameter + + + False + + + FontShift + + Subscript or Superscript (or None). + + + None + Baseline + Subscript + Superscript + + ExcelVerticalAlignmentFont + + ExcelVerticalAlignmentFont + + + None + + + FontName + + Font to use - Excel defaults to Calibri. + + String + + String + + + None + + + FontSize + + Point size for the text. + + Single + + Single + + + 0 + + + BackgroundColor + + Change background color. + + Object + + Object + + + None + + + BackgroundPattern + + Background pattern - "Solid" by default. + + + None + Solid + DarkGray + MediumGray + LightGray + Gray125 + Gray0625 + DarkVertical + DarkHorizontal + DarkDown + DarkUp + DarkGrid + DarkTrellis + LightVertical + LightHorizontal + LightDown + LightUp + LightGrid + LightTrellis + + ExcelFillStyle + + ExcelFillStyle + + + Solid + + + PatternColor + + Secondary color for background pattern. + + Object + + Object + + + None + + + WrapText + + Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. + + + SwitchParameter + + + False + + + HorizontalAlignment + + Position cell contents to Left, Right, Center etc. Default is "General". + + + General + Left + Center + CenterContinuous + Right + Fill + Distributed + Justify + + ExcelHorizontalAlignment + + ExcelHorizontalAlignment + + + None + + + VerticalAlignment + + Position cell contents to Top, Bottom or Center. + + + Top + Center + Bottom + Distributed + Justify + + ExcelVerticalAlignment + + ExcelVerticalAlignment + + + None + + + TextRotation + + Degrees to rotate text; up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise. + + Int32 + + Int32 + + + 0 + + + AutoSize + + Attempt to auto-fit cells to the width their contents. + + + SwitchParameter + + + False + + + Width + + Set cells to a fixed width, ignored if -AutoSize is specified. + + Single + + Single + + + 0 + + + AutoNameRange + + Set the inserted data to be a named range. + + + SwitchParameter + + + False + + + Hide + + Hide the column. + + + SwitchParameter + + + False + + + Specified + + If specified, returns the range of cells which were affected. + + + SwitchParameter + + + False + + + PassThru + + If specified, return an object representing the Column, to allow further work to be done on it. + + + SwitchParameter + + + False + + + + + + ExcelPackage + + If specifying the worksheet by name, the ExcelPackage object which contains the worksheet also needs to be passed. + + ExcelPackage + + ExcelPackage + + + None + + + Worksheetname + + The sheet to update can be given as a name or an Excel Worksheet object - this sets it by name. + + String + + String + + + Sheet1 + + + Worksheet + + This passes the worksheet object instead of passing a sheet name and an Excelpackage object. + + ExcelWorksheet + + ExcelWorksheet + + + None + + + Column + + Column to fill down - the first column is 1. 0 will be interpreted as first empty column. + + Object + + Object + + + 0 + + + StartRow + + First row to fill data in. + + Int32 + + Int32 + + + 0 + + + Value + + A value, formula or scriptblock to fill in. A script block can use $worksheet, $row, $column [number], $columnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn. + + Object + + Object + + + None + + + Heading + + Optional column heading. + + Object + + Object + + + None + + + NumberFormat + + Number format to apply to cells for example "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" or "0.0E+0" etc. + + Object + + Object + + + None + + + BorderAround + + Style of border to draw around the row. + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + FontColor + + Colour for the text - if none specified it will be left as it it is. + + Object + + Object + + + None + + + Bold + + Make text bold; use -Bold:$false to remove bold. + + SwitchParameter + + SwitchParameter + + + False + + + Italic + + Make text italic; use -Italic:$false to remove italic. + + SwitchParameter + + SwitchParameter + + + False + + + Underline + + Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. + + SwitchParameter + + SwitchParameter + + + False + + + UnderLineType + + Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". + + ExcelUnderLineType + + ExcelUnderLineType + + + Single + + + StrikeThru + + Strike through text; use -StrikeThru:$false to remove strike through. + + SwitchParameter + + SwitchParameter + + + False + + + FontShift + + Subscript or Superscript (or None). + + ExcelVerticalAlignmentFont + + ExcelVerticalAlignmentFont + + + None + + + FontName + + Font to use - Excel defaults to Calibri. + + String + + String + + + None + + + FontSize + + Point size for the text. + + Single + + Single + + + 0 + + + BackgroundColor + + Change background color. + + Object + + Object + + + None + + + BackgroundPattern + + Background pattern - "Solid" by default. + + ExcelFillStyle + + ExcelFillStyle + + + Solid + + + PatternColor + + Secondary color for background pattern. + + Object + + Object + + + None + + + WrapText + + Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. + + SwitchParameter + + SwitchParameter + + + False + + + HorizontalAlignment + + Position cell contents to Left, Right, Center etc. Default is "General". + + ExcelHorizontalAlignment + + ExcelHorizontalAlignment + + + None + + + VerticalAlignment + + Position cell contents to Top, Bottom or Center. + + ExcelVerticalAlignment + + ExcelVerticalAlignment + + + None + + + TextRotation + + Degrees to rotate text; up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise. + + Int32 + + Int32 + + + 0 + + + AutoSize + + Attempt to auto-fit cells to the width their contents. + + SwitchParameter + + SwitchParameter + + + False + + + Width + + Set cells to a fixed width, ignored if -AutoSize is specified. + + Single + + Single + + + 0 + + + AutoNameRange + + Set the inserted data to be a named range. + + SwitchParameter + + SwitchParameter + + + False + + + Hide + + Hide the column. + + SwitchParameter + + SwitchParameter + + + False + + + Specified + + If specified, returns the range of cells which were affected. + + SwitchParameter + + SwitchParameter + + + False + + + PassThru + + If specified, return an object representing the Column, to allow further work to be done on it. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + OfficeOpenXml.ExcelColumn + + + + + + + + System.String + + + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> Set-ExcelColumn -Worksheet $ws -Column 5 -NumberFormat 'Currency' + + $ws contains a worksheet object - and column "E" is set to use the local currency format. + Intelisense will complete the names of predefined number formats. + You can see how currency is interpreted on the local computer with the command Expand-NumberFormat currency + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\> Set-ExcelColumn -Worksheet $ws -Heading "WinsToFastLaps" -Value {"=E$row/C$row"} -Column 7 -AutoSize -AutoNameRange + + Here, $WS already contains a worksheet which holds counts of races won and fastest laps recorded by racing drivers (in columns C and E). Set-ExcelColumn specifies that Column 7 should have a heading of "WinsToFastLaps" and the data cells should contain =E2/C2 , =E3/C3 etc the new data cells should become a named range, which will also be named "WinsToFastLaps" and the column width will be set automatically. + When a value begins with "=", it is treated as a formula. + If value is a script block it will be evaluated, so here the string "=E$row/C$Row" will have the number of the current row inserted; see the value parameter for a list of variables which can be used. + Note than when evaluating an expression in a string, it is necessary to wrap it in $() so $row is valid but $($row+1) is needed. + To preventVariables merging into other parts of the string, use the back tick "$columnName`4" will be "G4" - without the backtick the string will look for a variable named "columnName4" + + + + -------------------------- EXAMPLE 3 -------------------------- + Set-ExcelColumn -Worksheet $ws -Heading "Link" -Value {"https://en.wikipedia.org" + $worksheet.cells["B$Row"].value } -AutoSize + + In this example, the worksheet in $ws has partial links to Wikipedia pages in column B. + The -Value parameter is a script block which outputs a string beginning "https..." and ending with the value of the cell at column B in the current row. + When given a valid URI, Set-ExcelColumn makes it a hyperlink. + The column will be autosized to fit the links. + + + + -------------------------- EXAMPLE 4 -------------------------- + 4..6 | Set-ExcelColumn -Worksheet $ws -AutoNameRange + + Again $ws contains a worksheet. Here columns 4 to 6 are made into named ranges, row 1 is used for the range name and the rest of the column becomes the range. + + + + + + + + Set-ExcelRange + Set + ExcelRange + + Applies number, font, alignment and/or color formatting, values or formulas to a range of Excel cells. + + + + Set-ExcelRange was created to set the style elements for a range of cells, this includes auto-sizing and hiding, setting font elements (Name, Size, Bold, Italic, Underline & UnderlineStyle and Subscript & SuperScript), font and background colors, borders, text wrapping, rotation, alignment within cells, and number format. + It was orignally named "Set-Format", but it has been extended to set Values, Formulas and ArrayFormulas (sometimes called Ctrl-shift-Enter [CSE] formulas); because of this, the name has become Set-ExcelRange but the old name of Set-Format is preserved as an alias. + + + + Set-ExcelRange + + Range + + One or more row(s), Column(s) and/or block(s) of cells to format. + + Object + + Object + + + None + + + WorkSheet + + The worksheet where the format is to be applied. + + ExcelWorksheet + + ExcelWorksheet + + + None + + + NumberFormat + + Number format to apply to cells for example "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" or "0.0E+0" etc. + + Object + + Object + + + None + + + BorderAround + + Style of border to draw around the range. + + + None + Hair + Dotted + DashDot + Thin + DashDotDot + Dashed + MediumDashDotDot + MediumDashed + MediumDashDot + Thick + Medium + Double + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderColor + + Color of the border. + + Object + + Object + + + [System.Drawing.Color]::Black + + + BorderBottom + + Style for the bottom border. + + + None + Hair + Dotted + DashDot + Thin + DashDotDot + Dashed + MediumDashDotDot + MediumDashed + MediumDashDot + Thick + Medium + Double + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderTop + + Style for the top border. + + + None + Hair + Dotted + DashDot + Thin + DashDotDot + Dashed + MediumDashDotDot + MediumDashed + MediumDashDot + Thick + Medium + Double + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderLeft + + Style for the left border. + + + None + Hair + Dotted + DashDot + Thin + DashDotDot + Dashed + MediumDashDotDot + MediumDashed + MediumDashDot + Thick + Medium + Double + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderRight + + Style for the right border. + + + None + Hair + Dotted + DashDot + Thin + DashDotDot + Dashed + MediumDashDotDot + MediumDashed + MediumDashDot + Thick + Medium + Double + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + FontColor + + Colour for the text - if none is specified it will be left as it is. + + Object + + Object + + + None + + + Value + + Value for the cell. + + Object + + Object + + + None + + + Formula + + Formula for the cell. + + Object + + Object + + + None + + + ArrayFormula + + Specifies formula should be an array formula (a.k.a CSE [ctrl-shift-enter] formula). + + + SwitchParameter + + + False + + + ResetFont + + Clear Bold, Italic, StrikeThrough and Underline and set color to Black. + + + SwitchParameter + + + False + + + Bold + + Make text bold; use -Bold:$false to remove bold. + + + SwitchParameter + + + False + + + Italic + + Make text italic; use -Italic:$false to remove italic. + + + SwitchParameter + + + False + + + Underline + + Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. + + + SwitchParameter + + + False + + + UnderLineType + + Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". + + + None + Single + Double + SingleAccounting + DoubleAccounting + + ExcelUnderLineType + + ExcelUnderLineType + + + Single + + + StrikeThru + + Strike through text; use -Strikethru:$false to remove Strike through + + + SwitchParameter + + + False + + + FontShift + + Subscript or Superscript (or none). + + + None + Baseline + Subscript + Superscript + + ExcelVerticalAlignmentFont + + ExcelVerticalAlignmentFont + + + None + + + FontName + + Font to use - Excel defaults to Calibri. + + String + + String + + + None + + + FontSize + + Point size for the text. + + Single + + Single + + + 0 + + + BackgroundColor + + Change background color. + + Object + + Object + + + None + + + BackgroundPattern + + Background pattern - Solid by default. + + + None + Solid + DarkGray + MediumGray + LightGray + Gray125 + Gray0625 + DarkVertical + DarkHorizontal + DarkDown + DarkUp + DarkGrid + DarkTrellis + LightVertical + LightHorizontal + LightDown + LightUp + LightGrid + LightTrellis + + ExcelFillStyle + + ExcelFillStyle + + + Solid + + + PatternColor + + Secondary color for background pattern. + + Object + + Object + + + None + + + WrapText + + Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. + + + SwitchParameter + + + False + + + HorizontalAlignment + + Position cell contents to Left, Right, Center etc. default is 'General'. + + + General + Left + Center + CenterContinuous + Right + Fill + Distributed + Justify + + ExcelHorizontalAlignment + + ExcelHorizontalAlignment + + + None + + + VerticalAlignment + + Position cell contents to Top, Bottom or Center. + + + Top + Center + Bottom + Distributed + Justify + + ExcelVerticalAlignment + + ExcelVerticalAlignment + + + None + + + TextRotation + + Degrees to rotate text; up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise. + + Int32 + + Int32 + + + 0 + + + AutoSize + + Autofit cells to width (columns or ranges only). + + + SwitchParameter + + + False + + + Width + + Set cells to a fixed width (columns or ranges only), ignored if Autosize is specified. + + Single + + Single + + + 0 + + + Height + + Set cells to a fixed height (rows or ranges only). + + Single + + Single + + + 0 + + + Hidden + + Hide a row or column (not a range); use -Hidden:$false to unhide. + + + SwitchParameter + + + False + + + Locked + + Locks cells. Cells are locked by default use -locked:$false on the whole sheet and then lock specific ones, and enable protection on the sheet. + + + SwitchParameter + + + False + + + Merge + + Merges cells - it is recommended that you explicitly set -HorizontalAlignment + + + SwitchParameter + + + False + + + + + + Range + + One or more row(s), Column(s) and/or block(s) of cells to format. + + Object + + Object + + + None + + + WorkSheet + + The worksheet where the format is to be applied. + + ExcelWorksheet + + ExcelWorksheet + + + None + + + NumberFormat + + Number format to apply to cells for example "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" or "0.0E+0" etc. + + Object + + Object + + + None + + + BorderAround + + Style of border to draw around the range. + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderColor + + Color of the border. + + Object + + Object + + + [System.Drawing.Color]::Black + + + BorderBottom + + Style for the bottom border. + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderTop + + Style for the top border. + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderLeft + + Style for the left border. + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderRight + + Style for the right border. + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + FontColor + + Colour for the text - if none is specified it will be left as it is. + + Object + + Object + + + None + + + Value + + Value for the cell. + + Object + + Object + + + None + + + Formula + + Formula for the cell. + + Object + + Object + + + None + + + ArrayFormula + + Specifies formula should be an array formula (a.k.a CSE [ctrl-shift-enter] formula). + + SwitchParameter + + SwitchParameter + + + False + + + ResetFont + + Clear Bold, Italic, StrikeThrough and Underline and set color to Black. + + SwitchParameter + + SwitchParameter + + + False + + + Bold + + Make text bold; use -Bold:$false to remove bold. + + SwitchParameter + + SwitchParameter + + + False + + + Italic + + Make text italic; use -Italic:$false to remove italic. + + SwitchParameter + + SwitchParameter + + + False + + + Underline + + Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. + + SwitchParameter + + SwitchParameter + + + False + + + UnderLineType + + Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". + + ExcelUnderLineType + + ExcelUnderLineType + + + Single + + + StrikeThru + + Strike through text; use -Strikethru:$false to remove Strike through + + SwitchParameter + + SwitchParameter + + + False + + + FontShift + + Subscript or Superscript (or none). + + ExcelVerticalAlignmentFont + + ExcelVerticalAlignmentFont + + + None + + + FontName + + Font to use - Excel defaults to Calibri. + + String + + String + + + None + + + FontSize + + Point size for the text. + + Single + + Single + + + 0 + + + BackgroundColor + + Change background color. + + Object + + Object + + + None + + + BackgroundPattern + + Background pattern - Solid by default. + + ExcelFillStyle + + ExcelFillStyle + + + Solid + + + PatternColor + + Secondary color for background pattern. + + Object + + Object + + + None + + + WrapText + + Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. + + SwitchParameter + + SwitchParameter + + + False + + + HorizontalAlignment + + Position cell contents to Left, Right, Center etc. default is 'General'. + + ExcelHorizontalAlignment + + ExcelHorizontalAlignment + + + None + + + VerticalAlignment + + Position cell contents to Top, Bottom or Center. + + ExcelVerticalAlignment + + ExcelVerticalAlignment + + + None + + + TextRotation + + Degrees to rotate text; up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise. + + Int32 + + Int32 + + + 0 + + + AutoSize + + Autofit cells to width (columns or ranges only). + + SwitchParameter + + SwitchParameter + + + False + + + Width + + Set cells to a fixed width (columns or ranges only), ignored if Autosize is specified. + + Single + + Single + + + 0 + + + Height + + Set cells to a fixed height (rows or ranges only). + + Single + + Single + + + 0 + + + Hidden + + Hide a row or column (not a range); use -Hidden:$false to unhide. + + SwitchParameter + + SwitchParameter + + + False + + + Locked + + Locks cells. Cells are locked by default use -locked:$false on the whole sheet and then lock specific ones, and enable protection on the sheet. + + SwitchParameter + + SwitchParameter + + + False + + + Merge + + Merges cells - it is recommended that you explicitly set -HorizontalAlignment + + SwitchParameter + + SwitchParameter + + + False + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> $sheet.Column(3) | Set-ExcelRange -HorizontalAlignment Right -NumberFormat "#,###" -AutoFit + + Selects column 3 from a sheet object (within a workbook object, which is a child of the ExcelPackage object) and passes it to Set-ExcelRange which formats numbers as a integers with comma-separated groups, aligns it right, and auto-fits the column to the contents. + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\> Set-ExcelRange -Range $sheet.Cells["E1:H1048576"] -HorizontalAlignment Right -NumberFormat "#,###" + + Instead of piping the address, this version specifies a block of cells and applies similar formatting. + + + + -------------------------- EXAMPLE 3 -------------------------- + PS\> Set-ExcelRange $excel.Workbook.Worksheets[1].Tables["Processes"] -Italic + + This time instead of specifying a range of cells, a table is selected by name and formatted as italic. + + + + + + + + Set-ExcelRow + Set + ExcelRow + + Fills values into a [new] row in an Excel spreadsheet, and sets row formats. + + + + Set-ExcelRow accepts either a Worksheet object or an ExcelPackage object returned by Export-Excel and the name of a sheet, and inserts the chosen contents into a row of the sheet. + The contents can be a constant, like "42", a formula or a script block which is converted into a constant or a formula. + The first cell of the row can optionally be given a heading. + + + + Set-ExcelRow + + ExcelPackage + + An Excel package object - for example from Export-Excel -PassThru - if specified requires a sheet name to be passed a parameter. + + ExcelPackage + + ExcelPackage + + + None + + + Worksheetname + + The name of the sheet to update in the package. + + Object + + Object + + + Sheet1 + + + Row + + Row to fill right - first row is 1. 0 will be interpreted as first unused row. + + Object + + Object + + + 0 + + + StartColumn + + Position in the row to start from. + + Int32 + + Int32 + + + 0 + + + Value + + Value, Formula or ScriptBlock to fill in. A ScriptBlock can use $worksheet, $row, $Column [number], $ColumnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn. + + Object + + Object + + + None + + + Heading + + Optional row-heading. + + Object + + Object + + + None + + + HeadingBold + + Set the heading in bold type. + + + SwitchParameter + + + False + + + HeadingSize + + Change the font-size of the heading. + + Int32 + + Int32 + + + 0 + + + NumberFormat + + Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc. + + Object + + Object + + + None + + + BorderAround + + Style of border to draw around the row. + + + None + Hair + Dotted + DashDot + Thin + DashDotDot + Dashed + MediumDashDotDot + MediumDashed + MediumDashDot + Thick + Medium + Double + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderColor + + Color of the border. + + Object + + Object + + + [System.Drawing.Color]::Black + + + BorderBottom + + Style for the bottom border. + + + None + Hair + Dotted + DashDot + Thin + DashDotDot + Dashed + MediumDashDotDot + MediumDashed + MediumDashDot + Thick + Medium + Double + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderTop + + Style for the top border. + + + None + Hair + Dotted + DashDot + Thin + DashDotDot + Dashed + MediumDashDotDot + MediumDashed + MediumDashDot + Thick + Medium + Double + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderLeft + + Style for the left border. + + + None + Hair + Dotted + DashDot + Thin + DashDotDot + Dashed + MediumDashDotDot + MediumDashed + MediumDashDot + Thick + Medium + Double + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderRight + + Style for the right border. + + + None + Hair + Dotted + DashDot + Thin + DashDotDot + Dashed + MediumDashDotDot + MediumDashed + MediumDashDot + Thick + Medium + Double + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + FontColor + + Color for the text - if not specified the font will be left as it it is. + + Object + + Object + + + None + + + Bold + + Make text bold; use -Bold:$false to remove bold. + + + SwitchParameter + + + False + + + Italic + + Make text italic; use -Italic:$false to remove italic. + + + SwitchParameter + + + False + + + Underline + + Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. + + + SwitchParameter + + + False + + + UnderLineType + + Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". + + + None + Single + Double + SingleAccounting + DoubleAccounting + + ExcelUnderLineType + + ExcelUnderLineType + + + Single + + + StrikeThru + + Strike through text; use -StrikeThru:$false to remove strike through. + + + SwitchParameter + + + False + + + FontShift + + Subscript or Superscript (or none). + + + None + Baseline + Subscript + Superscript + + ExcelVerticalAlignmentFont + + ExcelVerticalAlignmentFont + + + None + + + FontName + + Font to use - Excel defaults to Calibri. + + String + + String + + + None + + + FontSize + + Point size for the text. + + Single + + Single + + + 0 + + + BackgroundColor + + Change background color. + + Object + + Object + + + None + + + BackgroundPattern + + Background pattern - solid by default. + + + None + Solid + DarkGray + MediumGray + LightGray + Gray125 + Gray0625 + DarkVertical + DarkHorizontal + DarkDown + DarkUp + DarkGrid + DarkTrellis + LightVertical + LightHorizontal + LightDown + LightUp + LightGrid + LightTrellis + + ExcelFillStyle + + ExcelFillStyle + + + Solid + + + PatternColor + + Secondary color for background pattern. + + Object + + Object + + + None + + + WrapText + + Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. + + + SwitchParameter + + + False + + + HorizontalAlignment + + Position cell contents to Left, Right, Center etc. default is 'General'. + + + General + Left + Center + CenterContinuous + Right + Fill + Distributed + Justify + + ExcelHorizontalAlignment + + ExcelHorizontalAlignment + + + None + + + VerticalAlignment + + Position cell contents to Top, Bottom or Center. + + + Top + Center + Bottom + Distributed + Justify + + ExcelVerticalAlignment + + ExcelVerticalAlignment + + + None + + + TextRotation + + Degrees to rotate text. Up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise. + + Int32 + + Int32 + + + 0 + + + Height + + Set cells to a fixed height. + + Single + + Single + + + 0 + + + Hide + + Hide the row. + + + SwitchParameter + + + False + + + ReturnRange + + If sepecified, returns the range of cells which were affected. + + + SwitchParameter + + + False + + + PassThru + + If Specified, return a row object to allow further work to be done. + + + SwitchParameter + + + False + + + + Set-ExcelRow + + Worksheet + + A worksheet object instead of passing a name and package. + + ExcelWorksheet + + ExcelWorksheet + + + None + + + Row + + Row to fill right - first row is 1. 0 will be interpreted as first unused row. + + Object + + Object + + + 0 + + + StartColumn + + Position in the row to start from. + + Int32 + + Int32 + + + 0 + + + Value + + Value, Formula or ScriptBlock to fill in. A ScriptBlock can use $worksheet, $row, $Column [number], $ColumnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn. + + Object + + Object + + + None + + + Heading + + Optional row-heading. + + Object + + Object + + + None + + + HeadingBold + + Set the heading in bold type. + + + SwitchParameter + + + False + + + HeadingSize + + Change the font-size of the heading. + + Int32 + + Int32 + + + 0 + + + NumberFormat + + Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc. + + Object + + Object + + + None + + + BorderAround + + Style of border to draw around the row. + + + None + Hair + Dotted + DashDot + Thin + DashDotDot + Dashed + MediumDashDotDot + MediumDashed + MediumDashDot + Thick + Medium + Double + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderColor + + Color of the border. + + Object + + Object + + + [System.Drawing.Color]::Black + + + BorderBottom + + Style for the bottom border. + + + None + Hair + Dotted + DashDot + Thin + DashDotDot + Dashed + MediumDashDotDot + MediumDashed + MediumDashDot + Thick + Medium + Double + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderTop + + Style for the top border. + + + None + Hair + Dotted + DashDot + Thin + DashDotDot + Dashed + MediumDashDotDot + MediumDashed + MediumDashDot + Thick + Medium + Double + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderLeft + + Style for the left border. + + + None + Hair + Dotted + DashDot + Thin + DashDotDot + Dashed + MediumDashDotDot + MediumDashed + MediumDashDot + Thick + Medium + Double + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderRight + + Style for the right border. + + + None + Hair + Dotted + DashDot + Thin + DashDotDot + Dashed + MediumDashDotDot + MediumDashed + MediumDashDot + Thick + Medium + Double + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + FontColor + + Color for the text - if not specified the font will be left as it it is. + + Object + + Object + + + None + + + Bold + + Make text bold; use -Bold:$false to remove bold. + + + SwitchParameter + + + False + + + Italic + + Make text italic; use -Italic:$false to remove italic. + + + SwitchParameter + + + False + + + Underline + + Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. + + + SwitchParameter + + + False + + + UnderLineType + + Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". + + + None + Single + Double + SingleAccounting + DoubleAccounting + + ExcelUnderLineType + + ExcelUnderLineType + + + Single + + + StrikeThru + + Strike through text; use -StrikeThru:$false to remove strike through. + + + SwitchParameter + + + False + + + FontShift + + Subscript or Superscript (or none). + + + None + Baseline + Subscript + Superscript + + ExcelVerticalAlignmentFont + + ExcelVerticalAlignmentFont + + + None + + + FontName + + Font to use - Excel defaults to Calibri. + + String + + String + + + None + + + FontSize + + Point size for the text. + + Single + + Single + + + 0 + + + BackgroundColor + + Change background color. + + Object + + Object + + + None + + + BackgroundPattern + + Background pattern - solid by default. + + + None + Solid + DarkGray + MediumGray + LightGray + Gray125 + Gray0625 + DarkVertical + DarkHorizontal + DarkDown + DarkUp + DarkGrid + DarkTrellis + LightVertical + LightHorizontal + LightDown + LightUp + LightGrid + LightTrellis + + ExcelFillStyle + + ExcelFillStyle + + + Solid + + + PatternColor + + Secondary color for background pattern. + + Object + + Object + + + None + + + WrapText + + Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. + + + SwitchParameter + + + False + + + HorizontalAlignment + + Position cell contents to Left, Right, Center etc. default is 'General'. + + + General + Left + Center + CenterContinuous + Right + Fill + Distributed + Justify + + ExcelHorizontalAlignment + + ExcelHorizontalAlignment + + + None + + + VerticalAlignment + + Position cell contents to Top, Bottom or Center. + + + Top + Center + Bottom + Distributed + Justify + + ExcelVerticalAlignment + + ExcelVerticalAlignment + + + None + + + TextRotation + + Degrees to rotate text. Up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise. + + Int32 + + Int32 + + + 0 + + + Height + + Set cells to a fixed height. + + Single + + Single + + + 0 + + + Hide + + Hide the row. + + + SwitchParameter + + + False + + + ReturnRange + + If sepecified, returns the range of cells which were affected. + + + SwitchParameter + + + False + + + PassThru + + If Specified, return a row object to allow further work to be done. + + + SwitchParameter + + + False + + + + + + ExcelPackage + + An Excel package object - for example from Export-Excel -PassThru - if specified requires a sheet name to be passed a parameter. + + ExcelPackage + + ExcelPackage + + + None + + + Worksheetname + + The name of the sheet to update in the package. + + Object + + Object + + + Sheet1 + + + Worksheet + + A worksheet object instead of passing a name and package. + + ExcelWorksheet + + ExcelWorksheet + + + None + + + Row + + Row to fill right - first row is 1. 0 will be interpreted as first unused row. + + Object + + Object + + + 0 + + + StartColumn + + Position in the row to start from. + + Int32 + + Int32 + + + 0 + + + Value + + Value, Formula or ScriptBlock to fill in. A ScriptBlock can use $worksheet, $row, $Column [number], $ColumnName [letter(s)], $startRow, $startColumn, $endRow, $endColumn. + + Object + + Object + + + None + + + Heading + + Optional row-heading. + + Object + + Object + + + None + + + HeadingBold + + Set the heading in bold type. + + SwitchParameter + + SwitchParameter + + + False + + + HeadingSize + + Change the font-size of the heading. + + Int32 + + Int32 + + + 0 + + + NumberFormat + + Number format to apply to cells e.g. "dd/MM/yyyy HH:mm", "£#,##0.00;[Red]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc. + + Object + + Object + + + None + + + BorderAround + + Style of border to draw around the row. + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderColor + + Color of the border. + + Object + + Object + + + [System.Drawing.Color]::Black + + + BorderBottom + + Style for the bottom border. + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderTop + + Style for the top border. + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderLeft + + Style for the left border. + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + BorderRight + + Style for the right border. + + ExcelBorderStyle + + ExcelBorderStyle + + + None + + + FontColor + + Color for the text - if not specified the font will be left as it it is. + + Object + + Object + + + None + + + Bold + + Make text bold; use -Bold:$false to remove bold. + + SwitchParameter + + SwitchParameter + + + False + + + Italic + + Make text italic; use -Italic:$false to remove italic. + + SwitchParameter + + SwitchParameter + + + False + + + Underline + + Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. + + SwitchParameter + + SwitchParameter + + + False + + + UnderLineType + + Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". + + ExcelUnderLineType + + ExcelUnderLineType + + + Single + + + StrikeThru + + Strike through text; use -StrikeThru:$false to remove strike through. + + SwitchParameter + + SwitchParameter + + + False + + + FontShift + + Subscript or Superscript (or none). + + ExcelVerticalAlignmentFont + + ExcelVerticalAlignmentFont + + + None + + + FontName + + Font to use - Excel defaults to Calibri. + + String + + String + + + None + + + FontSize + + Point size for the text. + + Single + + Single + + + 0 + + + BackgroundColor + + Change background color. + + Object + + Object + + + None + + + BackgroundPattern + + Background pattern - solid by default. + + ExcelFillStyle + + ExcelFillStyle + + + Solid + + + PatternColor + + Secondary color for background pattern. + + Object + + Object + + + None + + + WrapText + + Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. + + SwitchParameter + + SwitchParameter + + + False + + + HorizontalAlignment + + Position cell contents to Left, Right, Center etc. default is 'General'. + + ExcelHorizontalAlignment + + ExcelHorizontalAlignment + + + None + + + VerticalAlignment + + Position cell contents to Top, Bottom or Center. + + ExcelVerticalAlignment + + ExcelVerticalAlignment + + + None + + + TextRotation + + Degrees to rotate text. Up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise. + + Int32 + + Int32 + + + 0 + + + Height + + Set cells to a fixed height. + + Single + + Single + + + 0 + + + Hide + + Hide the row. + + SwitchParameter + + SwitchParameter + + + False + + + ReturnRange + + If sepecified, returns the range of cells which were affected. + + SwitchParameter + + SwitchParameter + + + False + + + PassThru + + If Specified, return a row object to allow further work to be done. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + OfficeOpenXml.ExcelRow + + + + + + + + System.String + + + + + + + + + + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> Set-ExcelRow -Worksheet $ws -Heading Total -Value {"=sum($columnName`2:$columnName$endrow)" } + + $Ws contains a worksheet object, and no Row number is specified so Set-ExcelRow will select the next row after the end of the data in the sheet. + The first cell in the row will contain "Total", and each of the other cells will contain =Sum(xx2:xx99) where xx is the column name, and 99 is the last row of data. + Note the use of the backtick in the script block (`2) to Prevent 2 becoming part of the variable "ColumnName" + The script block can use $Worksheet, $Row, $Column (number), $ColumnName (letter), $StartRow/Column and $EndRow/Column. + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\> Set-ExcelRow -Worksheet $ws -Heading Total -HeadingBold -Value {"=sum($columnName`2:$columnName$endrow)" } -NumberFormat 'Currency' -StartColumn 2 -Bold -BorderTop Double -BorderBottom Thin + + This builds on the previous example, but this time the label "Total" appears in column 2 and the formula fills from column 3 onwards. + The formula and heading are set in bold face, and the formula is formatted for the local currency, and given a double line border above and single line border below. + + + + + + + + Update-FirstObjectProperties + Update + FirstObjectProperties + + Updates the first object to contain all the properties of the object with the most properties in the array. + + + + Updates the first object to contain all the properties found anywhere in the array. + This is usefull when not all objects have the same quantity of properties and CmdLets like Out-GridView or Export-Excel are not able to show all the properties because the first object doesn't have them all. + + + + Update-FirstObjectProperties + + + + + + + + CHANGELOG 2017/06/08 Function born + + + + + -------------------------- EXAMPLE 1 -------------------------- + PS\> $Array = @() +PS\> $Obj1 = [PSCustomObject]@{ + Member1 = 'First' + Member2 = 'Second' +} +PS\> $Obj2 = [PSCustomObject]@{ + Member1 = 'First' + Member2 = 'Second' + Member3 = 'Third' +} +PS\> $Obj3 = [PSCustomObject]@{ + Member1 = 'First' + Member2 = 'Second' + Member3 = 'Third' + Member4 = 'Fourth' +} +PS\> $Array = $Obj1, $Obj2, $Obj3 +PS\> $Array | Out-GridView -Title 'Not showing Member3 and Member4' +PS\> $Array | Update-FirstObjectProperties | Out-GridView -Title 'All properties are visible' + + Updates the first object of the array by adding Member3 and Member4 and shows before and after in gridviews + + + + -------------------------- EXAMPLE 2 -------------------------- + PS\>$ExcelParams = @{ + Path = $env:TEMP + '\Excel.xlsx' + Show = $true + Verbose = $true +} +PS\> Remove-Item -Path $ExcelParams.Path -Force -EA Ignore +PS\> $Array = @() +PS\> $Obj1 = [PSCustomObjectable@{ + Member1 = 'First' + Member2 = 'Second' +} +PS\> $Obj2 = [PSCustomObject]@{ + Member1 = 'First' + Member2 = 'Second' + Member3 = 'Third' +} +PS\> $Obj3 = [PSCustomObject]@{ + Member1 = 'First' + Member2 = 'Second' + Member3 = 'Third' + Member4 = 'Fourth' +} +PS\> $Array = $Obj1, $Obj2, $Obj3 +PS\> $Array | Out-GridView -Title 'Not showing Member3 and Member4' +PS\> $Array | Update-FirstObjectProperties | Export-Excel @ExcelParams -WorkSheetname Numbers + + Updates the first object of the array by adding property 'Member3' and 'Member4'. Afterwards, all objects are exported to an Excel file and all column headers are visible. + + + + + + https://github.com/dfinke/ImportExcel + https://github.com/dfinke/ImportExcel + + + + \ No newline at end of file diff --git a/mdHelp/Add-ConditionalFormatting.md b/mdHelp/Add-ConditionalFormatting.md new file mode 100644 index 0000000..158fac7 --- /dev/null +++ b/mdHelp/Add-ConditionalFormatting.md @@ -0,0 +1,482 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Add-ConditionalFormatting + +## SYNOPSIS +Adds conditional formatting to all or part of a worksheet. + +## SYNTAX + +### NamedRule +``` +Add-ConditionalFormatting [-Address] [-WorkSheet ] [-RuleType] [-ForegroundColor ] [-Reverse] [[-ConditionValue] ] [[-ConditionValue2] ] [-BackgroundColor ] [-BackgroundPattern ] [-PatternColor ] [-NumberFormat ] [-Bold] [-Italic] [-Underline] [-StrikeThru] [-StopIfTrue] [-Priority ] [-PassThru] [] +``` + +### DataBar +``` +Add-ConditionalFormatting [-Address] [-WorkSheet ] -DataBarColor [-Priority ] [-PassThru] [] +``` + +### ThreeIconSet +``` +Add-ConditionalFormatting [-Address] [-WorkSheet ] -ThreeIconsSet [-Reverse] [-Priority ] [-PassThru] [] +``` + +### FourIconSet +``` +Add-ConditionalFormatting [-Address] [-WorkSheet ] -FourIconsSet [-Reverse] [-Priority ] [-PassThru] [] +``` + +### FiveIconSet +``` +Add-ConditionalFormatting [-Address] [-WorkSheet ] -FiveIconsSet [-Reverse] [-Priority ] [-PassThru] [] +``` + +## DESCRIPTION +Conditional formatting allows Excel to: + +* Mark cells with icons depending on their value +* Show a databar whose length indicates the value or a two or three color scale where the color indicates the relative value +* Change the color, font, or number format of cells which meet given criteria +Add-ConditionalFormatting allows these parameters to be set; for fine tuning of the rules, the -PassThru switch will return the rule so that you can modify things which are specific to that type of rule, example, the values which correspond to each icon in an Icon-Set. + +## 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. + +## PARAMETERS + +### -Address +A block of cells to format - you can use a named range with -Address $ws.names\[1\] or $ws.cells\["RangeName"\] + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: Range + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WorkSheet +The worksheet where the format is to be applied + +```yaml +Type: ExcelWorksheet +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -RuleType +A standard named-rule - Top / Bottom / Less than / Greater than / Contains etc. + +```yaml +Type: eExcelConditionalFormattingRuleType +Parameter Sets: NamedRule +Aliases: +Accepted values: 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 + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ForegroundColor +Text color for matching objects + +```yaml +Type: Object +Parameter Sets: NamedRule +Aliases: ForegroundColour, FontColor + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DataBarColor +Color for databar type charts + +```yaml +Type: Object +Parameter Sets: DataBar +Aliases: DataBarColour + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ThreeIconsSet +One of the three-icon set types (e.g. +Traffic Lights) + +```yaml +Type: eExcelconditionalFormatting3IconsSetType +Parameter Sets: ThreeIconSet +Aliases: +Accepted values: Arrows, ArrowsGray, Flags, Signs, Symbols, Symbols2, TrafficLights1, TrafficLights2 + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FourIconsSet +A four-icon set name + +```yaml +Type: eExcelconditionalFormatting4IconsSetType +Parameter Sets: FourIconSet +Aliases: +Accepted values: Arrows, ArrowsGray, Rating, RedToBlack, TrafficLights + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FiveIconsSet +A five-icon set name + +```yaml +Type: eExcelconditionalFormatting5IconsSetType +Parameter Sets: FiveIconSet +Aliases: +Accepted values: Arrows, ArrowsGray, Quarters, Rating + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Reverse +Use the Icon-Set in reverse order, or reverse the orders of Two- & Three-Color Scales + +```yaml +Type: SwitchParameter +Parameter Sets: NamedRule, ThreeIconSet, FourIconSet, FiveIconSet +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ConditionValue +A value for the condition (for example 2000 if the test is 'lessthan 2000'; Formulas should begin with "=" ) + +```yaml +Type: Object +Parameter Sets: NamedRule +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ConditionValue2 +A second value for the conditions like "Between X and Y" + +```yaml +Type: Object +Parameter Sets: NamedRule +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BackgroundColor +Background color for matching items + +```yaml +Type: Object +Parameter Sets: NamedRule +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BackgroundPattern +Background pattern for matching items + +```yaml +Type: ExcelFillStyle +Parameter Sets: NamedRule +Aliases: +Accepted values: None, Solid, DarkGray, MediumGray, LightGray, Gray125, Gray0625, DarkVertical, DarkHorizontal, DarkDown, DarkUp, DarkGrid, DarkTrellis, LightVertical, LightHorizontal, LightDown, LightUp, LightGrid, LightTrellis + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PatternColor +Secondary color when a background pattern requires it + +```yaml +Type: Object +Parameter Sets: NamedRule +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NumberFormat +Sets the numeric format for matching items + +```yaml +Type: Object +Parameter Sets: NamedRule +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Bold +Put matching items in bold face + +```yaml +Type: SwitchParameter +Parameter Sets: NamedRule +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Italic +Put matching items in italic + +```yaml +Type: SwitchParameter +Parameter Sets: NamedRule +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Underline +Underline matching items + +```yaml +Type: SwitchParameter +Parameter Sets: NamedRule +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StrikeThru +Strikethrough text of matching items + +```yaml +Type: SwitchParameter +Parameter Sets: NamedRule +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StopIfTrue +Prevent the processing of subsequent rules + +```yaml +Type: SwitchParameter +Parameter Sets: NamedRule +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Priority +Set the sequence for rule processing + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +If specified pass the rule back to the caller to allow additional customization. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Add-ExcelChart.md b/mdHelp/Add-ExcelChart.md new file mode 100644 index 0000000..371661e --- /dev/null +++ b/mdHelp/Add-ExcelChart.md @@ -0,0 +1,736 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Add-ExcelChart + +## SYNOPSIS +Creates a chart in an existing Excel worksheet. + +## SYNTAX + +### Worksheet (Default) +``` +Add-ExcelChart [-Title ] [-ChartType ] [-ChartTrendLine ] [-XRange ] [-YRange ] [-Width ] [-Height ] [-Row ] [-RowOffSetPixels ] [-Column ] [-ColumnOffSetPixels ] [-LegendPosition ] [-LegendSize ] [-LegendBold] [-NoLegend] [-ShowCategory] [-ShowPercent] [-SeriesHeader ] [-TitleBold] [-TitleSize ] [-XAxisTitleText ] [-XAxisTitleBold] [-XAxisTitleSize ] [-XAxisNumberformat ] [-XMajorUnit ] [-XMinorUnit ] [-XMaxValue ] [-XMinValue ] [-XAxisPosition ] [-YAxisTitleText ] [-YAxisTitleBold] [-YAxisTitleSize ] [-YAxisNumberformat ] [-YMajorUnit ] [-YMinorUnit ] [-YMaxValue ] [-YMinValue ] [-YAxisPosition ] [-PassThru] [] +``` + +### PivotTable +``` +Add-ExcelChart -PivotTable [-Title ] [-ChartType ] [-ChartTrendLine ] [-XRange ] [-YRange ] [-Width ] [-Height ] [-Row ] [-RowOffSetPixels ] [-Column ] [-ColumnOffSetPixels ] [-LegendPosition ] [-LegendSize ] [-LegendBold] [-NoLegend] [-ShowCategory] [-ShowPercent] [-SeriesHeader ] [-TitleBold] [-TitleSize ] [-XAxisTitleText ] [-XAxisTitleBold] [-XAxisTitleSize ] [-XAxisNumberformat ] [-XMajorUnit ] [-XMinorUnit ] [-XMaxValue ] [-XMinValue ] [-XAxisPosition ] [-YAxisTitleText ] [-YAxisTitleBold] [-YAxisTitleSize ] [-YAxisNumberformat ] [-YMajorUnit ] [-YMinorUnit ] [-YMaxValue ] [-YMinValue ] [-YAxisPosition ] [-PassThru] [] +``` + +## 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 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. + +## 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)". + +## PARAMETERS + +### -Worksheet +An existing Sheet where the chart will be created. + +```yaml +Type: ExcelWorksheet +Parameter Sets: Workshet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotTable +Instead of specify X and Y ranges, get data from a PivotTable by passing a PivotTable Object. + +```yaml +Type: ExcelPivotTable +Parameter Sets: PivotTable +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Title +The title for the chart. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartType +One of the built-in chart types, such as Pie, ClusteredColumn, Line etc. +Defaults to "ColumnStacked". + +```yaml +Type: eChartType +Parameter Sets: (All) +Aliases: +Accepted values: 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 + +Required: False +Position: Named +Default value: ColumnStacked +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartTrendLine +{{ Fill ChartTrendLine Description }} + +```yaml +Type: eTrendLine[] +Parameter Sets: (All) +Aliases: +Accepted values: Exponential, Linear, Logarithmic, MovingAvgerage, Polynomial, Power + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XRange +The range of cells containing values for the X-Axis - usually labels. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YRange +The range(s) of cells holding values for the Y-Axis - usually "data". + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Width +Width of the chart in Pixels; defaults to 500. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 500 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Height +Height of the chart in Pixels; defaults to 350. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 350 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Row +Row position of the top left corner of the chart. ) places at the top of the sheet, 1 below row 1 and so on. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -RowOffSetPixels +Offset to position the chart by a fraction of a row. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 10 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Column +Column position of the top left corner of the chart; 0 places at the edge of the sheet 1 to the right of column A and so on. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 6 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ColumnOffSetPixels +Offset to position the chart by a fraction of a column. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 5 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LegendPosition +Location of the key, either left, right, top, bottom or TopRight. + +```yaml +Type: eLegendPosition +Parameter Sets: (All) +Aliases: +Accepted values: Top, Left, Right, Bottom, TopRight + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LegendSize +Font size for the key. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LegendBold +Sets the key in bold type. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoLegend +If specified, turns of display of the key. If you only have one data series it may be preferable to use the title to say what the chart is. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowCategory +Attaches a category label, in charts which support this. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowPercent +Attaches a percentage label, in charts which support this. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SeriesHeader +Specify explicit name(s) for the data series, which will appear in the legend/key. The contents of a cell can be specified in the from =Sheet9!Z10 . + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TitleBold +Sets the title in bold face. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TitleSize +Sets the point size for the title. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XAxisTitleText +Specifies a title for the X-axis. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XAxisTitleBold +Sets the X-axis title in bold face. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XAxisTitleSize +Sets the font size for the axis title. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XAxisNumberformat +A number formatting string, like "#,##0.00", for numbers along the X-axis. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XMajorUnit +Spacing for the major gridlines / tick marks along the X-axis. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XMinorUnit +Spacing for the minor gridlines / tick marks along the X-axis. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XMaxValue +Maximum value for the scale along the X-axis. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XMinValue +Minimum value for the scale along the X-axis. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XAxisPosition +Position for the X-axis (Top or Bottom). + +```yaml +Type: eAxisPosition +Parameter Sets: (All) +Aliases: +Accepted values: Left, Bottom, Right, Top + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YAxisTitleText +Specifies a title for the Y-axis. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YAxisTitleBold +Sets the Y-axis title in bold face. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YAxisTitleSize +Sets the font size for the Y-axis title + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YAxisNumberformat +A number formatting string, like "#,##0.00", for numbers on the Y-axis. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YMajorUnit +Spacing for the major gridlines / tick marks on the Y-axis. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YMinorUnit +Spacing for the minor gridlines / tick marks on the Y-axis. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YMaxValue +Maximum value on the Y-axis. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YMinValue +Minimum value on the Y-axis. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YAxisPosition +Position for the Y-axis (Left or Right). + +```yaml +Type: eAxisPosition +Parameter Sets: (All) +Aliases: +Accepted values: Left, Bottom, Right, Top + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### OfficeOpenXml.Drawing.Chart.ExcelChart +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Add-ExcelDataValidationRule.md b/mdHelp/Add-ExcelDataValidationRule.md new file mode 100644 index 0000000..af06331 --- /dev/null +++ b/mdHelp/Add-ExcelDataValidationRule.md @@ -0,0 +1,319 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Add-ExcelDataValidationRule + +## SYNOPSIS +Adds data validation to a range of cells + +## SYNTAX + +``` +Add-ExcelDataValidationRule [[-Range] ] [-WorkSheet ] [-ValidationType ] [-Operator ] [-Value ] [-Value2 ] [-Formula ] [-Formula2 ] [-ValueSet ] [-ShowErrorMessage] [-ErrorStyle ] [-ErrorTitle ] [-ErrorBody ] [-ShowPromptMessage] [-PromptBody ] [-PromptTitle ] [-NoBlank ] [] +``` + +## DESCRIPTION +Excel supports the validation of user input, and ranges of cells can be marked to only contain numbers, or date, or Text up to a particular length, or selections from a list. This command adds validation rules to a worksheet. + +## 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. + +## PARAMETERS + +### -Range +The range of cells to be validate, for example, "B2:C100" + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: Address + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -WorkSheet +The worksheet where the cells should be validated + +```yaml +Type: ExcelWorksheet +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ValidationType +An option corresponding to a choice from the 'Allow' pull down on the settings page in the Excel dialog. "Any" means "any allowed" - in other words, no Validation + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Operator +The operator to apply to Decimal, Integer, TextLength, DateTime and time fields, for example "equal" or "between" + +```yaml +Type: ExcelDataValidationOperator +Parameter Sets: (All) +Aliases: +Accepted values: between, notBetween, equal, notEqual, lessThan, lessThanOrEqual, greaterThan, greaterThanOrEqual + +Required: False +Position: Named +Default value: Equal +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Value +For Decimal, Integer, TextLength, DateTime the \[first\] data value + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Value2 +When using the between operator, the second data value + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Formula +The \[first\] data value as a formula. +Use absolute formulas $A$1 if (e.g.) you want all cells to check against the same list + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Formula2 +When using the between operator, the second data value as a formula + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ValueSet +When using the list validation type, a set of values (rather than refering to Sheet!B$2:B$100 ) + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowErrorMessage +Corresponds to the the 'Show Error alert ...' check box on error alert page in the Excel dialog + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ErrorStyle +Stop, Warning, or Infomation, corresponding to to the style setting in the Excel dialog + +```yaml +Type: ExcelDataValidationWarningStyle +Parameter Sets: (All) +Aliases: +Accepted values: undefined, stop, warning, information + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ErrorTitle +The title for the message box corresponding to to the title setting in the Excel dialog + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ErrorBody +The error message corresponding to to the Error message setting in the Excel dialog + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowPromptMessage +Corresponds to the the 'Show Input message ...' check box on input message page in the Excel dialog + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PromptBody +The prompt message corresponding to to the Input message setting in the Excel dialog + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PromptTitle +The title for the message box corresponding to to the title setting in the Excel dialog + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoBlank +By default the 'Ignore blank' option will be selected, unless NoBlank is sepcified. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Add-ExcelName.md b/mdHelp/Add-ExcelName.md new file mode 100644 index 0000000..df1eb37 --- /dev/null +++ b/mdHelp/Add-ExcelName.md @@ -0,0 +1,72 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Add-ExcelName + +## SYNOPSIS +Adds a named-range to an existing Excel worksheet. + +## SYNTAX + +``` +Add-ExcelName [-Range] [[-RangeName] ] [] +``` + +## 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. + +## 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. + +## PARAMETERS + +### -Range +The range of cells to assign as a name. + +```yaml +Type: ExcelRange +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -RangeName +The name to assign to the range. If the name exists it will be updated to the new range. If no name is specified, the first cell in the range will be used as the name. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Add-ExcelTable.md b/mdHelp/Add-ExcelTable.md new file mode 100644 index 0000000..200ad0d --- /dev/null +++ b/mdHelp/Add-ExcelTable.md @@ -0,0 +1,236 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Add-ExcelTable + +## SYNOPSIS +Adds Tables to Excel workbooks. + +## SYNTAX + +``` +Add-ExcelTable [-Range] [[-TableName] ] [[-TableStyle] ] [-ShowHeader] [-ShowFilter] [-ShowTotal] [[-TotalSettings] ] [-ShowFirstColumn] [-ShowLastColumn] [-ShowRowStripes] [-ShowColumnStripes] [-PassThru] [] +``` + +## DESCRIPTION +Unlike named ranges, where the name only needs to be unique within a sheet, Table names must be unique in the workbook. + +Tables carry formatting and by default have a filter. + +The filter, header, totals, first and last column highlights can all be configured. + +## 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. + +## PARAMETERS + +### -Range +The range of cells to assign to a table. + +```yaml +Type: ExcelRange +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TableName +The name for the Table - this should be unqiue in the Workbook - auto generated names will be used if this is left empty. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TableStyle +The Style for the table, by default "Medium6" is used + +```yaml +Type: TableStyles +Parameter Sets: (All) +Aliases: +Accepted values: 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 + +Required: False +Position: 3 +Default value: Medium6 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowHeader +By default the header row is shown - it can be turned off with -ShowHeader:$false. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowFilter +By default the filter is enabled - it can be turned off with -ShowFilter:$false. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowTotal +Show total adds a totals row. This does not automatically sum the columns but provides a drop-down in each to select sum, average etc + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TotalSettings +A HashTable in the form ColumnName = "Average"|"Count"|"CountNums"|"Max"|"Min"|"None"|"StdDev"|"Sum"|"Var" - if specified, -ShowTotal is not needed. + +```yaml +Type: Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowFirstColumn +Highlights the first column in bold. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowLastColumn +Highlights the last column in bold. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowRowStripes +By default the table formats show striped rows, the can be turned off with -ShowRowStripes:$false + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowColumnStripes +Turns on column stripes. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +If -PassThru is specified, the table object will be returned to allow additional changes to be made. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### OfficeOpenXml.Table.ExcelTable +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Add-PivotTable.md b/mdHelp/Add-PivotTable.md new file mode 100644 index 0000000..7f4f1cd --- /dev/null +++ b/mdHelp/Add-PivotTable.md @@ -0,0 +1,659 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Add-PivotTable + +## SYNOPSIS +Adds a PivotTable (and optional PivotChart) to a workbook. + +## SYNTAX + +### ChartbyParams (Default) +``` +Add-PivotTable -PivotTableName [-Address ] [-ExcelPackage ] [-SourceWorkSheet ] [-SourceRange ] [-PivotRows ] [-PivotData ] [-PivotColumns ] [-PivotFilter ] [-PivotDataToColumn] [-PivotTotals ] [-NoTotalsInPivot] [-GroupDateRow ] [-GroupDatePart ] [-GroupNumericRow ] [-GroupNumericMin ] [-GroupNumericMax ] [-GroupNumericInterval ] [-PivotNumberFormat ] [-PivotTableStyle ] [-IncludePivotChart] [-ChartTitle ] [-ChartHeight ] [-ChartWidth ] [-ChartRow ] [-ChartColumn ] [-ChartRowOffSetPixels ] [-ChartColumnOffSetPixels ] [-ChartType ] [-NoLegend] [-ShowCategory] [-ShowPercent] [-Activate] [-PassThru] [] +``` + +### ChartbyDef +``` +Add-PivotTable -PivotTableName [-Address ] [-ExcelPackage ] [-SourceWorkSheet ] [-SourceRange ] [-PivotRows ] [-PivotData ] [-PivotColumns ] [-PivotFilter ] [-PivotDataToColumn] [-PivotTotals ] [-NoTotalsInPivot] [-GroupDateRow ] [-GroupDatePart ] [-GroupNumericRow ] [-GroupNumericMin ] [-GroupNumericMax ] [-GroupNumericInterval ] [-PivotNumberFormat ] [-PivotTableStyle ] -PivotChartDefinition [-Activate] [-PassThru] [] +``` + +## DESCRIPTION +If the PivotTable already exists, the source data will be updated. + +## 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. + +## PARAMETERS + +### -PivotTableName +Name for the new PivotTable - this will be the name of a sheet in the Workbook. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Address +By default, a PivotTable will be created on its own sheet, but it can be created on an existing sheet by giving the address where the top left corner of the table should go. (Allow two rows for the filter if one is used.) + +```yaml +Type: ExcelAddressBase +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcelPackage +An Excel-package object for the workbook. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SourceWorkSheet +Worksheet where the data is found. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SourceRange +Address range in the worksheet e.g "A10:F20" - the first row must be column names: if not specified the whole sheet will be used. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotRows +Fields to set as rows in the PivotTable. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotData +A hash table in form "FieldName"="Function", where function is one of Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotColumns +Fields to set as columns in the PivotTable. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotFilter +Fields to use to filter in the PivotTable. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotDataToColumn +If there are multiple data items in a PivotTable, by default they are shown on separate rows; this switch makes them separate columns. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotTotals +Define whether totals should be added to rows, columns neither, or both (the default is both). + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: Both +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoTotalsInPivot +Included for compatibility - equivalent to -PivotTotals "None". + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GroupDateRow +The name of a row field which should be grouped by parts of the date/time (ignored if GroupDateRow is not specified) + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GroupDatePart +The Part(s) of the date to use in the grouping (ignored if GroupDateRow is not specified) + +```yaml +Type: eDateGroupBy[] +Parameter Sets: (All) +Aliases: +Accepted values: Years, Quarters, Months, Days, Hours, Minutes, Seconds + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GroupNumericRow +The name of a row field which should be grouped by Number (e.g. 0-99, 100-199, 200-299 ) + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GroupNumericMin +The starting point for grouping + +```yaml +Type: Double +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GroupNumericMax +The endpoint for grouping + +```yaml +Type: Double +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 1.79769313486232E+308 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GroupNumericInterval +The interval for grouping + +```yaml +Type: Double +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 100 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotNumberFormat +Number format to apply to the data cells in the PivotTable. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotTableStyle +Apply a table style to the PivotTable. + +```yaml +Type: TableStyles +Parameter Sets: (All) +Aliases: +Accepted values: 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 + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotChartDefinition +Use a chart definition instead of specifying chart settings one by one. + +```yaml +Type: Object +Parameter Sets: ChartbyDef +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -IncludePivotChart +If specified, a chart will be included. + +```yaml +Type: SwitchParameter +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartTitle +Optional title for the pivot chart, by default the title omitted. + +```yaml +Type: String +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartHeight +Height of the chart in Pixels (400 by default). + +```yaml +Type: Int32 +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: 400 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartWidth +Width of the chart in Pixels (600 by default). + +```yaml +Type: Int32 +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: 600 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartRow +Cell position of the top left corner of the chart, there will be this number of rows above the top edge of the chart (default is 0, chart starts at top edge of row 1). + +```yaml +Type: Int32 +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartColumn +Cell position of the top left corner of the chart, there will be this number of cells to the left of the chart (default is 4, chart starts at left edge of column E). + +```yaml +Type: Int32 +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: 4 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartRowOffSetPixels +Vertical offset of the chart from the cell corner. + +```yaml +Type: Int32 +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartColumnOffSetPixels +Horizontal offset of the chart from the cell corner. + +```yaml +Type: Int32 +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartType +Type of chart; defaults to "Pie". + +```yaml +Type: eChartType +Parameter Sets: ChartbyParams +Aliases: +Accepted values: 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 + +Required: False +Position: Named +Default value: Pie +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoLegend +If specified hides the chart legend. + +```yaml +Type: SwitchParameter +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowCategory +If specified attaches the category to slices in a pie chart : not supported on all chart types, this may give errors if applied to an unsupported type. + +```yaml +Type: SwitchParameter +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowPercent +If specified attaches percentages to slices in a pie chart. + +```yaml +Type: SwitchParameter +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Activate +If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +Return the PivotTable so it can be customized. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### OfficeOpenXml.Table.PivotTable.ExcelPivotTable +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Add-WorkSheet.md b/mdHelp/Add-WorkSheet.md new file mode 100644 index 0000000..9586c2c --- /dev/null +++ b/mdHelp/Add-WorkSheet.md @@ -0,0 +1,248 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Add-WorkSheet + +## SYNOPSIS +Adds a worksheet to an existing workbook. + +## SYNTAX + +### Package +``` +Add-WorkSheet [-ExcelPackage] [-WorksheetName ] [-ClearSheet] [-MoveToStart] [-MoveToEnd] [-MoveBefore ] [-MoveAfter ] [-Activate] [-CopySource ] [-NoClobber] [] +``` + +### WorkBook +``` +Add-WorkSheet -ExcelWorkbook [-WorksheetName ] [-ClearSheet] [-MoveToStart] [-MoveToEnd] [-MoveBefore ] [-MoveAfter ] [-Activate] [-CopySource ] [-NoClobber] [] +``` + +## DESCRIPTION +If the named worksheet already exists, the -Clearsheet parameter decides whether it should be deleted and a new one returned, +or if not specified the existing sheet will be returned. + +By default the sheet is created at the end of the work book, the -MoveXXXX switches allow the sheet to be \[re\]positioned at the start or before or after another sheet. + +A new sheet will only be made the default sheet when excel opens if -Activate is specified. + +## 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. + +## PARAMETERS + +### -ExcelPackage +An object representing an Excel Package. + +```yaml +Type: ExcelPackage +Parameter Sets: Package +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ExcelWorkbook +An Excel Workbook to which the Worksheet will be added - a Package contains one Workbook, so you can use whichever fits at the time. + +```yaml +Type: ExcelWorkbook +Parameter Sets: WorkBook +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WorksheetName +The name of the worksheet, 'Sheet1' by default. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ClearSheet +If the worksheet already exists, by default it will returned, unless -ClearSheet is specified in which case it will be deleted and re-created. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MoveToStart +If specified, the worksheet will be moved to the start of the workbook. + +MoveToStart takes precedence over MoveToEnd, Movebefore and MoveAfter if more than one is specified. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MoveToEnd +If specified, the worksheet will be moved to the end of the workbook. + +(This is the default position for newly created sheets, but it can be used to move existing sheets.) + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MoveBefore +If specified, the worksheet will be moved before the nominated one (which can be an index starting from 1, or a name). + +MoveBefore takes precedence over MoveAfter if both are specified. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MoveAfter +If specified, the worksheet will be moved after the nominated one (which can be an index starting from 1, or a name or *). + +If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Activate +If there is already content in the workbook the new sheet will not be active UNLESS Activate is specified. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CopySource +If worksheet is provided as a copy source the new worksheet will be a copy of it. The source can be in the same workbook, or in a different file. + +```yaml +Type: ExcelWorksheet +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoClobber +Ignored but retained for backwards compatibility. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### OfficeOpenXml.ExcelWorksheet +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Close-ExcelPackage.md b/mdHelp/Close-ExcelPackage.md new file mode 100644 index 0000000..0bab0b6 --- /dev/null +++ b/mdHelp/Close-ExcelPackage.md @@ -0,0 +1,143 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Close-ExcelPackage + +## SYNOPSIS +Closes an Excel Package, saving, saving under a new name or abandoning changes and opening the file in Excel as required. + +## SYNTAX + +``` +Close-ExcelPackage [-ExcelPackage] [-Show] [-NoSave] [[-SaveAs] ] [[-Password] ] [-Calculate] [] +``` + +## DESCRIPTION +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 + +## 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. + +## PARAMETERS + +### -ExcelPackage +Package to close. + +```yaml +Type: ExcelPackage +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Show +Open the file in Excel. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoSave +Abandon the file without saving. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SaveAs +Save file with a new name (ignored if -NoSave Specified). + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Password +Password to protect the file. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Calculate +Attempt to recalculation the workbook before saving + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Compare-WorkSheet.md b/mdHelp/Compare-WorkSheet.md new file mode 100644 index 0000000..429ee2f --- /dev/null +++ b/mdHelp/Compare-WorkSheet.md @@ -0,0 +1,397 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Compare-WorkSheet + +## SYNOPSIS +Compares two worksheets and shows the differences. + +## SYNTAX + +### True (Default) +``` +Compare-WorkSheet [-Referencefile] [-Differencefile] [-WorkSheetName ] [-Property ] [-ExcludeProperty ] [-Startrow ] [-AllDataBackgroundColor ] [-BackgroundColor ] [-TabColor ] [-Key ] [-FontColor ] [-Show] [-GridView] [-PassThru] [-IncludeEqual] [-ExcludeDifferent] [] +``` + +### B +``` +Compare-WorkSheet [-Referencefile] [-Differencefile] [-WorkSheetName ] [-Property ] [-ExcludeProperty ] -Headername [-Startrow ] [-AllDataBackgroundColor ] [-BackgroundColor ] [-TabColor ] [-Key ] [-FontColor ] [-Show] [-GridView] [-PassThru] [-IncludeEqual] [-ExcludeDifferent] [] +``` + +### C +``` +Compare-WorkSheet [-Referencefile] [-Differencefile] [-WorkSheetName ] [-Property ] [-ExcludeProperty ] [-NoHeader] [-Startrow ] [-AllDataBackgroundColor ] [-BackgroundColor ] [-TabColor ] [-Key ] [-FontColor ] [-Show] [-GridView] [-PassThru] [-IncludeEqual] [-ExcludeDifferent] [] +``` + +## DESCRIPTION +This command takes two file names, one or two worksheet names and a name for a "key" column. + +It reads the worksheet from each file and decides the column names and builds a hashtable of the key-column values and the +rows in which they appear. + +It then uses PowerShell's Compare-Object command to compare the sheets (explicitly checking all the column names which have not been excluded). + +For the difference rows it adds the row number for the key of that row - we have to add the key after doing the comparison, otherwise identical rows at different positions in the file will not be considered a match. + +We also add the name of the file and sheet in which the difference occurs. + +If -BackgroundColor is specified the difference rows will be changed to that background in the orginal file. + +## 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. + +## PARAMETERS + +### -Referencefile +First file to compare. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Differencefile +Second file to compare. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WorkSheetName +Name(s) of worksheets to compare. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: Sheet1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Property +Properties to include in the comparison - supports wildcards, default is "*". + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: * +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcludeProperty +Properties to exclude from the comparison - supports wildcards. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Headername +Specifies custom property names to use, instead of the values defined in the starting row of the sheet. + +```yaml +Type: String[] +Parameter Sets: B +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoHeader +Automatically generate property names (P1, P2, P3 ...) instead of the using the values the starting row of the sheet. + +```yaml +Type: SwitchParameter +Parameter Sets: C +Aliases: + +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Startrow +The row from where we start to import data: all rows above the start row are disregarded. By default, this is the first row. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AllDataBackgroundColor +If specified, highlights all the cells - so you can make Equal cells one color, and Different cells another. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BackgroundColor +If specified, highlights the rows with differences. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TabColor +If specified identifies the tabs which contain difference rows (ignored if -BackgroundColor is omitted). + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Key +Name of a column which is unique and will be used to add a row to the DIFF object, defaults to "Name". + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: Name +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FontColor +If specified, highlights the DIFF columns in rows which have the same key. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Show +If specified, opens the Excel workbooks instead of outputting the diff to the console (unless -PassThru is also specified). + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GridView +If specified, the command tries to the show the DIFF in a Grid-View and not on the console (unless-PassThru is also specified). +This works best with few columns selected, and requires a key. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +If specified a full set of DIFF data is returned without filtering to the specified properties. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -IncludeEqual +If specified the result will include equal rows as well. By default only different rows are returned. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcludeDifferent +If specified, the result includes only the rows where both are equal. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Convert-ExcelRangeToImage.md b/mdHelp/Convert-ExcelRangeToImage.md new file mode 100644 index 0000000..ba09ea5 --- /dev/null +++ b/mdHelp/Convert-ExcelRangeToImage.md @@ -0,0 +1,117 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Convert-ExcelRangeToImage + +## SYNOPSIS +Gets the specified part of an Excel file and exports it as an image + +## SYNTAX + +``` +Convert-ExcelRangeToImage [-Path] [[-workSheetname] ] [-range] [[-destination] ] [-show] [] +``` + +## DESCRIPTION +Excel allows charts to be exported directly to a file, but it can't do this with the rest of a sheet. To work round this, this function + +* Opens a copy of Excel and loads a file +* Selects a worksheet and then a range of cells in that worksheet +* Copies the select to the clipboard +* Saves the clipboard contents as an image file (it will save as .JPG unless the file name ends .BMP or .PNG) +* Copies a single cell to the clipboard (to prevent the "you have put a lot in the clipboard" message appearing) +* Closes Excel +Unlike most functions in the module it needs a local copy of Excel to be installed. +## EXAMPLES + +## PARAMETERS + +### -Path +Path to the Excel file + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WorkSheetname +Worksheet name - if none is specified "Sheet1" will be assumed + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: Sheet1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Range +Range of cells within the sheet, e.g "A1:Z99" + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Destination +A bmp, png or jpg file where the result will be saved + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: "$pwd\temp.png" +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Show +If specified opens the image in the default viewer. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/mdHelp/ConvertFrom-ExcelToSQLInsert.md b/mdHelp/ConvertFrom-ExcelToSQLInsert.md new file mode 100644 index 0000000..b178c1a --- /dev/null +++ b/mdHelp/ConvertFrom-ExcelToSQLInsert.md @@ -0,0 +1,225 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# ConvertFrom-ExcelToSQLInsert + +## SYNOPSIS +Generate SQL insert statements from Excel spreadsheet. + +## SYNTAX + +``` +ConvertFrom-ExcelToSQLInsert [-TableName] [-Path] [[-WorkSheetname] ] [[-StartRow] ] [[-Header] ] [-NoHeader] [-DataOnly] [-ConvertEmptyStringsToNull] [-UseMSSQLSyntax] [] +``` + +## DESCRIPTION +Generate SQL insert statements from Excel spreadsheet. + +## 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); +``` + +## PARAMETERS + +### -TableName +Name of the target database table. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Path +Path to an existing .XLSX file +This parameter is passed to Import-Excel as is. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: FullName + +Required: True +Position: 2 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -WorkSheetname +Specifies the name of the worksheet in the Excel workbook to import. +By default, if no name is provided, the first worksheet will be imported. +This parameter is passed to Import-Excel as is. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: Sheet + +Required: False +Position: 3 +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StartRow +The row from where we start to import data, all rows above the StartRow are disregarded. +By default this is the first row. +When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. +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. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: HeaderRow, TopRow + +Required: False +Position: 4 +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Header +Specifies custom property names to use, instead of the values defined in the column headers of the TopRow. +If you provide fewr header names than there is data in the worksheet, then only the data with a corresponding header name will be imported and the data without header name will be disregarded. +If you provide more header names than there is data in the worksheet, then all data will be imported and all objects will have all the property names you defined in the header names. +As such, the last properties will be blank as there is no data for them. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoHeader +Automatically generate property names (P1, P2, P3, ..) instead of the ones defined in the column headers of the TopRow. +This switch is best used when you want to import the complete worksheet 'as is' and are not concerned with the property names. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DataOnly +Import only rows and columns that contain data, empty rows and empty columns are not imported. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ConvertEmptyStringsToNull +If specified, cells without any data are replaced with NULL, instead of an empty string. +This is to address behviors in certain DBMS where an empty string is insert as 0 for INT column, instead of a NULL value. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UseMSSQLSyntax +{{ Fill UseMSSQLSyntax Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Copy-ExcelWorkSheet.md b/mdHelp/Copy-ExcelWorkSheet.md new file mode 100644 index 0000000..85f9a89 --- /dev/null +++ b/mdHelp/Copy-ExcelWorkSheet.md @@ -0,0 +1,150 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Copy-ExcelWorkSheet + +## SYNOPSIS +Copies a worksheet between workbooks or within the same workbook. + +## SYNTAX + +``` +Copy-ExcelWorkSheet [-SourceObject] [[-SourceWorkSheet] ] [-DestinationWorkbook] + [[-DestinationWorksheet] ] [-Show] [] +``` + +## DESCRIPTION +Copy-ExcelWorkSheet takes a Source object which is either a worksheet, +or a package, Workbook or path, in which case the source worksheet can be specified +by name or number (starting from 1). +The destination worksheet can be explicitly named, or will follow the name of the source if no name is specified. +The Destination workbook can be given as the path to an XLSx file, an ExcelPackage object or an ExcelWorkbook object. + +## 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 + +## PARAMETERS + +### -SourceObject +An ExcelWorkbook or ExcelPackage object or the path to an XLSx file where the data is found. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: SourceWorkbook + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -SourceWorkSheet +Name or number (starting from 1) of the worksheet in the source workbook (defaults to 1). + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DestinationWorkbook +An ExcelWorkbook or ExcelPackage object or the path to an XLSx file where the data should be copied. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DestinationWorksheet +Name of the worksheet in the destination workbook; by default the same as the source worksheet's name. +If the sheet exists it will be deleted and re-copied. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Show +if the destination is an excel package or a path, launch excel and open the file on completion. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Expand-NumberFormat.md b/mdHelp/Expand-NumberFormat.md new file mode 100644 index 0000000..c643555 --- /dev/null +++ b/mdHelp/Expand-NumberFormat.md @@ -0,0 +1,70 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Expand-NumberFormat + +## SYNOPSIS +Converts short names for number formats to the formatting strings used in Excel + +## SYNTAX + +``` +Expand-NumberFormat [[-NumberFormat] ] [] +``` + +## DESCRIPTION +Where you can type a number format you can write, for example, 'Short-Date' and the module will translate it into the format string used by Excel. Some formats, like Short-Date, change when Excel loads (so date will use the local ordering of year, month and Day). Excel also changes how markers in the are presented different cultures "," is used in the format string to mean "local thousand seperator" but depending on the country "," or "." or " " may used as the thousand seperator. + +## 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. + +## PARAMETERS + +### -NumberFormat +The format string to Expand + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### System.String +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Export-Excel.md b/mdHelp/Export-Excel.md new file mode 100644 index 0000000..e4e3c1b --- /dev/null +++ b/mdHelp/Export-Excel.md @@ -0,0 +1,1397 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Export-Excel + +## SYNOPSIS +Exports data to an Excel worksheet. + +## SYNTAX + +### Default (Default) +``` +Export-Excel [[-Path] ] [-InputObject ] [-Calculate] [-Show] [-WorksheetName ] [-Password ] [-ClearSheet] [-Append] [-Title ] [-TitleFillPattern ] [-TitleBold] [-TitleSize ] [-TitleBackgroundColor ][-IncludePivotTable] [-PivotTableName ] [-PivotRows [-PivotColumns ] [-PivotData ] [-PivotFilter ] [-PivotDataToColumn] [-PivotTableDefinition ] [-IncludePivotChart] [-ChartType ] [-NoLegend] [-ShowCategory] [-ShowPercent] [-AutoSize] [-MaxAutoSizeRows ] [-NoClobber] [-FreezeTopRow] [-FreezeFirstColumn] [-FreezeTopRowFirstColumn] [-FreezePane ] [-AutoFilter] [-BoldTopRow] [-NoHeader] [-RangeName ] [-TableName ] [-TableStyle ] [-Barchart] [-PieChart] [-LineChart] [-ColumnChart] [-ExcelChartDefinition ] [-HideSheet ] [-UnHideSheet ] [-MoveToStart] [-MoveToEnd] [-MoveBefore ] [-MoveAfter ] [-KillExcel] [-AutoNameRange] [-StartRow ] [-StartColumn ] [-PassThru] [-Numberformat ] [-ExcludeProperty ] [-NoAliasOrScriptPropeties] [-DisplayPropertySet] [-NoNumberConversion ] [-ConditionalFormat ] [-ConditionalText ] [-Style ] [-CellStyleSB ] [-Activate] [-Now] [-ReturnRange] [-PivotTotals ] [-NoTotalsInPivot] [-ReZip] [] +``` + +### Package +``` +Export-Excel -ExcelPackage [-InputObject ] [-Calculate] [-Show] [-WorksheetName ] [-Password ] [-ClearSheet] [-Append] [-Title ] [-TitleFillPattern ] [-TitleBold] [-TitleSize ] [-TitleBackgroundColor ] [-IncludePivotTable] [-PivotTableName ] [-PivotRows ] [-PivotColumns ] [-PivotData ] [-PivotFilter ] [-PivotDataToColumn] [-PivotTableDefinition ] [-IncludePivotChart] [-ChartType ] [-NoLegend] [-ShowCategory] [-ShowPercent] [-AutoSize] [-MaxAutoSizeRows ] [-NoClobber] [-FreezeTopRow] [-FreezeFirstColumn] [-FreezeTopRowFirstColumn] [-FreezePane ] [-AutoFilter] [-BoldTopRow] [-NoHeader] [-RangeName ] [-TableName ] [-TableStyle ] [-Barchart] [-PieChart] [-LineChart] [-ColumnChart] [-ExcelChartDefinition ] [-HideSheet ] [-UnHideSheet ] [-MoveToStart] [-MoveToEnd] [-MoveBefore ] [-MoveAfter ] [-KillExcel] [-AutoNameRange] [-StartRow ] [-StartColumn ] [-PassThru] [-Numberformat ] [-ExcludeProperty ] + [-NoAliasOrScriptPropeties] [-DisplayPropertySet] [-NoNumberConversion ] [-ConditionalFormat ] [-ConditionalText ] [-Style ] [-CellStyleSB ] [-Activate] [-ReturnRange] [-PivotTotals ] [-NoTotalsInPivot] [-ReZip] [] +``` + +## DESCRIPTION +Exports data to an Excel file and where possible tries to convert numbers in text fields so Excel recognizes them as numbers instead of text. After all: Excel is a spreadsheet program used for number manipulation and calculations. +The parameter -NoNumberConversion * can be used if number conversion is not desired. + +## 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. + +## PARAMETERS + +### -Path +Path to a new or existing .XLSX file. + +```yaml +Type: String +Parameter Sets: Default +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcelPackage +An object representing an Excel Package - usually this is returned by specifying -PassThru allowing multiple commands to work on the same workbook without saving and reloading each time. + +```yaml +Type: ExcelPackage +Parameter Sets: Package +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Date is usually piped into Export-Excel, but it also accepts data through the InputObject parameter + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: TargetData + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Calculate +If specified, a recalculation of the worksheet will be requested before saving. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Show +Opens the Excel file immediately after creation; convenient for viewing the results instantly without having to search for the file first. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WorksheetName +The name of a sheet within the workbook - "Sheet1" by default. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: Sheet1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Password +Sets password protection on the workbook. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ClearSheet +If specified Export-Excel will remove any existing worksheet with the selected name. + +The default behaviour is to overwrite cells in this sheet as needed (but leaving non-overwritten ones in place). + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Append +If specified data will be added to the end of an existing sheet, using the same column headings. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Title +Text of a title to be placed in the top left cell. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TitleFillPattern +Sets the fill pattern for the title cell. + +```yaml +Type: ExcelFillStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Solid, DarkGray, MediumGray, LightGray, Gray125, Gray0625, DarkVertical, DarkHorizontal, DarkDown, DarkUp, DarkGrid, DarkTrellis, LightVertical, LightHorizontal, LightDown, LightUp, LightGrid, LightTrellis + +Required: False +Position: Named +Default value: Solid +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TitleBold +Sets the title in boldface type. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TitleSize +Sets the point size for the title. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 22 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TitleBackgroundColor +Sets the cell background color for the title cell. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -IncludePivotTable +Adds a PivotTable using the data in the worksheet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotTableName +If a PivotTable is created from command line parameters, specifies the name of the new sheet holding the pivot. Defaults to "WorksheetName-PivotTable". + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotRows +Name(s) of column(s) from the spreadsheet which will provide the Row name(s) in a PivotTable created from command line parameters. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotColumns +Name(s) of columns from the spreadsheet which will provide the Column name(s) in a PivotTable created from command line parameters. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotData +In a PivotTable created from command line parameters, the fields to use in the table body are given as a Hash-table in the form + +ColumnName = Average|Count|CountNums|Max|Min|Product|None|StdDev|StdDevP|Sum|Var|VarP. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotFilter +Name(s) columns from the spreadsheet which will provide the Filter name(s) in a PivotTable created from command line parameters. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotTableDefinition +Instead of describing a single PivotTable with multiple command-line parameters; you can use a HashTable in the form PivotTableName = Definition; + +In this table Definition is itself a Hashtable with Sheet, PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values. The New-PivotTableDefinition command will create the definition from a command line. + +```yaml +Type: Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -IncludePivotChart +Include a chart with the PivotTable - implies -IncludePivotTable. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartType +The type for PivotChart (one of Excel's defined chart types). + +```yaml +Type: eChartType +Parameter Sets: (All) +Aliases: +Accepted values: 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 + +Required: False +Position: Named +Default value: Pie +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoLegend +Exclude the legend from the PivotChart. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowCategory +Add category labels to the PivotChart. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowPercent +Add percentage labels to the PivotChart. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AutoSize +Sizes the width of the Excel column to the maximum width needed to display all the containing data in that cell. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MaxAutoSizeRows +Autosizing can be time consuming, so this sets a maximum number of rows to look at for the Autosize operation. Default is 1000; If 0 is specified ALL rows will be checked + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 1000 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoClobber +Not used. Left in to avoid problems with older scripts, it may be removed in future versions. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FreezeTopRow +Freezes headers etc. in the top row. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FreezeFirstColumn +Freezes titles etc. in the left column. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FreezeTopRowFirstColumn +Freezes top row and left column (equivalent to Freeze pane 2,2 ). + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FreezePane +Freezes panes at specified coordinates (in the form RowNumber, ColumnNumber). + +```yaml +Type: Int32[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AutoFilter +Enables the Excel filter on the complete header row, so users can easily sort, filter and/or search the data in the selected column. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BoldTopRow +Makes the top row boldface. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoHeader +Specifies that field names should not be put at the top of columns. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -RangeName +Makes the data in the worksheet a named range. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TableName +Makes the data in the worksheet a table with a name, and applies a style to it. The name must not contain spaces. If the -Tablestyle parameter is specified without Tablename, "table1", "table2" etc. will be used. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: Table + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TableStyle +Selects the style for the named table - if the Tablename parameter is specified without giving a style, 'Medium6' is used as a default. + +```yaml +Type: TableStyles +Parameter Sets: (All) +Aliases: +Accepted values: 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 + +Required: False +Position: Named +Default value: Medium6 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Barchart +Creates a "quick" bar chart using the first text column as labels and the first numeric column as values. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PieChart +Creates a "quick" pie chart using the first text column as labels and the first numeric column as values. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LineChart +Creates a "quick" line chart using the first text column as labels and the first numeric column as values. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ColumnChart +Creates a "quick" column chart using the first text column as labels and the first numeric column as values. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcelChartDefinition +A hash-table containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more \[non-Pivot\] charts. This can be created with the New-ExcelChartDefinition command. + +```yaml +Type: Object[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HideSheet +Name(s) of Sheet(s) to hide in the workbook, supports wildcards. If the selection would cause all sheets to be hidden, the sheet being worked on will be revealed. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UnHideSheet +Name(s) of Sheet(s) to reveal in the workbook, supports wildcards. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MoveToStart +If specified, the worksheet will be moved to the start of the workbook. + +-MoveToStart takes precedence over -MoveToEnd, -Movebefore and -MoveAfter if more than one is specified. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MoveToEnd +If specified, the worksheet will be moved to the end of the workbook. (This is the default position for newly created sheets, but the option can be specified to move existing sheets.) + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MoveBefore +If specified, the worksheet will be moved before the nominated one (which can be a position starting from 1, or a name). + +-MoveBefore takes precedence over -MoveAfter if both are specified. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MoveAfter +If specified, the worksheet will be moved after the nominated one (which can be a position starting from 1, or a name or *). + +If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -KillExcel +Closes Excel without stopping to ask if work should be saved - prevents errors writing to the file because Excel has it open. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AutoNameRange +Makes each column a named range. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StartRow +Row to start adding data. 1 by default. +Row 1 will contain the title, if any is specifed. Then headers will appear (Unless -No header is specified) then the data appears. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StartColumn +Column to start adding data - 1 by default. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +If specified, Export-Excel returns an object representing the Excel package without saving the package first. +To save, you must either use the Close-ExcelPackage command, or send the package object back to Export-Excel which will save and close the file, or use the object's .Save() or SaveAs() method. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: PT + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Numberformat +Formats all values that can be converted to a number to the format specified. For examples: +``` +'0' integer (not really needed unless you need to round numbers, Excel will use default cell properties). +'#' integer without displaying the number 0 in the cell. +'0.0' number with 1 decimal place. +'0.00' number with 2 decimal places. +'#,##0.00' number with 2 decimal places and thousand-separator. +'€#,##0.00' number with 2 decimal places and thousand-separator and money-symbol. +'0%' number with 2 decimal places and thousand-separator and money-symbol. +'[Blue]$#,##0.00;[Red]-$#,##0.00' + blue for positive numbers and red for negative numbers; Both proceeded by a '$' sign +``` + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: General +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcludeProperty +Specifies properties which may exist in the target data but should not be placed on the worksheet. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoAliasOrScriptPropeties +Some objects in PowerShell duplicate existing properties by adding aliases, or have Script properties which may take a long time to return a value and slow the export down, if specified this option removes these properties + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DisplayPropertySet +Many (but not all) objects in PowerShell have a hidden property named psStandardmembers with a child property DefaultDisplayPropertySet ; this parameter reduces the properties exported to those in this set. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoNumberConversion +By default the command will convert all values to numbers if possible, but this isn't always desirable. -NoNumberConversion allows you to add exceptions for the conversion. + +The only Wildcard allowed is * for all properties + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ConditionalFormat +One or more conditional formatting rules defined with New-ConditionalFormattingIconSet. + +```yaml +Type: Object[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ConditionalText +Applies a Conditional formatting rule defined with New-ConditionalText. When specific conditions are met the format is applied. + +```yaml +Type: Object[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Style +Takes style settings as a hash-table (which may be built with the New-ExcelStyle command) and applies them to the worksheet. If the hash-table contains a range the settings apply to the range, otherewise they apply to the whole sheet. + +```yaml +Type: Object[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CellStyleSB +A script block which is run at the end of the export to apply styles to cells (although it can be used for other purposes). +The script block is given three paramaters; an object containing the current worksheet, the Total number of Rows and the number of the last column. + +```yaml +Type: ScriptBlock +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Activate +If there is already content in the workbook, a new sheet will not be active UNLESS Activate is specified; when a PivotTable is created its sheet will be activated by this switch. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Now +The -Now switch is a shortcut that automatically creates a temporary file, enables "AutoSize", "TableName" and "Show", and opens the file immediately. + +```yaml +Type: SwitchParameter +Parameter Sets: Default +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ReturnRange +If specified, Export-Excel returns the range of added cells in the format "A1:Z100". + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotTotals +By default, PivotTables have totals for each row (on the right) and for each column at the bottom. This allows just one or neither to be selected. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: Both +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoTotalsInPivot +In a PivotTable created from command line parameters, prevents the addition of totals to rows and columns. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ReZip +If specified, Export-Excel will expand the contents of the .XLSX file (which is multiple files in a zip archive) and rebuild it. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### OfficeOpenXml.ExcelPackage +## NOTES + +## RELATED LINKS + +[https://github.com/dfinke/ImportExcel](https://github.com/dfinke/ImportExcel) + diff --git a/mdHelp/Get-ExcelSheetInfo.md b/mdHelp/Get-ExcelSheetInfo.md new file mode 100644 index 0000000..5d718c3 --- /dev/null +++ b/mdHelp/Get-ExcelSheetInfo.md @@ -0,0 +1,60 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Get-ExcelSheetInfo + +## SYNOPSIS +Get worksheet names and their indices of an Excel workbook. + +## SYNTAX + +``` +Get-ExcelSheetInfo [-Path] [] +``` + +## DESCRIPTION +The Get-ExcelSheetInfo cmdlet gets worksheet names and their indices of an Excel workbook. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-ExcelSheetInfo .\Test.xlsx +``` + +## PARAMETERS + +### -Path +Specifies the path to the Excel file. (This parameter is required.) + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: FullName + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +CHANGELOG +2016/01/07 Added Created by Johan Akerstrom (https://github.com/CosmosKey) + +## RELATED LINKS + +[https://github.com/dfinke/ImportExcel](https://github.com/dfinke/ImportExcel) + diff --git a/mdHelp/Get-ExcelWorkbookInfo.md b/mdHelp/Get-ExcelWorkbookInfo.md new file mode 100644 index 0000000..287db1f --- /dev/null +++ b/mdHelp/Get-ExcelWorkbookInfo.md @@ -0,0 +1,82 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Get-ExcelWorkbookInfo + +## SYNOPSIS +Retrieve information of an Excel workbook. + +## SYNTAX + +``` +Get-ExcelWorkbookInfo [-Path] [] +``` + +## DESCRIPTION +The Get-ExcelWorkbookInfo cmdlet retrieves information (LastModifiedBy, LastPrinted, Created, Modified, ...) fron an Excel workbook. +These are the same details that are visible in Windows Explorer when right clicking the Excel file, selecting Properties and check the Details tabpage. + +## 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 + +## PARAMETERS + +### -Path +Specifies the path to the Excel file. +This parameter is required. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: FullName + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +CHANGELOG +2016/01/07 Added Created by Johan Akerstrom (https://github.com/CosmosKey) + +## RELATED LINKS + +[https://github.com/dfinke/ImportExcel](https://github.com/dfinke/ImportExcel) + diff --git a/mdHelp/Import-Excel.md b/mdHelp/Import-Excel.md new file mode 100644 index 0000000..159f13d --- /dev/null +++ b/mdHelp/Import-Excel.md @@ -0,0 +1,425 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Import-Excel + +## SYNOPSIS +Create custom objects from the rows in an Excel worksheet. + +## SYNTAX + +### PathC +``` +Import-Excel [-Path] [[-WorksheetName] ] [-NoHeader] [-StartRow ] [-EndRow ] [-StartColumn ] [-EndColumn ] [-DataOnly] [-AsText ] [-Password ] [] +``` + +### PathB +``` +Import-Excel [-Path] [[-WorksheetName] ] -HeaderName [-StartRow ] [-EndRow ] [-StartColumn ] [-EndColumn ] [-DataOnly] [-AsText ] [-Password ] [] +``` + +### PathA +``` +Import-Excel [-Path] [[-WorksheetName] ] [-StartRow ] [-EndRow ] [-StartColumn ] [-EndColumn ] [-DataOnly] [-AsText ] [-Password ] [] +``` + +### PackageC +``` +Import-Excel -ExcelPackage [[-WorksheetName] ] [-NoHeader] [-StartRow ] [-EndRow ] [-StartColumn ] [-EndColumn ] [-DataOnly] [-AsText ] [-Password ] [] +``` + +### PackageB +``` +Import-Excel -ExcelPackage [[-WorksheetName] ] -HeaderName [-StartRow ] [-EndRow ] [-StartColumn ] [-EndColumn ] [-DataOnly] [-AsText ] [-Password ] [] +``` + +### PackageA +``` +Import-Excel -ExcelPackage [[-WorksheetName] ] [-StartRow ] [-EndRow ] [-StartColumn ] [-EndColumn ] [-DataOnly] [-AsText ] [-Password ] [] +``` + +## DESCRIPTION +The Import-Excel cmdlet creates custom objects from the rows in an Excel worksheet. Each row is represented as one object. + +This is possible without installing Microsoft Excel by using the .NET library 'EPPLus.dll'. + +By default, the property names of the objects are retrieved from the column headers. Because an object cannot have a blank property name, only columns with column headers will be imported. + +If the default behavior is not desired and you want to import the complete worksheet 'as is', the parameter '-NoHeader' can be used. +In case you want to provide your own property names, you can use the parameter '-HeaderName'. + +## 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. + +## PARAMETERS + +### -Path +Specifies the path to the Excel file. + +```yaml +Type: String +Parameter Sets: PathC, PathB, PathA +Aliases: FullName + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -ExcelPackage +Instead of specifying a path, provides an Excel Package object (from Open-ExcelPackage). Using this avoids re-reading the whole file when importing multiple parts of it. + +To allow multiple read operations Import-Excel does NOT close the package, and you should use Close-ExcelPackage -noSave to close it. + +```yaml +Type: ExcelPackage +Parameter Sets: PackageC, PackageB, PackageA +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WorksheetName +Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: Sheet + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HeaderName +Specifies custom property names to use, instead of the values defined in the column headers of the TopRow. + +If you provide fewer header names than there are columns of data in the worksheet, then data will only be imported from that number of columns - the others will be ignored. + +If you provide more header names than there are columns of data in the worksheet, it will result in blank properties being added to the objects returned. + +```yaml +Type: String[] +Parameter Sets: PathB, PackageB +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoHeader +Automatically generate property names (P1, P2, P3, ..) instead of the ones defined in the column headers of the TopRow. + +This switch is best used when you want to import the complete worksheet 'as is' and are not concerned with the property names. + +```yaml +Type: SwitchParameter +Parameter Sets: PathC, PackageC +Aliases: + +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StartRow +The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. + +When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. If either is provided, the property names are automatically created and this row will be treated as a regular row containing data. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: HeaderRow, TopRow + +Required: False +Position: Named +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -EndRow +By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: StopRow, BottomRow + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StartColumn +The number of the first column to read data from (1 by default). + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: LeftColumn + +Required: False +Position: Named +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -EndColumn +By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: RightColumn + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DataOnly +Import only rows and columns that contain data, empty rows and empty columns are not imported. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AsText +Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. (* is supported as a wildcard.) + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Password +Accepts a string that will be used to open a password protected Excel file. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://github.com/dfinke/ImportExcel](https://github.com/dfinke/ImportExcel) + diff --git a/mdHelp/Join-Worksheet.md b/mdHelp/Join-Worksheet.md new file mode 100644 index 0000000..ad9fc2f --- /dev/null +++ b/mdHelp/Join-Worksheet.md @@ -0,0 +1,553 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Join-Worksheet + +## SYNOPSIS +Combines data on all the sheets in an Excel worksheet onto a single sheet. + +## SYNTAX + +### Default (Default) +``` +Join-Worksheet [[-Path] ] [-WorkSheetName ] [-Clearsheet] [-NoHeader] [-FromLabel ] [-LabelBlocks] [-AutoSize] [-FreezeTopRow] [-FreezeFirstColumn] [-FreezeTopRowFirstColumn] [-FreezePane ] [-AutoFilter] [-BoldTopRow] [-HideSource] [-Title ] [-TitleFillPattern ] [-TitleBackgroundColor ] [-TitleBold] [-TitleSize ] [-PivotTableDefinition ] [-ExcelChartDefinition ] [-ConditionalFormat ] [-ConditionalText ] [-AutoNameRange] [-RangeName ] [-ReturnRange] [-Show] [-PassThru][] +``` + +### Table +``` +Join-Worksheet [[-Path] ] [-WorkSheetName ] [-Clearsheet] [-NoHeader] [-FromLabel ] [-LabelBlocks] [-AutoSize] [-FreezeTopRow] [-FreezeFirstColumn] [-FreezeTopRowFirstColumn] [-FreezePane ] [-BoldTopRow] [-HideSource] [-Title ] [-TitleFillPattern ] [-TitleBackgroundColor ] [-TitleBold] [-TitleSize ] [-PivotTableDefinition ] [-ExcelChartDefinition ] [-ConditionalFormat ] [-ConditionalText ] [-AutoNameRange] [-RangeName ] -TableName [-TableStyle ] [-ReturnRange] [-Show] [-PassThru] [] +``` + +### PackageTable +``` +Join-Worksheet -ExcelPackage [-WorkSheetName ] [-Clearsheet] [-NoHeader] [-FromLabel ] [-LabelBlocks] [-AutoSize] [-FreezeTopRow] [-FreezeFirstColumn] [-FreezeTopRowFirstColumn] [-FreezePane ] [-BoldTopRow] [-HideSource] [-Title ] [-TitleFillPattern ] [-TitleBackgroundColor ] [-TitleBold] [-TitleSize ] [-PivotTableDefinition ] [-ExcelChartDefinition ] [-ConditionalFormat ] [-ConditionalText ] [-AutoNameRange] [-RangeName ] -TableName [-TableStyle ] [-ReturnRange] [-Show] [-PassThru] [] +``` + +### PackageDefault +``` +Join-Worksheet -ExcelPackage [-WorkSheetName ] [-Clearsheet] [-NoHeader] [-FromLabel ] [-LabelBlocks] [-AutoSize] [-FreezeTopRow] [-FreezeFirstColumn] [-FreezeTopRowFirstColumn] [-FreezePane ] [-AutoFilter] [-BoldTopRow] [-HideSource] [-Title ] [-TitleFillPattern ] [-TitleBackgroundColor ] [-TitleBold] [-TitleSize ] [-PivotTableDefinition ] [-ExcelChartDefinition ] [-ConditionalFormat ] [-ConditionalText ] [-AutoNameRange] [-RangeName ] [-ReturnRange] [-Show] [-PassThru] [] +``` + +## DESCRIPTION +Join-Worksheet can work in two main ways, either + +*Combining data which has the same layout from many pages into one, or +*Combining pages which have nothing in common. +In the former case the header row is copied from the first sheet and, by default, each row of data is labelled with the name of the sheet it came from. + +In the latter case -NoHeader is specified, and each copied block can have the sheet it came from placed above it as a title. + +## 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. + +## PARAMETERS + +### -Path +Path to a new or existing .XLSX file. + +```yaml +Type: String +Parameter Sets: Default, Table +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcelPackage +An object representing an Excel Package - either from Open-ExcelPackage or specifying -PassThru to Export-Excel. + +```yaml +Type: ExcelPackage +Parameter Sets: PackageTable, PackageDefault +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WorkSheetName +The name of a sheet within the workbook where the other sheets will be joined together - "Combined" by default. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: Combined +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Clearsheet +If specified ,any pre-existing target for the joined data will be deleted and re-created; otherwise data will be appended on this sheet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoHeader +Join-Worksheet assumes each sheet has identical headers and the headers should be copied to the target sheet, unless -NoHeader is specified. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FromLabel +If -NoHeader is NOT specified, then rows of data will be labeled with the name of the sheet they came from. FromLabel is the header for this column. If it is null or empty, the labels will be omitted. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: From +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LabelBlocks +If specified, the copied blocks of data will have the name of the sheet they were copied from inserted above them as a title. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AutoSize +Sets the width of the Excel columns to display all the data in their cells. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FreezeTopRow +Freezes headers etc. in the top row. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FreezeFirstColumn +Freezes titles etc. in the left column. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FreezeTopRowFirstColumn +Freezes top row and left column (equivalent to Freeze pane 2,2 ). + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FreezePane +Freezes panes at specified coordinates (in the formRowNumber , ColumnNumber). + +```yaml +Type: Int32[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AutoFilter +Enables the Excel filter on the headers of the combined sheet. + +```yaml +Type: SwitchParameter +Parameter Sets: Default, PackageDefault +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BoldTopRow +Makes the top row boldface. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HideSource +If specified, hides the sheets that the data is copied from. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Title +Text of a title to be placed in Cell A1. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TitleFillPattern +Sets the fill pattern for the title cell. + +```yaml +Type: ExcelFillStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Solid, DarkGray, MediumGray, LightGray, Gray125, Gray0625, DarkVertical, DarkHorizontal, DarkDown, DarkUp, DarkGrid, DarkTrellis, LightVertical, LightHorizontal, LightDown, LightUp, LightGrid, LightTrellis + +Required: False +Position: Named +Default value: Solid +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TitleBackgroundColor +Sets the cell background color for the title cell. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TitleBold +Sets the title in boldface type. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TitleSize +Sets the point size for the title. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 22 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotTableDefinition +Hashtable(s) with Sheet PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values to specify a definition for one or morePivotTable(s). + +```yaml +Type: Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcelChartDefinition +A hashtable containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more \[non-pivot\] charts. + +```yaml +Type: Object[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ConditionalFormat +One or more conditional formatting rules defined with New-ConditionalFormattingIconSet. + +```yaml +Type: Object[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ConditionalText +Applies a Conditional formatting rule defined with New-ConditionalText. + +```yaml +Type: Object[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AutoNameRange +Makes each column a named range. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -RangeName +Makes the data in the worksheet a named range. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TableName +Makes the data in the worksheet a table with a name and applies a style to it. Name must not contain spaces. + +```yaml +Type: String +Parameter Sets: Table, PackageTable +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TableStyle +Selects the style for the named table - defaults to "Medium6". + +```yaml +Type: TableStyles +Parameter Sets: Table, PackageTable +Aliases: +Accepted values: 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 + +Required: False +Position: Named +Default value: Medium6 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ReturnRange +If specified, returns the range of cells in the combined sheet, in the format "A1:Z100". + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Show +Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +If specified, an object representing the unsaved Excel package will be returned, it then needs to be saved. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Merge-MultipleSheets.md b/mdHelp/Merge-MultipleSheets.md new file mode 100644 index 0000000..71483ec --- /dev/null +++ b/mdHelp/Merge-MultipleSheets.md @@ -0,0 +1,330 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Merge-MultipleSheets + +## SYNOPSIS +Merges Worksheets into a single Worksheet with differences marked up. + +## SYNTAX + +``` +Merge-MultipleSheets [-Path] [[-Startrow] ] [[-Headername] ] [-NoHeader] [[-WorksheetName] ] [[-OutputFile] ] [[-OutputSheetName] ] [[-Property] ] [[-ExcludeProperty] ] [[-Key] ] [[-KeyFontColor] ] [[-ChangeBackgroundColor] ] [[-DeleteBackgroundColor] ] [[-AddBackgroundColor] ] [-HideRowNumbers] [-Passthru] [-Show] [] +``` + +## DESCRIPTION +The Merge Worksheet command combines two sheets. Merge-MultipleSheets is designed to merge more than two. + +If asked to merge sheets A,B,C which contain Services, with a Name, Displayname and Start mode, where "Name" is treated as the key, Merge-MultipleSheets: + +* Calls Merge-Worksheet to merge "Name", "Displayname" and "Startmode" from sheets A and C; the result has column headings "_Row", "Name", "DisplayName", "Startmode", "C-DisplayName", "C-StartMode", "C-Is" and "C-Row". +* Calls Merge-Worksheet again passing it the intermediate result and sheet B, comparing "Name", "Displayname" and "Start mode" columns on each side, and gets a result with columns "_Row", "Name", "DisplayName", "Startmode", "B-DisplayName", "B-StartMode", "B-Is", "B-Row", "C-DisplayName", "C-StartMode", "C-Is" and "C-Row". +Any columns on the "reference" side which are not used in the comparison are added on the right, which is why we compare the sheets in reverse order. + +The "Is" columns hold "Same", "Added", "Removed" or "Changed" and is used for conditional formatting in the output sheet (these columns are hidden by default), and when the data is written to Excel the "reference" columns, in this case "DisplayName" and "Start" are renamed to reflect their source, so they become "A-DisplayName" and "A-Start". + +Conditional formatting is also applied to the Key column ("Name" in this case) so the view can be filtered to rows with changes by filtering this +column on color. + +Note: the processing order can affect what is seen as a change.For example, if there is an extra item in sheet B in the example above, Sheet C will be processed first and that row and will not be seen to be missing. When sheet B is processed it is marked as an addition, and the conditional formatting marks the entries from sheet A to show that a values were added in at least one sheet. + +However if Sheet B is the reference sheet, A and C will be seen to have an item removed; and if B is processed before C, the extra item is known when C is processed and so C is considered to be missing that item. + +## 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. + +## PARAMETERS + +### -Path +Paths to the files to be merged. +Files are also accepted + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Startrow +The row from where we start to import data, all rows above the Start row are disregarded. By default this is the first row. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Headername +Specifies custom property names to use, instead of the values defined in the column headers of the Start row. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoHeader +If specified, property names will be automatically generated (P1, P2, P3, ..) instead of using the values from the start row. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WorksheetName +Name(s) of Worksheets to compare. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: Sheet1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OutputFile +File to write output to. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: OutFile + +Required: False +Position: 5 +Default value: .\temp.xlsx +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OutputSheetName +Name of Worksheet to output - if none specified will use the reference Worksheet name. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: OutSheet + +Required: False +Position: 6 +Default value: Sheet1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Property +Properties to include in the comparison - supports wildcards, default is "*". + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 7 +Default value: * +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcludeProperty +Properties to exclude from the the comparison - supports wildcards. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 8 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Key +Name of a column which is unique used to pair up rows from the reference and difference sides, default is "Name". + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 9 +Default value: Name +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -KeyFontColor +Sets the font color for the Key field; this means you can filter by color to get only changed rows. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 10 +Default value: [System.Drawing.Color]::Red +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChangeBackgroundColor +Sets the background color for changed rows. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 11 +Default value: [System.Drawing.Color]::Orange +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DeleteBackgroundColor +Sets the background color for rows in the reference but deleted from the difference sheet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 12 +Default value: [System.Drawing.Color]::LightPink +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AddBackgroundColor +Sets the background color for rows not in the reference but added to the difference sheet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 13 +Default value: [System.Drawing.Color]::Orange +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HideRowNumbers +If specified, hides the columns in the spreadsheet that contain the row numbers. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Passthru +If specified, outputs the data to the pipeline (you can add -whatif so it the command only outputs to the pipeline). + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Show +If specified, opens the output workbook. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Merge-Worksheet.md b/mdHelp/Merge-Worksheet.md new file mode 100644 index 0000000..8821125 --- /dev/null +++ b/mdHelp/Merge-Worksheet.md @@ -0,0 +1,462 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Merge-Worksheet + +## SYNOPSIS +Merges two Worksheets (or other objects) into a single Worksheet with differences marked up. + +## SYNTAX + +### C +``` +Merge-Worksheet [-Referencefile] [-Differencefile] [[-WorksheetName] ] [-Startrow ] [-NoHeader] [[-OutputFile] ] [[-OutputSheetName] ] [-Property ] [-ExcludeProperty ] [-Key ] [-KeyFontColor ] [-ChangeBackgroundColor ] [-DeleteBackgroundColor ] [-AddBackgroundColor ] [-HideEqual] [-Passthru] [-Show] [-WhatIf] [-Confirm] [] +``` + +### B +``` +Merge-Worksheet [-Referencefile] [-Differencefile] [[-WorksheetName] ] [-Startrow ] -Headername [[-OutputFile] ] [[-OutputSheetName] ] [-Property ] [-ExcludeProperty ] [-Key ] [-KeyFontColor ] [-ChangeBackgroundColor ] [-DeleteBackgroundColor ] [-AddBackgroundColor ] [-HideEqual] [-Passthru] [-Show] [-WhatIf] [-Confirm] [] +``` + +### A +``` +Merge-Worksheet [-Referencefile] [-Differencefile] [[-WorksheetName] ] [-Startrow ] [[-OutputFile] ] [[-OutputSheetName] ] [-Property ] [-ExcludeProperty ] [-Key ] [-KeyFontColor ] [-ChangeBackgroundColor ] [-DeleteBackgroundColor ] [-AddBackgroundColor ] [-HideEqual] [-Passthru] [-Show] [-WhatIf] [-Confirm] [] +``` + +### G +``` +Merge-Worksheet [-Differencefile] [[-WorksheetName] ] [-Startrow ] [-NoHeader] -ReferenceObject [[-DiffPrefix] ] [[-OutputFile] ] [[-OutputSheetName] ] [-Property ] [-ExcludeProperty ] [-Key ] [-KeyFontColor ] [-ChangeBackgroundColor ] [-DeleteBackgroundColor ] [-AddBackgroundColor ] [-HideEqual] [-Passthru] [-Show] [-WhatIf] [-Confirm] [] +``` + +### F +``` +Merge-Worksheet [-Differencefile] [[-WorksheetName] ] [-Startrow ] -Headername -ReferenceObject [[-DiffPrefix] ] [[-OutputFile] ] [[-OutputSheetName] ] [-Property ] [-ExcludeProperty ] [-Key ] [-KeyFontColor ] [-ChangeBackgroundColor ] [-DeleteBackgroundColor ] [-AddBackgroundColor ] [-HideEqual] [-Passthru] [-Show] [-WhatIf] [-Confirm] [] +``` + +### E +``` +Merge-Worksheet [-Differencefile] [[-WorksheetName] ] [-Startrow ] -ReferenceObject [[-DiffPrefix] ] [[-OutputFile] ] [[-OutputSheetName] ] [-Property ] [-ExcludeProperty ] [-Key ] [-KeyFontColor ] [-ChangeBackgroundColor ] [-DeleteBackgroundColor ] [-AddBackgroundColor ] [-HideEqual] [-Passthru] [-Show] [-WhatIf] [-Confirm] [] +``` + +### D +``` +Merge-Worksheet -ReferenceObject [-DifferenceObject] [[-DiffPrefix] ] [[-OutputFile] ] [[-OutputSheetName] ] [-Property ] [-ExcludeProperty ] [-Key ] [-KeyFontColor ] [-ChangeBackgroundColor ] [-DeleteBackgroundColor ] [-AddBackgroundColor ] [-HideEqual] [-Passthru] [-Show] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +The Compare-Worksheet command takes two Worksheets and marks differences in the source document, and optionally outputs a grid showing the changes. + +By contrast the Merge-Worksheet command takes the Worksheets and combines them into a single sheet showing the old and new data side by side. Although it is designed to work with Excel data it can work with arrays of any kind of object; so it can be a merge *of* Worksheets, or a merge *to* a Worksheet. + +## 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). + +## PARAMETERS + +### -Referencefile +First Excel file to compare. You can compare two Excel files or two other objects or a reference obhct against a difference file, but not a reference file against an object. works with the following parameter sets + +* A = Compare two files default headers +* B = Compare two files user supplied headers +* C = Compare two files headers P1, P2, P3 etc + +```yaml +Type: Object +Parameter Sets: C, B, A +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Differencefile +Second Excel file to compare. Works with paramter sets A,B,C as well as the following + +* D = Compare two objects; +* E = Compare one object one file that uses default headers +* F = Compare one object one file that uses user supplied headers +* G = Compare one object one file that uses headers P1, P2, P3 etc + +```yaml +Type: Object +Parameter Sets: C, B, A, G, F, E +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WorksheetName +Name(s) of Worksheets to compare. Applies to all parameter sets EXCEPT D which is two objects (no sheets) + +```yaml +Type: Object +Parameter Sets: C, B, A, G, F, E +Aliases: + +Required: False +Position: 3 +Default value: Sheet1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Startrow +The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. Applies to all sets EXCEPT D which is two objects (no sheets, so no start row ) + +```yaml +Type: Int32 +Parameter Sets: C, B, A, G, F, E +Aliases: + +Required: False +Position: Named +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Headername +Specifies custom property names to use, instead of the values defined in the column headers of the Start Row. Works with the following parameter sets: + +* B 2 sheets with user supplied headers +* F Compare object + sheet +```yaml +Type: String[] +Parameter Sets: B, F +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoHeader +Automatically generate property names (P1, P2, P3, ..) instead of using the values the top row of the sheet. Works with parameter sets + +* C 2 sheets with headers of P1, P2, P3 ... +* G Compare object + sheet +```yaml +Type: SwitchParameter +Parameter Sets: C, G +Aliases: + +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ReferenceObject +Reference object to compare if a Worksheet is NOT being used. +Reference object can combine with a difference sheet or difference object + +```yaml +Type: Object +Parameter Sets: G, F, E, D +Aliases: RefObject + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DifferenceObject +Difference object to compare if a Worksheet is NOT being used for either half. +Can't have a reference sheet and difference object. + +```yaml +Type: Object +Parameter Sets: D +Aliases: DiffObject + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DiffPrefix +If there isn't a filename to use to label data from the "Difference" side, DiffPrefix is used, it defaults to "=\>" + +```yaml +Type: Object +Parameter Sets: G, F, E, D +Aliases: + +Required: False +Position: 3 +Default value: => +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OutputFile +File to hold merged data. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: OutFile + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OutputSheetName +Name of Worksheet to output - if none specified will use the reference Worksheet name. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: OutSheet + +Required: False +Position: 5 +Default value: Sheet1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Property +Properties to include in the DIFF - supports wildcards, default is "*". + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: * +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcludeProperty +Properties to exclude from the the search - supports wildcards. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Key +Name of a column which is unique used to pair up rows from the refence and difference side, default is "Name". + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: Name +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -KeyFontColor +Sets the font color for the "key" field; this means you can filter by color to get only changed rows. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: [System.Drawing.Color]::DarkRed +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChangeBackgroundColor +Sets the background color for changed rows. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: [System.Drawing.Color]::Orange +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DeleteBackgroundColor +Sets the background color for rows in the reference but deleted from the difference sheet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: [System.Drawing.Color]::LightPink +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AddBackgroundColor +Sets the background color for rows not in the reference but added to the difference sheet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: [System.Drawing.Color]::PaleGreen +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HideEqual +if specified, hides the rows in the spreadsheet that are equal and only shows changes, added or deleted rows. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Passthru +If specified, outputs the data to the pipeline (you can add -WhatIf so the command only outputs to the pipeline). + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Show +If specified, opens the output workbook. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/mdHelp/New-ConditionalFormattingIconSet.md b/mdHelp/New-ConditionalFormattingIconSet.md new file mode 100644 index 0000000..2de38f5 --- /dev/null +++ b/mdHelp/New-ConditionalFormattingIconSet.md @@ -0,0 +1,92 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# New-ConditionalFormattingIconSet + +## SYNOPSIS +Creates an object which describes a conditional formatting rule a for 3,4 or 5 icon set. + +## SYNTAX + +``` +New-ConditionalFormattingIconSet [-Range] [[-ConditionalFormat] ] [-Reverse] [] +``` + +## DESCRIPTION +Export-Excel takes a -ConditionalFormat parameter which can hold one or more descriptions for conditional formats; this command builds the defintion of a Conditional formatting rule for an icon set. + +## 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. + +## PARAMETERS + +### -Range +The range of cells that the conditional format applies to. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ConditionalFormat +The type of rule: one of "ThreeIconSet","FourIconSet" or "FiveIconSet" + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Reverse +Use the icons in the reverse order. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[Add-Add-ConditionalFormatting]() +[New-ConditionalText]() + diff --git a/mdHelp/New-ConditionalText.md b/mdHelp/New-ConditionalText.md new file mode 100644 index 0000000..fb55d6b --- /dev/null +++ b/mdHelp/New-ConditionalText.md @@ -0,0 +1,153 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# New-ConditionalText + +## SYNOPSIS +Creates an object which describes a conditional formatting rule for single valued rules. + +## SYNTAX + +``` +New-ConditionalText [[-Text] ] [[-ConditionalTextColor] ] [[-BackgroundColor] ] [[-Range] ] [[-PatternType] ] [[-ConditionalType] ] [] +``` + +## 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 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. + +## 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. + +## PARAMETERS + +### -Text +The text (or other value) to use in the rule. Note that Equals, GreaterThan/LessThan rules require text to wrapped in double quotes. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: ConditionValue + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ConditionalTextColor +The font color for the cell - by default: "DarkRed". + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: ForeGroundColor + +Required: False +Position: 2 +Default value: [System.Drawing.Color]::DarkRed +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BackgroundColor +The fill color for the cell - by default: "LightPink". + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: [System.Drawing.Color]::LightPink +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PatternType +The background pattern for the cell - by default: "Solid" + +```yaml +Type: ExcelFillStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Solid, DarkGray, MediumGray, LightGray, Gray125, Gray0625, DarkVertical, DarkHorizontal, DarkDown, DarkUp, DarkGrid, DarkTrellis, LightVertical, LightHorizontal, LightDown, LightUp, LightGrid, LightTrellis + +Required: False +Position: 5 +Default value: Solid +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ConditionalType +One of the supported rules; by default "ContainsText" is selected. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: RuleType + +Required: False +Position: 6 +Default value: ContainsText +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[Add-ConditionalFormatting]() +[New-ConditionalFormattingIconSet]() + diff --git a/mdHelp/New-ExcelChartDefinition.md b/mdHelp/New-ExcelChartDefinition.md new file mode 100644 index 0000000..fbaac1e --- /dev/null +++ b/mdHelp/New-ExcelChartDefinition.md @@ -0,0 +1,634 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# New-ExcelChartDefinition + +## SYNOPSIS +Creates a Definition of a chart which can be added using Export-Excel, or Add-PivotTable + +## SYNTAX + +``` +New-ExcelChartDefinition [[-Title] ] [[-Header] ] [[-ChartType] ] [[-ChartTrendLine] ] [[-XRange] ] [[-YRange] ] [[-Width] ] [[-Height] ] [[-Row] ] [[-RowOffSetPixels] ] [[-Column] ] [[-ColumnOffSetPixels] ] [[-LegendPosition] ] [[-LegendSize] ] [-LegendBold] [-NoLegend] [-ShowCategory] [-ShowPercent] [[-SeriesHeader] ] [-TitleBold] [[-TitleSize] ] [[-XAxisTitleText] ] [-XAxisTitleBold] [[-XAxisTitleSize] ] [[-XAxisNumberformat] ] [[-XMajorUnit] ] [[-XMinorUnit] ] [[-XMaxValue] ] [[-XMinValue] ] [[-XAxisPosition] ] [[-YAxisTitleText] ] [-YAxisTitleBold] [[-YAxisTitleSize] ] [[-YAxisNumberformat] ] [[-YMajorUnit] ] [[-YMinorUnit] ] [[-YMaxValue] ] [[-YMinValue] ] [[-YAxisPosition] ] [] +``` + +## DESCRIPTION +All the parameters which are passed to Add-ExcelChart can be added to a chart-definition object and passed to Export-Excel with the -ExcelChartDefinition parameter, +or to Add-PivotTable with the -PivotChartDefinition parameter. This command sets up those definition objects. + +## 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 . + +## PARAMETERS + +### -Title +The title for the chart. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: Chart Title +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Header +No longer used. This may be removed in future versions. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartType +One of the built-in chart types, such as Pie, ClusteredColumn, Line etc. Defaults to "ColumnStacked". + +```yaml +Type: eChartType +Parameter Sets: (All) +Aliases: +Accepted values: 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 + +Required: False +Position: 3 +Default value: ColumnStacked +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartTrendLine +Superimposes one of Excel's trenline types on the chart. + +```yaml +Type: eTrendLine[] +Parameter Sets: (All) +Aliases: +Accepted values: Exponential, Linear, Logarithmic, MovingAvgerage, Polynomial, Power + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XRange +The range of cells containing values for the X-Axis - usually labels. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YRange +The range(s) of cells holding values for the Y-Axis - usually "data". + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 6 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Width +Width of the chart in pixels. Defaults to 500. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 7 +Default value: 500 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Height +Height of the chart in pixels. Defaults to 350. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 8 +Default value: 350 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Row +Row position of the top left corner of the chart. 0 places it at the top of the sheet, 1 below row 1 and so on. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 9 +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -RowOffSetPixels +Offset to position the chart by a fraction of a row. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 10 +Default value: 10 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Column +Column position of the top left corner of the chart. 0 places it at the edge of the sheet, 1 to the right of column A and so on. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 11 +Default value: 6 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ColumnOffSetPixels +Offset to position the chart by a fraction of a column. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 12 +Default value: 5 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LegendPosition +Location of the key, either "Left", "Right", "Top", "Bottom" or "TopRight". + +```yaml +Type: eLegendPosition +Parameter Sets: (All) +Aliases: +Accepted values: Top, Left, Right, Bottom, TopRight + +Required: False +Position: 13 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LegendSize +Font size for the key. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 14 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LegendBold +Sets the key in bold type. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoLegend +If specified, turns off display of the key. If you only have one data series it may be preferable to use the title to say what the chart is. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowCategory +Attaches a category label in charts which support this. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowPercent +Attaches a percentage label in charts which support this. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SeriesHeader +Specifies explicit name(s) for the data series, which will appear in the legend/key + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 15 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TitleBold +Sets the title in bold face. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TitleSize +Sets the point size for the title. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 16 +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XAxisTitleText +Specifies a title for the X-axis. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 17 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XAxisTitleBold +Sets the X-axis title in bold face. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XAxisTitleSize +Sets the font size for the axis title. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 18 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XAxisNumberformat +A number formatting string, like "#,##0.00", for numbers along the X-axis. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 19 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XMajorUnit +Spacing for the major gridlines / tick marks along the X-axis. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 20 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XMinorUnit +Spacing for the minor gridlines / tick marks along the X-axis. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 21 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XMaxValue +Maximum value for the scale along the X-axis. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 22 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XMinValue +Minimum value for the scale along the X-axis. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 23 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XAxisPosition +Position for the X-axis ("Top" or" Bottom"). + +```yaml +Type: eAxisPosition +Parameter Sets: (All) +Aliases: +Accepted values: Left, Bottom, Right, Top + +Required: False +Position: 24 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YAxisTitleText +Specifies a title for the Y-axis. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 25 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YAxisTitleBold +Sets the Y-axis title in bold face. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YAxisTitleSize +Sets the font size for the Y-axis title. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 26 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YAxisNumberformat +A number formatting string, like "#,##0.00", for numbers on the Y-axis + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 27 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YMajorUnit +Spacing for the major gridlines / tick marks on the Y-axis. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 28 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YMinorUnit +Spacing for the minor gridlines / tick marks on the Y-axis. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 29 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YMaxValue +Maximum value on the Y-axis. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 30 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YMinValue +Minimum value on the Y-axis. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 31 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -YAxisPosition +Position for the Y-axis ("Left" or "Right"). + +```yaml +Type: eAxisPosition +Parameter Sets: (All) +Aliases: +Accepted values: Left, Bottom, Right, Top + +Required: False +Position: 32 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/mdHelp/New-PivotTableDefinition.md b/mdHelp/New-PivotTableDefinition.md new file mode 100644 index 0000000..2fbf56a --- /dev/null +++ b/mdHelp/New-PivotTableDefinition.md @@ -0,0 +1,538 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# New-PivotTableDefinition + +## SYNOPSIS +Creates PivotTable definitons for Export-Excel + +## SYNTAX + +### ChartbyDef +``` +New-PivotTableDefinition -PivotTableName [-SourceWorkSheet ] [-SourceRange ] [-PivotRows ] [-PivotData ] [-PivotColumns ] [-PivotFilter ] [-PivotDataToColumn] [-PivotTotals ] [-NoTotalsInPivot] [-GroupDateRow ] [-GroupDatePart ] [-GroupNumericRow ] [-GroupNumericMin ] [-GroupNumericMax ] [-GroupNumericInterval ] [-PivotNumberFormat ] [-PivotTableStyle ] -PivotChartDefinition [-Activate] [] +``` + +### ChartbyParams +``` +New-PivotTableDefinition -PivotTableName [-SourceWorkSheet ] [-SourceRange ] [-PivotRows ] [-PivotData ] [-PivotColumns ] [-PivotFilter ] [-PivotDataToColumn] [-PivotTotals ] [-NoTotalsInPivot] [-GroupDateRow ] [-GroupDatePart ] [-GroupNumericRow ] [-GroupNumericMin ] [-GroupNumericMax ] [-GroupNumericInterval ] [-PivotNumberFormat ] [-PivotTableStyle ] [-IncludePivotChart] [-ChartTitle ] [-ChartHeight ] [-ChartWidth ] [-ChartRow ] [-ChartColumn ] [-ChartRowOffSetPixels ] [-ChartColumnOffSetPixels ] [-ChartType ] [-NoLegend] [-ShowCategory] [-ShowPercent] [-Activate] [] +``` + +## DESCRIPTION +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. + +## 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. + +## PARAMETERS + +### -PivotTableName +Name for the new pivot table + +This command previously had a typo - and has an alias to avoid breaking scripts This will be removed in a future release + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: PivtoTableName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SourceWorkSheet +Worksheet where the data is found + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SourceRange +Address range in the worksheet e.g "A10:F20" - the first row must contain the column names to pivot by: if the range is not specified the whole source sheet will be used. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotRows +Fields to set as rows in the PivotTable + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotData +A hash-table in form "FieldName"="Function", where function is one of Average, Count, CountNums, Max, Min, Product, None, StdDev, StdDevP, Sum, Var, VarP + +```yaml +Type: Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotColumns +Fields to set as columns in the PivotTable + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotFilter +Fields to use to filter in the PivotTable + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotDataToColumn +If there are multiple datasets in a PivotTable, by default they are shown seperatate rows under the given row heading; this switch makes them seperate columns. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotTotals +By default PivotTables have Totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: Both +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoTotalsInPivot +Included for compatibility - equivalent to -PivotTotals "None" + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GroupDateRow +The name of a row field which should be grouped by parts of the date/time (ignored if GroupDateRow is not specified) + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GroupDatePart +The Part(s) of the date to use in the grouping (ignored if GroupDateRow is not specified) + +```yaml +Type: eDateGroupBy[] +Parameter Sets: (All) +Aliases: +Accepted values: Years, Quarters, Months, Days, Hours, Minutes, Seconds + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GroupNumericRow +The name of a row field which should be grouped by Number (e.g 0-99, 100-199, 200-299 ) + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GroupNumericMin +The starting point for grouping + +```yaml +Type: Double +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GroupNumericMax +The endpoint for grouping + +```yaml +Type: Double +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 1.79769313486232E+308 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GroupNumericInterval +The interval for grouping + +```yaml +Type: Double +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 100 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotNumberFormat +Number format to apply to the data cells in the PivotTable + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotTableStyle +Apply a table style to the PivotTable + +```yaml +Type: TableStyles +Parameter Sets: (All) +Aliases: +Accepted values: 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 + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PivotChartDefinition +Use a chart definition instead of specifying chart settings one by one + +```yaml +Type: Object +Parameter Sets: ChartbyDef +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -IncludePivotChart +If specified a chart Will be included. + +```yaml +Type: SwitchParameter +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartTitle +Optional title for the pivot chart, by default the title omitted. + +```yaml +Type: String +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartHeight +Height of the chart in Pixels (400 by default) + +```yaml +Type: Int32 +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: 400 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartWidth +Width of the chart in Pixels (600 by default) + +```yaml +Type: Int32 +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: 600 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartRow +Cell position of the top left corner of the chart, there will be this number of rows above the top edge of the chart (default is 0, chart starts at top edge of row 1). + +```yaml +Type: Int32 +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartColumn +Cell position of the top left corner of the chart, there will be this number of cells to the left of the chart (default is 4, chart starts at left edge of column E) + +```yaml +Type: Int32 +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: 4 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartRowOffSetPixels +Vertical offset of the chart from the cell corner. + +```yaml +Type: Int32 +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartColumnOffSetPixels +Horizontal offset of the chart from the cell corner. + +```yaml +Type: Int32 +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChartType +Type of chart + +```yaml +Type: eChartType +Parameter Sets: ChartbyParams +Aliases: +Accepted values: 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 + +Required: False +Position: Named +Default value: Pie +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoLegend +If specified hides the chart legend + +```yaml +Type: SwitchParameter +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowCategory +if specified attaches the category to slices in a pie chart : not supported on all chart types, this may give errors if applied to an unsupported type. + +```yaml +Type: SwitchParameter +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ShowPercent +If specified attaches percentages to slices in a pie chart. + +```yaml +Type: SwitchParameter +Parameter Sets: ChartbyParams +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Activate +If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Open-ExcelPackage.md b/mdHelp/Open-ExcelPackage.md new file mode 100644 index 0000000..c16d198 --- /dev/null +++ b/mdHelp/Open-ExcelPackage.md @@ -0,0 +1,120 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Open-ExcelPackage + +## SYNOPSIS +Returns an ExcelPackage object for the specified XLSX fil.e + +## SYNTAX + +``` +Open-ExcelPackage [-Path] [-KillExcel] [[-Password] ] [-Create] [] +``` + +## DESCRIPTION +Import-Excel and Export-Excel open an Excel file, carry out their tasks and close it again. + +Sometimes it is necessary to open a file and do other work on it. Open-ExcelPackage allows the file to be opened for these tasks. + +It takes a -KillExcel switch to make sure Excel is not holding the file open; a -Password parameter for existing protected files, and a -Create switch to set-up a new file if no file already exists. + +## 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. + +## PARAMETERS + +### -Path +The path to the file to open. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -KillExcel +If specified, any running instances of Excel will be terminated before opening the file. This may result in lost work, so should be used with caution. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Password +The password for a protected worksheet, as a \[normal\] string (not a secure string). + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Create +By default Open-ExcelPackage will only open an existing file; -Create instructs it to create a new file if required. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### OfficeOpenXml.ExcelPackage +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Remove-WorkSheet.md b/mdHelp/Remove-WorkSheet.md new file mode 100644 index 0000000..5c1f54a --- /dev/null +++ b/mdHelp/Remove-WorkSheet.md @@ -0,0 +1,135 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Remove-WorkSheet + +## SYNOPSIS +Removes one or more worksheets from one or more workbooks + +## SYNTAX + +``` +Remove-WorkSheet [[-FullName] ] [[-WorksheetName] ] [-Show] [-WhatIf] [-Confirm] [] +``` + +## 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 + +## PARAMETERS + +### -FullName +The fully qualified path to the XLSX file(s) + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: Path + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -WorksheetName +The worksheet to be removed (sheet1 by default) + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: Sheet1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Show +If specified the file will be opened in excel after the sheet is removed. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Select-Worksheet.md b/mdHelp/Select-Worksheet.md new file mode 100644 index 0000000..f0e93eb --- /dev/null +++ b/mdHelp/Select-Worksheet.md @@ -0,0 +1,127 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Select-Worksheet + +## SYNOPSIS +Sets the selected tab in an Excel workbook to be the chosen sheet and unselects all the others. + +## SYNTAX + +### Package +``` +Select-Worksheet [-ExcelPackage] [-WorksheetName ] [] +``` + +### Workbook +``` +Select-Worksheet [-WorksheetName ] [] +``` + +### Sheet +``` +Select-Worksheet -ExcelWorksheet [] +``` + +## 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 which sheet is the selected tab when Excel opens the file. + +## 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. + +## PARAMETERS + +### -ExcelPackage +An object representing an ExcelPackage. + +```yaml +Type: ExcelPackage +Parameter Sets: Package +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ExcelWorkbook +An Excel workbook to which the Worksheet will be added - a package contains one Workbook so you can use workbook or package as it suits. + +```yaml +Type: ExcelWorkbook +Parameter Sets: WorkBook +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WorksheetName +The name of the worksheet "Sheet1" by default. + +```yaml +Type: String +Parameter Sets: Package, Workbook +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcelWorksheet +An object representing an Excel worksheet. + +```yaml +Type: ExcelWorksheet +Parameter Sets: Sheet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Send-SQLDataToExcel.md b/mdHelp/Send-SQLDataToExcel.md new file mode 100644 index 0000000..aa0067c --- /dev/null +++ b/mdHelp/Send-SQLDataToExcel.md @@ -0,0 +1,288 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Send-SQLDataToExcel + +## SYNOPSIS +Inserts a DataTable - returned by a SQL query - into an ExcelSheet + +## SYNTAX + +### none (Default) +``` +Send-SQLDataToExcel [-QueryTimeout ] [-Force] [-Path ] [-ExcelPackage ] + [-Calculate] [-Show] [-WorksheetName ] [-Password ] [-ClearSheet] [-Append] [-Title ] + [-TitleFillPattern ] [-TitleBold] [-TitleSize ] [-TitleBackgroundColor ] + [-IncludePivotTable] [-PivotTableName ] [-PivotRows ] [-PivotColumns ] + [-PivotData ] [-PivotFilter ] [-PivotDataToColumn] [-PivotTableDefinition ] + [-IncludePivotChart] [-ChartType ] [-NoLegend] [-ShowCategory] [-ShowPercent] [-AutoSize] + [-MaxAutoSizeRows ] [-NoClobber] [-FreezeTopRow] [-FreezeFirstColumn] [-FreezeTopRowFirstColumn] + [-FreezePane ] [-AutoFilter] [-BoldTopRow] [-NoHeader] [-RangeName ] [-TableName ] + [-TableStyle ] [-Barchart] [-PieChart] [-LineChart] [-ColumnChart] + [-ExcelChartDefinition ] [-HideSheet ] [-UnHideSheet ] [-MoveToStart] + [-MoveToEnd] [-MoveBefore ] [-MoveAfter ] [-KillExcel] [-AutoNameRange] [-StartRow ] + [-StartColumn ] [-PassThru] [-Numberformat ] [-ExcludeProperty ] + [-NoAliasOrScriptPropeties] [-DisplayPropertySet] [-NoNumberConversion ] + [-ConditionalFormat ] [-ConditionalText ] [-Style ] [-CellStyleSB ] + [-Activate] [-Now] [-ReturnRange] [-PivotTotals ] [-NoTotalsInPivot] [-ReZip] [] +``` + +### ODBCConnection +``` +Send-SQLDataToExcel -Connection -SQL [-QueryTimeout ] [-Force] [-Path ] + [-ExcelPackage ] [-Calculate] [-Show] [-WorksheetName ] [-Password ] + [-ClearSheet] [-Append] [-Title ] [-TitleFillPattern ] [-TitleBold] + [-TitleSize ] [-TitleBackgroundColor ] [-IncludePivotTable] [-PivotTableName ] + [-PivotRows ] [-PivotColumns ] [-PivotData ] [-PivotFilter ] + [-PivotDataToColumn] [-PivotTableDefinition ] [-IncludePivotChart] [-ChartType ] + [-NoLegend] [-ShowCategory] [-ShowPercent] [-AutoSize] [-MaxAutoSizeRows ] [-NoClobber] + [-FreezeTopRow] [-FreezeFirstColumn] [-FreezeTopRowFirstColumn] [-FreezePane ] [-AutoFilter] + [-BoldTopRow] [-NoHeader] [-RangeName ] [-TableName ] [-TableStyle ] [-Barchart] + [-PieChart] [-LineChart] [-ColumnChart] [-ExcelChartDefinition ] [-HideSheet ] + [-UnHideSheet ] [-MoveToStart] [-MoveToEnd] [-MoveBefore ] [-MoveAfter ] + [-KillExcel] [-AutoNameRange] [-StartRow ] [-StartColumn ] [-PassThru] [-Numberformat ] + [-ExcludeProperty ] [-NoAliasOrScriptPropeties] [-DisplayPropertySet] + [-NoNumberConversion ] [-ConditionalFormat ] [-ConditionalText ] + [-Style ] [-CellStyleSB ] [-Activate] [-Now] [-ReturnRange] [-PivotTotals ] + [-NoTotalsInPivot] [-ReZip] [] +``` + +### SQLConnection +``` +Send-SQLDataToExcel -Connection [-MsSQLserver] [-DataBase ] -SQL [-QueryTimeout ] [-Force] [-Path ] [-ExcelPackage ] [-Calculate] [-Show] [-WorksheetName ] [-Password ] [-ClearSheet] [-Append] [-Title ] [-TitleFillPattern ] [-TitleBold] [-TitleSize ] [-TitleBackgroundColor ] [-IncludePivotTable] [-PivotTableName ] [-PivotRows ] [-PivotColumns ] [-PivotData ] [-PivotFilter ] [-PivotDataToColumn] [-PivotTableDefinition ] [-IncludePivotChart] [-ChartType ] [-NoLegend] [-ShowCategory] [-ShowPercent] [-AutoSize] [-MaxAutoSizeRows ] [-NoClobber] [-FreezeTopRow] [-FreezeFirstColumn] [-FreezeTopRowFirstColumn] [-FreezePane ] [-AutoFilter] [-BoldTopRow] [-NoHeader] [-RangeName ] [-TableName ] [-TableStyle ] [-Barchart] [-PieChart] [-LineChart] [-ColumnChart] [-ExcelChartDefinition ] [-HideSheet ] [-UnHideSheet ] [-MoveToStart] [-MoveToEnd] [-MoveBefore ] [-MoveAfter ] [-KillExcel] [-AutoNameRange] [-StartRow ] [-StartColumn ] [-PassThru] [-Numberformat ] [-ExcludeProperty ] [-NoAliasOrScriptPropeties] [-DisplayPropertySet] [-NoNumberConversion ] [-ConditionalFormat ] [-ConditionalText ] [-Style ] [-CellStyleSB ] [-Activate] [-Now] [-ReturnRange] [-PivotTotals ] [-NoTotalsInPivot] [-ReZip] [] +``` + +### ExistingSession +``` +Send-SQLDataToExcel -Session -SQL [-QueryTimeout ] [-Force] [-Path ] [-ExcelPackage ] [-Calculate] [-Show] [-WorksheetName ] [-Password ] [-ClearSheet] [-Append] [-Title ] [-TitleFillPattern ] [-TitleBold] [-TitleSize ] [-TitleBackgroundColor ] [-IncludePivotTable] [-PivotTableName ] [-PivotRows ] [-PivotColumns ] [-PivotData ] [-PivotFilter ] [-PivotDataToColumn] [-PivotTableDefinition ] [-IncludePivotChart] [-ChartType ] [-NoLegend] [-ShowCategory] [-ShowPercent] [-AutoSize] [-MaxAutoSizeRows ] [-NoClobber] [-FreezeTopRow] [-FreezeFirstColumn] [-FreezeTopRowFirstColumn] [-FreezePane ] [-AutoFilter] [-BoldTopRow] [-NoHeader] [-RangeName ] [-TableName ] [-TableStyle ] [-Barchart] [-PieChart] [-LineChart] [-ColumnChart] [-ExcelChartDefinition ] [-HideSheet ] [-UnHideSheet ] [-MoveToStart] [-MoveToEnd] [-MoveBefore ] [-MoveAfter ] [-KillExcel] [-AutoNameRange] [-StartRow ] [-StartColumn ] [-PassThru] [-Numberformat ] [-ExcludeProperty ] [-NoAliasOrScriptPropeties] [-DisplayPropertySet] [-NoNumberConversion ] [-ConditionalFormat ] [-ConditionalText ] [-Style ] [-CellStyleSB ] [-Activate] [-Now] [-ReturnRange] [-PivotTotals ] [-NoTotalsInPivot] [-ReZip] [] +``` + +### Pre-FetchedData +``` +Send-SQLDataToExcel [-QueryTimeout ] -DataTable [-Force] [-Path ] [-ExcelPackage ] [-Calculate] [-Show] [-WorksheetName ] [-Password ] [-ClearSheet] [-Append] [-Title ] [-TitleFillPattern ] [-TitleBold] [-TitleSize ] [-TitleBackgroundColor ] [-IncludePivotTable] [-PivotTableName ] [-PivotRows ] [-PivotColumns ] [-PivotData ] [-PivotFilter ] [-PivotDataToColumn] [-PivotTableDefinition ] [-IncludePivotChart] [-ChartType ] [-NoLegend] [-ShowCategory] [-ShowPercent] [-AutoSize] [-MaxAutoSizeRows ] [-NoClobber] [-FreezeTopRow] [-FreezeFirstColumn] [-FreezeTopRowFirstColumn] [-FreezePane ] [-AutoFilter] [-BoldTopRow] [-NoHeader] [-RangeName ] [-TableName ] [-TableStyle ] [-Barchart] [-PieChart] [-LineChart] [-ColumnChart] [-ExcelChartDefinition ] [-HideSheet ] [-UnHideSheet ] [-MoveToStart] [-MoveToEnd] [-MoveBefore ] [-MoveAfter ] [-KillExcel] [-AutoNameRange] [-StartRow ] [-StartColumn ] [-PassThru] [-Numberformat ] [-ExcludeProperty ] [-NoAliasOrScriptPropeties] [-DisplayPropertySet] [-NoNumberConversion ] [-ConditionalFormat ] [-ConditionalText ] [-Style ] [-CellStyleSB ] [-Activate] [-Now] [-ReturnRange] [-PivotTotals ] [-NoTotalsInPivot] [-ReZip] [] +``` + +## DESCRIPTION +This command takes a SQL statement and run it against a database connection; for the connection it accepts either + +* an object representing a session with a SQL server or ODBC database, or +* a connection string to make a session (if -MSSQLServer is specified it uses the SQL Native client, + and -Connection can be a server name instead of a detailed connection string. Without this switch it uses ODBC) + +The command takes all the parameters of Export-Excel, except for -InputObject (alias TargetData); after fetching the data it calls Export-Excel with the data as the value of InputParameter and whichever of Export-Excel's parameters it was passed; for details of these parameters see the help for Export-Excel. + +## 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 \ | export-excel -ExcludeProperty rowerror,rowstate,table,itemarray,haserrors \ + +(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 + +## PARAMETERS + +### -Connection +A database connection string to be used to create a database session; either + +* A Data source name written in the form DSN=ODBC_Data_Source_Name, or +* A full ODBC or SQL Native Client Connection string, or +* The name of a SQL server. + +```yaml +Type: Object +Parameter Sets: ODBCConnection, SQLConnection +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Session +An active ODBC Connection or SQL connection object representing a session with a database which will be queried to get the data . + +```yaml +Type: Object +Parameter Sets: ExistingSession +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MsSQLserver +Specifies the connection string is for SQL server, not ODBC. + +```yaml +Type: SwitchParameter +Parameter Sets: SQLConnection +Aliases: + +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DataBase +Switches to a specific database on a SQL server. + +```yaml +Type: String +Parameter Sets: SQLConnection +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SQL +The SQL query to run against the session which was passed in -Session or set up from -Connection. + +```yaml +Type: String +Parameter Sets: ODBCConnection, SQLConnection, ExistingSession +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -QueryTimeout +Override the default query time of 30 seconds. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DataTable +A System.Data.DataTable object containing the data to be inserted into the spreadsheet without running a query. This remains supported to avoid breaking older scripts, but if you have a DataTable object you can pass the it into Export-Excel using -InputObject. + +```yaml +Type: DataTable +Parameter Sets: Pre-FetchedData +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Force +If specified Export-Excel will be called with parameters specified, even if there is no data to send + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[Export-Excel]() + diff --git a/mdHelp/Set-ExcelColumn.md b/mdHelp/Set-ExcelColumn.md new file mode 100644 index 0000000..96d0464 --- /dev/null +++ b/mdHelp/Set-ExcelColumn.md @@ -0,0 +1,567 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Set-ExcelColumn + +## SYNOPSIS +Adds or modifies a column in an Excel worksheet, filling values, setting formatting and/or creating named ranges. + +## SYNTAX + +### Package +``` +Set-ExcelColumn -ExcelPackage [-Worksheetname ] [-Column ] [-StartRow ] [-Value ] [-Heading ] [-NumberFormat ] [-BorderAround ] [-FontColor ] [-Bold] [-Italic] [-Underline] [-UnderLineType ] [-StrikeThru] [-FontShift ] [-FontName ] [-FontSize ] [-BackgroundColor ] [-BackgroundPattern ] [-PatternColor ] [-WrapText] [-HorizontalAlignment ] [-VerticalAlignment ] [-TextRotation ] [-AutoSize] [-Width ] [-AutoNameRange] [-Hide] [-Specified] [-PassThru] [] +``` + +### sheet +``` +Set-ExcelColumn -Worksheet [-Column ] [-StartRow ] [-Value ] [-Heading ] [-NumberFormat ] [-BorderAround ] [-FontColor ] [-Bold] [-Italic] [-Underline] [-UnderLineType ] [-StrikeThru] [-FontShift ] [-FontName ] [-FontSize ] [-BackgroundColor ] [-BackgroundPattern ] [-PatternColor ] [-WrapText] [-HorizontalAlignment ] [-VerticalAlignment ] [-TextRotation ] [-AutoSize] [-Width ] [-AutoNameRange] [-Hide] [-Specified] [-PassThru] [] +``` + +## 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. + +The column can be formatted in the same operation. + +## 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. + +## PARAMETERS + +### -ExcelPackage +If specifying the worksheet by name, the ExcelPackage object which contains the worksheet also needs to be passed. + +```yaml +Type: ExcelPackage +Parameter Sets: Package +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Worksheetname +The sheet to update can be given as a name or an Excel Worksheet object - this sets it by name. + +```yaml +Type: String +Parameter Sets: Package +Aliases: + +Required: False +Position: Named +Default value: Sheet1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Worksheet +This passes the worksheet object instead of passing a sheet name and an Excelpackage object. + +```yaml +Type: ExcelWorksheet +Parameter Sets: sheet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Column +Column to fill down - the first column is 1. 0 will be interpreted as first empty column. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -StartRow +First row to fill data in. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Value +A value, formula or scriptblock to fill in. A script block can use $worksheet, $row, $column \[number\], $columnName \[letter(s)\], $startRow, $startColumn, $endRow, $endColumn. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Heading +Optional column heading. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NumberFormat +Number format to apply to cells for example "dd/MM/yyyy HH:mm", "£#,##0.00;\[Red\]-£#,##0.00", "0.00%" , "##/##" or "0.0E+0" etc. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: NFormat + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderAround +Style of border to draw around the row. + +```yaml +Type: ExcelBorderStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Hair, Dotted, DashDot, Thin, DashDotDot, Dashed, MediumDashDotDot, MediumDashed, MediumDashDot, Thick, Medium, Double + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FontColor +Colour for the text - if none specified it will be left as it it is. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Bold +Make text bold; use -Bold:$false to remove bold. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Italic +Make text italic; use -Italic:$false to remove italic. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Underline +Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UnderLineType +Specifies whether underlining should be single or double, normal or accounting mode. +The default is "Single". + +```yaml +Type: ExcelUnderLineType +Parameter Sets: (All) +Aliases: +Accepted values: None, Single, Double, SingleAccounting, DoubleAccounting + +Required: False +Position: Named +Default value: Single +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StrikeThru +Strike through text; use -StrikeThru:$false to remove strike through. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FontShift +Subscript or Superscript (or None). + +```yaml +Type: ExcelVerticalAlignmentFont +Parameter Sets: (All) +Aliases: +Accepted values: None, Baseline, Subscript, Superscript + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FontName +Font to use - Excel defaults to Calibri. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FontSize +Point size for the text. + +```yaml +Type: Single +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BackgroundColor +Change background color. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BackgroundPattern +Background pattern - "Solid" by default. + +```yaml +Type: ExcelFillStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Solid, DarkGray, MediumGray, LightGray, Gray125, Gray0625, DarkVertical, DarkHorizontal, DarkDown, DarkUp, DarkGrid, DarkTrellis, LightVertical, LightHorizontal, LightDown, LightUp, LightGrid, LightTrellis + +Required: False +Position: Named +Default value: Solid +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PatternColor +Secondary color for background pattern. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: PatternColour + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WrapText +Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HorizontalAlignment +Position cell contents to Left, Right, Center etc. Default is "General". + +```yaml +Type: ExcelHorizontalAlignment +Parameter Sets: (All) +Aliases: +Accepted values: General, Left, Center, CenterContinuous, Right, Fill, Distributed, Justify + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -VerticalAlignment +Position cell contents to Top, Bottom or Center. + +```yaml +Type: ExcelVerticalAlignment +Parameter Sets: (All) +Aliases: +Accepted values: Top, Center, Bottom, Distributed, Justify + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TextRotation +Degrees to rotate text; up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AutoSize +Attempt to auto-fit cells to the width their contents. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: AutoFit + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Width +Set cells to a fixed width, ignored if -AutoSize is specified. + +```yaml +Type: Single +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AutoNameRange +Set the inserted data to be a named range. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Hide +Hide the column. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Specified +If specified, returns the range of cells which were affected. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +If specified, return an object representing the Column, to allow further work to be done on it. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### OfficeOpenXml.ExcelColumn +### System.String +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Set-ExcelRange.md b/mdHelp/Set-ExcelRange.md new file mode 100644 index 0000000..551b738 --- /dev/null +++ b/mdHelp/Set-ExcelRange.md @@ -0,0 +1,594 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Set-ExcelRange + +## SYNOPSIS +Applies number, font, alignment and/or color formatting, values or formulas to a range of Excel cells. + +## SYNTAX + +``` +Set-ExcelRange [[-Range] ] [-WorkSheet ] [-NumberFormat ] [-BorderAround ] [-BorderColor ] [-BorderBottom ] [-BorderTop ] [-BorderLeft ] [-BorderRight ] [-FontColor ] [-Value ] [-Formula ] [-ArrayFormula] [-ResetFont] [-Bold] [-Italic] [-Underline] [-UnderLineType ] [-StrikeThru] [-FontShift ] [-FontName ] [-FontSize ] [-BackgroundColor ] [-BackgroundPattern ] [-PatternColor ] [-WrapText] [-HorizontalAlignment ] [-VerticalAlignment ] [-TextRotation ] [-AutoSize] [-Width ] [-Height ] [-Hidden] [-Locked] [-Merge] [] +``` + +## DESCRIPTION +Set-ExcelRange was created to set the style elements for a range of cells, this includes auto-sizing and hiding, setting font elements (Name, Size, Bold, Italic, Underline & UnderlineStyle and Subscript & SuperScript), font and background colors, borders, text wrapping, rotation, alignment within cells, and number format. + +It was orignally named "Set-Format", but it has been extended to set Values, Formulas and ArrayFormulas (sometimes called Ctrl-shift-Enter \[CSE\] formulas); because of this, the name has become Set-ExcelRange but the old name of Set-Format is preserved as an alias. + +## 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. + +## PARAMETERS + +### -Range +One or more row(s), Column(s) and/or block(s) of cells to format. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: Address + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -WorkSheet +The worksheet where the format is to be applied. + +```yaml +Type: ExcelWorksheet +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NumberFormat +Number format to apply to cells for example "dd/MM/yyyy HH:mm", "£#,##0.00;\[Red\]-£#,##0.00", "0.00%" , "##/##" or "0.0E+0" etc. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: NFormat + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderAround +Style of border to draw around the range. + +```yaml +Type: ExcelBorderStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Hair, Dotted, DashDot, Thin, DashDotDot, Dashed, MediumDashDotDot, MediumDashed, MediumDashDot, Thick, Medium, Double + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderColor +Color of the border. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: [System.Drawing.Color]::Black +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderBottom +Style for the bottom border. + +```yaml +Type: ExcelBorderStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Hair, Dotted, DashDot, Thin, DashDotDot, Dashed, MediumDashDotDot, MediumDashed, MediumDashDot, Thick, Medium, Double + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderTop +Style for the top border. + +```yaml +Type: ExcelBorderStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Hair, Dotted, DashDot, Thin, DashDotDot, Dashed, MediumDashDotDot, MediumDashed, MediumDashDot, Thick, Medium, Double + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderLeft +Style for the left border. + +```yaml +Type: ExcelBorderStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Hair, Dotted, DashDot, Thin, DashDotDot, Dashed, MediumDashDotDot, MediumDashed, MediumDashDot, Thick, Medium, Double + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderRight +Style for the right border. + +```yaml +Type: ExcelBorderStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Hair, Dotted, DashDot, Thin, DashDotDot, Dashed, MediumDashDotDot, MediumDashed, MediumDashDot, Thick, Medium, Double + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FontColor +Colour for the text - if none is specified it will be left as it is. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: ForegroundColor + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Value +Value for the cell. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Formula +Formula for the cell. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ArrayFormula +Specifies formula should be an array formula (a.k.a CSE \[ctrl-shift-enter\] formula). + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResetFont +Clear Bold, Italic, StrikeThrough and Underline and set color to Black. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Bold +Make text bold; use -Bold:$false to remove bold. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Italic +Make text italic; use -Italic:$false to remove italic. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Underline +Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UnderLineType +Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". + +```yaml +Type: ExcelUnderLineType +Parameter Sets: (All) +Aliases: +Accepted values: None, Single, Double, SingleAccounting, DoubleAccounting + +Required: False +Position: Named +Default value: Single +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StrikeThru +Strike through text; use -Strikethru:$false to remove Strike through + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FontShift +Subscript or Superscript (or none). + +```yaml +Type: ExcelVerticalAlignmentFont +Parameter Sets: (All) +Aliases: +Accepted values: None, Baseline, Subscript, Superscript + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FontName +Font to use - Excel defaults to Calibri. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FontSize +Point size for the text. + +```yaml +Type: Single +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BackgroundColor +Change background color. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BackgroundPattern +Background pattern - Solid by default. + +```yaml +Type: ExcelFillStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Solid, DarkGray, MediumGray, LightGray, Gray125, Gray0625, DarkVertical, DarkHorizontal, DarkDown, DarkUp, DarkGrid, DarkTrellis, LightVertical, LightHorizontal, LightDown, LightUp, LightGrid, LightTrellis + +Required: False +Position: Named +Default value: Solid +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PatternColor +Secondary color for background pattern. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: PatternColour + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WrapText +Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HorizontalAlignment +Position cell contents to Left, Right, Center etc. +default is 'General'. + +```yaml +Type: ExcelHorizontalAlignment +Parameter Sets: (All) +Aliases: +Accepted values: General, Left, Center, CenterContinuous, Right, Fill, Distributed, Justify + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -VerticalAlignment +Position cell contents to Top, Bottom or Center. + +```yaml +Type: ExcelVerticalAlignment +Parameter Sets: (All) +Aliases: +Accepted values: Top, Center, Bottom, Distributed, Justify + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TextRotation +Degrees to rotate text; up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AutoSize +Autofit cells to width (columns or ranges only). + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: AutoFit + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Width +Set cells to a fixed width (columns or ranges only), ignored if Autosize is specified. + +```yaml +Type: Single +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Height +Set cells to a fixed height (rows or ranges only). + +```yaml +Type: Single +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Hidden +Hide a row or column (not a range); use -Hidden:$false to unhide. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Locked +Locks cells. Cells are locked by default use -locked:$false on the whole sheet and then lock specific ones, and enable protection on the sheet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Merge +Merges cells - it is recommended that you explicitly set -HorizontalAlignment + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Set-ExcelRow.md b/mdHelp/Set-ExcelRow.md new file mode 100644 index 0000000..447b37d --- /dev/null +++ b/mdHelp/Set-ExcelRow.md @@ -0,0 +1,622 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: +schema: 2.0.0 +--- + +# Set-ExcelRow + +## SYNOPSIS +Fills values into a \[new\] row in an Excel spreadsheet, and sets row formats. + +## SYNTAX + +### Package +``` +Set-ExcelRow -ExcelPackage [-Worksheetname ] [-Row ] [-StartColumn ] [-Value ] [-Heading ] [-HeadingBold] [-HeadingSize ] [-NumberFormat ] [-BorderAround ] [-BorderColor ] [-BorderBottom ] [-BorderTop ] [-BorderLeft ] [-BorderRight ] [-FontColor ] [-Bold] [-Italic] [-Underline] [-UnderLineType ] [-StrikeThru] + [-FontShift ] [-FontName ] [-FontSize ] [-BackgroundColor ] [-BackgroundPattern ] [-PatternColor ] [-WrapText] [-HorizontalAlignment ] [-VerticalAlignment ] [-TextRotation ] [-Height ] [-Hide] [-ReturnRange] [-PassThru] [] +``` + +### Sheet +``` +Set-ExcelRow -Worksheet [-Row ] [-StartColumn ] [-Value ] [-Heading ] [-HeadingBold] [-HeadingSize ] [-NumberFormat ] [-BorderAround ] [-BorderColor ] [-BorderBottom ] [-BorderTop ] [-BorderLeft ] [-BorderRight ] [-FontColor ] [-Bold] [-Italic] [-Underline] [-UnderLineType ] [-StrikeThru] [-FontShift ] [-FontName ] [-FontSize ] [-BackgroundColor ] [-BackgroundPattern ] [-PatternColor ] [-WrapText] [-HorizontalAlignment ] [-VerticalAlignment ] [-TextRotation ] [-Height ] [-Hide] [-ReturnRange] [-PassThru] [] +``` + +## DESCRIPTION +Set-ExcelRow accepts either a Worksheet object or an ExcelPackage object returned by Export-Excel and the name of a sheet, and inserts the chosen contents into a row of the sheet. + +The contents can be a constant, like "42", a formula or a script block which is converted into a constant or a formula. + +The first cell of the row can optionally be given a heading. + +## 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. + +## PARAMETERS + +### -ExcelPackage +An Excel package object - for example from Export-Excel -PassThru - if specified requires a sheet name to be passed a parameter. + +```yaml +Type: ExcelPackage +Parameter Sets: Package +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Worksheetname +The name of the sheet to update in the package. + +```yaml +Type: Object +Parameter Sets: Package +Aliases: + +Required: False +Position: Named +Default value: Sheet1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Worksheet +A worksheet object instead of passing a name and package. + +```yaml +Type: ExcelWorksheet +Parameter Sets: Sheet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Row +Row to fill right - first row is 1. 0 will be interpreted as first unused row. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -StartColumn +Position in the row to start from. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Value +Value, Formula or ScriptBlock to fill in. A ScriptBlock can use $worksheet, $row, $Column \[number\], $ColumnName \[letter(s)\], $startRow, $startColumn, $endRow, $endColumn. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Heading +Optional row-heading. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HeadingBold +Set the heading in bold type. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HeadingSize +Change the font-size of the heading. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NumberFormat +Number format to apply to cells e.g. +"dd/MM/yyyy HH:mm", "£#,##0.00;\[Red\]-£#,##0.00", "0.00%" , "##/##" , "0.0E+0" etc. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: NFormat + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderAround +Style of border to draw around the row. + +```yaml +Type: ExcelBorderStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Hair, Dotted, DashDot, Thin, DashDotDot, Dashed, MediumDashDotDot, MediumDashed, MediumDashDot, Thick, Medium, Double + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderColor +Color of the border. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: [System.Drawing.Color]::Black +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderBottom +Style for the bottom border. + +```yaml +Type: ExcelBorderStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Hair, Dotted, DashDot, Thin, DashDotDot, Dashed, MediumDashDotDot, MediumDashed, MediumDashDot, Thick, Medium, Double + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderTop +Style for the top border. + +```yaml +Type: ExcelBorderStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Hair, Dotted, DashDot, Thin, DashDotDot, Dashed, MediumDashDotDot, MediumDashed, MediumDashDot, Thick, Medium, Double + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderLeft +Style for the left border. + +```yaml +Type: ExcelBorderStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Hair, Dotted, DashDot, Thin, DashDotDot, Dashed, MediumDashDotDot, MediumDashed, MediumDashDot, Thick, Medium, Double + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BorderRight +Style for the right border. + +```yaml +Type: ExcelBorderStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Hair, Dotted, DashDot, Thin, DashDotDot, Dashed, MediumDashDotDot, MediumDashed, MediumDashDot, Thick, Medium, Double + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FontColor +Color for the text - if not specified the font will be left as it it is. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Bold +Make text bold; use -Bold:$false to remove bold. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Italic +Make text italic; use -Italic:$false to remove italic. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Underline +Underline the text using the underline style in -UnderlineType; use -Underline:$false to remove underlining. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UnderLineType +Specifies whether underlining should be single or double, normal or accounting mode. The default is "Single". + +```yaml +Type: ExcelUnderLineType +Parameter Sets: (All) +Aliases: +Accepted values: None, Single, Double, SingleAccounting, DoubleAccounting + +Required: False +Position: Named +Default value: Single +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StrikeThru +Strike through text; use -StrikeThru:$false to remove strike through. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FontShift +Subscript or Superscript (or none). + +```yaml +Type: ExcelVerticalAlignmentFont +Parameter Sets: (All) +Aliases: +Accepted values: None, Baseline, Subscript, Superscript + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FontName +Font to use - Excel defaults to Calibri. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FontSize +Point size for the text. + +```yaml +Type: Single +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BackgroundColor +Change background color. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BackgroundPattern +Background pattern - solid by default. + +```yaml +Type: ExcelFillStyle +Parameter Sets: (All) +Aliases: +Accepted values: None, Solid, DarkGray, MediumGray, LightGray, Gray125, Gray0625, DarkVertical, DarkHorizontal, DarkDown, DarkUp, DarkGrid, DarkTrellis, LightVertical, LightHorizontal, LightDown, LightUp, LightGrid, LightTrellis + +Required: False +Position: Named +Default value: Solid +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PatternColor +Secondary color for background pattern. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: PatternColour + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WrapText +Turn on Text-Wrapping; use -WrapText:$false to turn off wrapping. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HorizontalAlignment +Position cell contents to Left, Right, Center etc. +default is 'General'. + +```yaml +Type: ExcelHorizontalAlignment +Parameter Sets: (All) +Aliases: +Accepted values: General, Left, Center, CenterContinuous, Right, Fill, Distributed, Justify + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -VerticalAlignment +Position cell contents to Top, Bottom or Center. + +```yaml +Type: ExcelVerticalAlignment +Parameter Sets: (All) +Aliases: +Accepted values: Top, Center, Bottom, Distributed, Justify + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TextRotation +Degrees to rotate text. Up to +90 for anti-clockwise ("upwards"), or to -90 for clockwise. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Height +Set cells to a fixed height. + +```yaml +Type: Single +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Hide +Hide the row. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ReturnRange +If sepecified, returns the range of cells which were affected. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +If Specified, return a row object to allow further work to be done. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### OfficeOpenXml.ExcelRow +### System.String +## NOTES + +## RELATED LINKS diff --git a/mdHelp/Update-FirstObjectProperties.md b/mdHelp/Update-FirstObjectProperties.md new file mode 100644 index 0000000..4fd13a5 --- /dev/null +++ b/mdHelp/Update-FirstObjectProperties.md @@ -0,0 +1,94 @@ +--- +external help file: ImportExcel-help.xml +Module Name: ImportExcel +online version: https://github.com/dfinke/ImportExcel +schema: 2.0.0 +--- + +# Update-FirstObjectProperties + +## SYNOPSIS +Updates the first object to contain all the properties of the object with the most properties in the array. + +## SYNTAX +``` +Update-FirstObjectProperties +``` + +## DESCRIPTION +Updates the first object to contain all the properties found anywhere in the array. + +This is usefull when not all objects have the same quantity of properties and CmdLets like Out-GridView or Export-Excel are not able to show all the properties because the first object doesn't have them all. + +## 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. + +## PARAMETERS + +## INPUTS + +## OUTPUTS + +## NOTES +CHANGELOG +2017/06/08 Function born + +## RELATED LINKS + +[https://github.com/dfinke/ImportExcel](https://github.com/dfinke/ImportExcel) + From 1f767338f254b4a01c6e771738a581f379e32999 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sun, 17 Nov 2019 16:04:10 +0000 Subject: [PATCH 02/25] Fix path error in PSM1 --- ImportExcel.psm1 | 53 ++++++++++++++++++++++++------------------------ 1 file changed, 26 insertions(+), 27 deletions(-) diff --git a/ImportExcel.psm1 b/ImportExcel.psm1 index 6bc76f5..359fd89 100644 --- a/ImportExcel.psm1 +++ b/ImportExcel.psm1 @@ -4,6 +4,32 @@ Add-Type -Path "$($PSScriptRoot)\EPPlus.dll" try {[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")} catch {Write-Warning -Message "System.Drawing could not be loaded. Color and font look-ups may not be available."} +foreach ($directory in @('ExportedCommands','Charting','InferData','Pivot')) { + Get-ChildItem -Path "$PSScriptRoot\$directory\*.ps1" | ForEach-Object {. $_.FullName} +} + +if ($PSVersionTable.PSVersion.Major -ge 5) { + . $PSScriptRoot\Plot.ps1 + + Function New-Plot { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'New-Plot does not change system state')] + Param() + + [PSPlot]::new() + } + +} +else { + Write-Warning 'PowerShell 5 is required for plot.ps1' + Write-Warning 'PowerShell Excel is ready, except for that functionality' +} + + +. $PSScriptRoot\ArgumentCompletion.ps1 + +#endregion + + if (($IsLinux -or $IsMacOS) -or $env:NoAutoSize) { $ExcelPackage = [OfficeOpenXml.ExcelPackage]::new() $Cells = ($ExcelPackage | Add-WorkSheet).Cells['A1'] @@ -27,30 +53,3 @@ if (($IsLinux -or $IsMacOS) -or $env:NoAutoSize) { $ExcelPackage | Close-ExcelPackage -NoSave } } - -Get-ChildItem -Path "$PSScriptRoot\ExportedCommands\*.ps1" | ForEach-Object {. $_.FullName} - -. $PSScriptRoot\Charting.ps1 -. $PSScriptRoot\Export-StocksToExcel.ps1 -. $PSScriptRoot\InferData.ps1 -. $PSScriptRoot\Pivot.ps1 - - -if ($PSVersionTable.PSVersion.Major -ge 5) { - . $PSScriptRoot\Plot.ps1 - - Function New-Plot { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'New-Plot does not change system state')] - Param() - - [PSPlot]::new() - } - -} -else { - Write-Warning 'PowerShell 5 is required for plot.ps1' - Write-Warning 'PowerShell Excel is ready, except for that functionality' -} -#endregion - -. $PSScriptRoot\ArgumentCompletion.ps1 \ No newline at end of file From cc5eff11570560ceb6da6ccdaecb5f27849ba205 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Mon, 18 Nov 2019 01:30:37 +0000 Subject: [PATCH 03/25] sync export-excel to 321699e spec. --- ExportedCommands/Export-Excel.ps1 | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/ExportedCommands/Export-Excel.ps1 b/ExportedCommands/Export-Excel.ps1 index 2659470..0c5cfa3 100644 --- a/ExportedCommands/Export-Excel.ps1 +++ b/ExportedCommands/Export-Excel.ps1 @@ -201,8 +201,8 @@ <# If inputObject was passed via the pipeline it won't be visible until the process block, we will only see it here if it was passed as a parameter if it is a data table don't do foreach on it (slow) - put the whole table in and set dates on date columns, set things up for the end block, and skip the process block #> - if ($InputObject -is [System.Data.DataTable]) { - #don't leave caller with a renamed table, save the name and set it back later + if ($InputObject -is [System.Data.DataTable]) { + #Change TableName if $TableName is non-empty; don't leave caller with a renamed table! $orginalTableName = $InputObject.TableName if ($TableName) { $InputObject.TableName = $TableName @@ -211,8 +211,8 @@ Write-Warning "Table name $($InputObject.TableName) is not unique, adding '_' to it " $InputObject.TableName += "_" } - if ($TableName -or $PSBoundParameters.ContainsKey("TableStyle")) { - $TableName = $null + #Insert as a table, if Tablestyle didn't arrive as a default, or $TableName non-null - even if empty + if ($null -ne $TableName -or $PSBoundParameters.ContainsKey("TableStyle")) { $null = $ws.Cells[$row,$StartColumn].LoadFromDataTable($InputObject, (-not $noHeader),$TableStyle ) } else { @@ -233,9 +233,9 @@ } #endregion else {$firstTimeThru = $true} - } + } - process { if ($PSBoundParameters.ContainsKey("InputObject")) { + process { if ($PSBoundParameters.ContainsKey("InputObject")) { try { if ($null -eq $InputObject) {$row += 1} foreach ($TargetData in $InputObject) { @@ -346,9 +346,9 @@ } catch {throw "Failed exporting data to worksheet '$WorksheetName' to '$Path': $_" } - }} + }} - end { + end { if ($firstTimeThru -and $ws.Dimension) { $LastRow = $ws.Dimension.End.Row $LastCol = $ws.Dimension.End.Column @@ -400,11 +400,11 @@ if ($RangeName) { Add-ExcelName -Range $ws.Cells[$dataRange] -RangeName $RangeName} #Allow table to be inserted by specifying Name, or Style or both; only process autoFilter if there is no table (they clash). - if ($null -ne $TableName) { - Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $PSBoundParameters['TableName'] -TableStyle $TableStyle - } - elseif ($PSBoundParameters.ContainsKey('TableStyle')) { - Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName "" -TableStyle $TableStyle + if ($null -ne $TableName -or $PSBoundParameters.ContainsKey('TableStyle')) { + #Already inserted Excel table if input was a DataTable + if ($InputObject -isnot [System.Data.DataTable]) { + Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $TableName -TableStyle $TableStyle + } } elseif ($AutoFilter) { try { @@ -413,7 +413,6 @@ } catch {Write-Warning -Message "Failed adding autofilter to worksheet '$WorksheetName': $_"} } - if ($PivotTableDefinition) { foreach ($item in $PivotTableDefinition.GetEnumerator()) { $params = $item.value From d3a2edcc5f71526531fead20c0c6b0dc0030e38e Mon Sep 17 00:00:00 2001 From: jhoneill Date: Mon, 18 Nov 2019 01:32:14 +0000 Subject: [PATCH 04/25] default CI/Install-PowerShell version to stable release --- CI/InstallPowerShell.ps1 | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/CI/InstallPowerShell.ps1 b/CI/InstallPowerShell.ps1 index b4f3cc7..e49b21c 100644 --- a/CI/InstallPowerShell.ps1 +++ b/CI/InstallPowerShell.ps1 @@ -6,11 +6,15 @@ Param ( # Version to install in the format from the .msi, for example "7.0.0-preview.1" - [Parameter(Mandatory)] [String]$Version ) $ErrorActionPreference = 'Stop' +if (-not $Version) { + $Version = (Invoke-RestMethod https://raw.githubusercontent.com/PowerShell/PowerShell/master/tools/metadata.json).StableReleaseTag +} +$Version = $Version -replace "^v","" + '[Progress] Downloading PowerShell Core.' $MsiPath = Join-Path $env:TEMP "PowerShell-$Version-win-x64.msi" [System.Net.WebClient]::new().DownloadFile("https://github.com/PowerShell/PowerShell/releases/download/v$Version/PowerShell-$Version-win-x64.msi", $MsiPath) From f27729d2abcc7c71a55f6bc6810e35421e5cc1af Mon Sep 17 00:00:00 2001 From: jhoneill Date: Mon, 18 Nov 2019 07:50:20 +0000 Subject: [PATCH 05/25] Remove 72 empty catch blocks and Loadpsd1 --- Examples/AddWorkSheet/AddMultiWorkSheet.ps1 | 4 ++-- Examples/AddWorkSheet/AddWorkSheet.ps1 | 2 +- Examples/Charts/MultiSeries.ps1 | 2 +- Examples/Charts/MultiSeries1.ps1 | 2 +- Examples/Charts/MultipleCharts.ps1 | 2 +- Examples/Charts/plot.ps1 | 2 +- Examples/ConditionalFormatting/ConditionalText.ps1 | 2 +- Examples/ConditionalFormatting/ContainsBlanks.ps1 | 2 +- Examples/ConditionalFormatting/Databar.ps1 | 2 +- Examples/ConditionalFormatting/FormatCalculations.ps1 | 2 +- Examples/ConditionalFormatting/GetProcess.ps1 | 2 +- Examples/ConditionalFormatting/Highlight-Last7Days.ps1 | 2 +- Examples/ConditionalFormatting/Highlight-LastMonth.ps1 | 2 +- Examples/ConditionalFormatting/Highlight-LastWeek.ps1 | 2 +- Examples/ConditionalFormatting/Highlight-NextMonth.ps1 | 2 +- Examples/ConditionalFormatting/Highlight-NextWeek.ps1 | 2 +- Examples/ConditionalFormatting/Highlight-ThisMonth.ps1 | 2 +- Examples/ConditionalFormatting/Highlight-ThisWeek.ps1 | 2 +- Examples/ConditionalFormatting/Highlight-Today.ps1 | 2 +- Examples/ConditionalFormatting/Highlight-Tomorrow.ps1 | 2 +- Examples/ConditionalFormatting/Highlight-Yesterday.ps1 | 2 +- Examples/ConditionalFormatting/HighlightDuplicates.ps1 | 2 +- Examples/ConditionalFormatting/MonthlyTemperatuesDatabar.ps1 | 2 +- Examples/ConditionalFormatting/RangeFormatting.ps1 | 2 +- Examples/ConditionalFormatting/SalesReportWithDatabar.ps1 | 2 +- Examples/ConvertFrom/ConvertFrom.ps1 | 2 +- Examples/CustomReporting/CustomReport.ps1 | 2 +- Examples/ExcelDataValidation/MutipleValidations.ps1 | 2 +- Examples/ExcelToSQLInsert/DemoSQLInsert.ps1 | 2 +- Examples/Fibonacci/ShowFibonacci.ps1 | 2 +- Examples/FormatCellStyles/ApplyFormatInScriptBlock.ps1 | 2 +- Examples/FormatCellStyles/PassInScriptBlock.ps1 | 2 +- Examples/HyperLinks/Hyperlinks.ps1 | 2 +- Examples/ImportHtml/DemoGraphics.ps1 | 2 +- Examples/ImportHtml/PeriodicElements.ps1 | 2 +- Examples/ImportHtml/StarTrek.ps1 | 2 +- Examples/JoinWorksheet/JoinSalesData.ps1 | 2 +- Examples/JustCharts/CentralLimitTheorem.ps1 | 2 +- Examples/JustCharts/PieChartHandles.ps1 | 2 +- Examples/JustCharts/PieChartPM.ps1 | 2 +- Examples/JustCharts/TryBarChart.ps1 | 2 +- Examples/JustCharts/TryColumnChart.ps1 | 2 +- Examples/JustCharts/TryPieChart.ps1 | 2 +- Examples/MergeWorkSheet/MergeCSV.ps1 | 2 +- Examples/MoveSheets/MoveSheets.ps1 | 2 +- Examples/Nasa/FireBalls.ps1 | 2 +- Examples/NumberFormat/ColorizeNumbers.ps1 | 2 +- Examples/NumberFormat/CurrencyFormat.ps1 | 2 +- Examples/NumberFormat/PercentagFormat.ps1 | 2 +- Examples/NumberFormat/PosNegNumbers.ps1 | 2 +- Examples/NumberFormat/Win32LogicalDisk.ps1 | 2 +- Examples/NumberFormat/Win32LogicalDiskFormatted.ps1 | 2 +- Examples/PassThru/TryPassThru.ps1 | 2 +- Examples/PivotTable/PivotTableWithName.ps1 | 2 +- Examples/PivotTableFilters/testPivotFilter.ps1 | 2 +- Examples/Plot/PlotCos.ps1 | 2 +- Examples/SQL+FillColumns+Pivot/Example.ps1 | 2 +- Examples/SQL+FillColumns+Pivot/Example2.ps1 | 2 +- .../SetColumnBackgroundColor/SetColumnBackgroundColor.ps1 | 2 +- Examples/Sparklines/SalesByQuarter.ps1 | 2 +- Examples/Sparklines/Sparklines.ps1 | 2 +- Examples/SpreadsheetCells/CalculatedFields.ps1 | 2 +- Examples/SpreadsheetCells/ExcelFormulasUsingAddMember.ps1 | 2 +- Examples/SpreadsheetCells/ExcelFunctions.ps1 | 2 +- Examples/SpreadsheetCells/HyperLink.ps1 | 2 +- Examples/Styles/MultipleStyles.ps1 | 2 +- Examples/Styles/NewExcelStyle.ps1 | 2 +- Examples/Tables/MultipleTables.ps1 | 2 +- Examples/TestRestAPI/RunAndShowUnitTests.ps1 | 2 +- Examples/TestRestAPI/TryIt.ps1 | 2 +- Examples/TryMultiplePivotTablesFromOneSheet.ps1 | 2 +- Examples/XlRangeToImage/XlRangeToImage.ps1 | 2 +- LoadPSD1.ps1 | 3 --- 73 files changed, 73 insertions(+), 76 deletions(-) delete mode 100644 LoadPSD1.ps1 diff --git a/Examples/AddWorkSheet/AddMultiWorkSheet.ps1 b/Examples/AddWorkSheet/AddMultiWorkSheet.ps1 index fc0a877..6318980 100644 --- a/Examples/AddWorkSheet/AddMultiWorkSheet.ps1 +++ b/Examples/AddWorkSheet/AddMultiWorkSheet.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $xlSourcefile = "$env:TEMP\Source.xlsx" write-host "Save location: $xlSourcefile" @@ -6,7 +6,7 @@ write-host "Save location: $xlSourcefile" Remove-Item $xlSourcefile -ErrorAction Ignore #Put some simple data in a worksheet and Get an excel package object to represent the file -$TabData1 = 1..5 | Export-Excel $xlSourcefile -WorksheetName 'Tab 1' -AutoSize -AutoFilter +$TabData1 = 1..5 | Export-Excel $xlSourcefile -WorksheetName 'Tab1' -AutoSize -AutoFilter #Add another tab. Replace the $TabData2 with your data $TabData2 = 1..10 | Export-Excel $xlSourcefile -WorksheetName 'Tab 2' -AutoSize -AutoFilter diff --git a/Examples/AddWorkSheet/AddWorkSheet.ps1 b/Examples/AddWorkSheet/AddWorkSheet.ps1 index 4535d4c..c4e798c 100644 --- a/Examples/AddWorkSheet/AddWorkSheet.ps1 +++ b/Examples/AddWorkSheet/AddWorkSheet.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $xlSourcefile = "$env:TEMP\Source.xlsx" diff --git a/Examples/Charts/MultiSeries.ps1 b/Examples/Charts/MultiSeries.ps1 index e1d9eee..ff3fdfb 100644 --- a/Examples/Charts/MultiSeries.ps1 +++ b/Examples/Charts/MultiSeries.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} Remove-Item temp.xlsx -ErrorAction Ignore diff --git a/Examples/Charts/MultiSeries1.ps1 b/Examples/Charts/MultiSeries1.ps1 index ddcbf4b..e727ffc 100644 --- a/Examples/Charts/MultiSeries1.ps1 +++ b/Examples/Charts/MultiSeries1.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} Remove-Item temp.xlsx -ErrorAction Ignore diff --git a/Examples/Charts/MultipleCharts.ps1 b/Examples/Charts/MultipleCharts.ps1 index dfffe5d..82f5ad0 100644 --- a/Examples/Charts/MultipleCharts.ps1 +++ b/Examples/Charts/MultipleCharts.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} Remove-Item -Path Tools.xlsx diff --git a/Examples/Charts/plot.ps1 b/Examples/Charts/plot.ps1 index f8c0401..c311fe9 100644 --- a/Examples/Charts/plot.ps1 +++ b/Examples/Charts/plot.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} function plot { param( diff --git a/Examples/ConditionalFormatting/ConditionalText.ps1 b/Examples/ConditionalFormatting/ConditionalText.ps1 index 96130e1..8a9b9ab 100644 --- a/Examples/ConditionalFormatting/ConditionalText.ps1 +++ b/Examples/ConditionalFormatting/ConditionalText.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $file = "$env:temp\conditionalTextFormatting.xlsx" Remove-Item $file -ErrorAction Ignore diff --git a/Examples/ConditionalFormatting/ContainsBlanks.ps1 b/Examples/ConditionalFormatting/ContainsBlanks.ps1 index 45eb134..3ced09a 100644 --- a/Examples/ConditionalFormatting/ContainsBlanks.ps1 +++ b/Examples/ConditionalFormatting/ContainsBlanks.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} #Define a "Contains blanks" rule. No format is specified so it default to dark-red text on light-pink background. $ContainsBlanks = New-ConditionalText -ConditionalType ContainsBlanks diff --git a/Examples/ConditionalFormatting/Databar.ps1 b/Examples/ConditionalFormatting/Databar.ps1 index 3b72742..d117244 100644 --- a/Examples/ConditionalFormatting/Databar.ps1 +++ b/Examples/ConditionalFormatting/Databar.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $path = "$env:temp\test.xlsx" Remove-Item -Path $path -ErrorAction Ignore diff --git a/Examples/ConditionalFormatting/FormatCalculations.ps1 b/Examples/ConditionalFormatting/FormatCalculations.ps1 index 11098d7..f343b0c 100644 --- a/Examples/ConditionalFormatting/FormatCalculations.ps1 +++ b/Examples/ConditionalFormatting/FormatCalculations.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $f = "$env:TEMP\testExport.xlsx" diff --git a/Examples/ConditionalFormatting/GetProcess.ps1 b/Examples/ConditionalFormatting/GetProcess.ps1 index ed6c47e..860d130 100644 --- a/Examples/ConditionalFormatting/GetProcess.ps1 +++ b/Examples/ConditionalFormatting/GetProcess.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} Remove-Item "$env:TEMP\testExport.xlsx" -ErrorAction Ignore diff --git a/Examples/ConditionalFormatting/Highlight-Last7Days.ps1 b/Examples/ConditionalFormatting/Highlight-Last7Days.ps1 index 3246bd8..005f17a 100644 --- a/Examples/ConditionalFormatting/Highlight-Last7Days.ps1 +++ b/Examples/ConditionalFormatting/Highlight-Last7Days.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $f = ".\testExport.xlsx" diff --git a/Examples/ConditionalFormatting/Highlight-LastMonth.ps1 b/Examples/ConditionalFormatting/Highlight-LastMonth.ps1 index 04d43ac..fe837b4 100644 --- a/Examples/ConditionalFormatting/Highlight-LastMonth.ps1 +++ b/Examples/ConditionalFormatting/Highlight-LastMonth.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $f = ".\testExport.xlsx" diff --git a/Examples/ConditionalFormatting/Highlight-LastWeek.ps1 b/Examples/ConditionalFormatting/Highlight-LastWeek.ps1 index 18466c0..7877296 100644 --- a/Examples/ConditionalFormatting/Highlight-LastWeek.ps1 +++ b/Examples/ConditionalFormatting/Highlight-LastWeek.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $f = ".\testExport.xlsx" diff --git a/Examples/ConditionalFormatting/Highlight-NextMonth.ps1 b/Examples/ConditionalFormatting/Highlight-NextMonth.ps1 index 4d0f60c..ca8285a 100644 --- a/Examples/ConditionalFormatting/Highlight-NextMonth.ps1 +++ b/Examples/ConditionalFormatting/Highlight-NextMonth.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $f = ".\testExport.xlsx" diff --git a/Examples/ConditionalFormatting/Highlight-NextWeek.ps1 b/Examples/ConditionalFormatting/Highlight-NextWeek.ps1 index 196ab22..5930faa 100644 --- a/Examples/ConditionalFormatting/Highlight-NextWeek.ps1 +++ b/Examples/ConditionalFormatting/Highlight-NextWeek.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $f = ".\testExport.xlsx" diff --git a/Examples/ConditionalFormatting/Highlight-ThisMonth.ps1 b/Examples/ConditionalFormatting/Highlight-ThisMonth.ps1 index 85a7c81..e3ddb87 100644 --- a/Examples/ConditionalFormatting/Highlight-ThisMonth.ps1 +++ b/Examples/ConditionalFormatting/Highlight-ThisMonth.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $f = ".\testExport.xlsx" diff --git a/Examples/ConditionalFormatting/Highlight-ThisWeek.ps1 b/Examples/ConditionalFormatting/Highlight-ThisWeek.ps1 index 02a4de0..da9f46a 100644 --- a/Examples/ConditionalFormatting/Highlight-ThisWeek.ps1 +++ b/Examples/ConditionalFormatting/Highlight-ThisWeek.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $f = ".\testExport.xlsx" diff --git a/Examples/ConditionalFormatting/Highlight-Today.ps1 b/Examples/ConditionalFormatting/Highlight-Today.ps1 index fce0ec8..58df813 100644 --- a/Examples/ConditionalFormatting/Highlight-Today.ps1 +++ b/Examples/ConditionalFormatting/Highlight-Today.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $f = ".\testExport.xlsx" diff --git a/Examples/ConditionalFormatting/Highlight-Tomorrow.ps1 b/Examples/ConditionalFormatting/Highlight-Tomorrow.ps1 index d336223..e6dc9f4 100644 --- a/Examples/ConditionalFormatting/Highlight-Tomorrow.ps1 +++ b/Examples/ConditionalFormatting/Highlight-Tomorrow.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $f = ".\testExport.xlsx" diff --git a/Examples/ConditionalFormatting/Highlight-Yesterday.ps1 b/Examples/ConditionalFormatting/Highlight-Yesterday.ps1 index af53393..0b3f080 100644 --- a/Examples/ConditionalFormatting/Highlight-Yesterday.ps1 +++ b/Examples/ConditionalFormatting/Highlight-Yesterday.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $f = ".\testExport.xlsx" diff --git a/Examples/ConditionalFormatting/HighlightDuplicates.ps1 b/Examples/ConditionalFormatting/HighlightDuplicates.ps1 index 5ed5627..66d71c0 100644 --- a/Examples/ConditionalFormatting/HighlightDuplicates.ps1 +++ b/Examples/ConditionalFormatting/HighlightDuplicates.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $f = ".\testExport.xlsx" diff --git a/Examples/ConditionalFormatting/MonthlyTemperatuesDatabar.ps1 b/Examples/ConditionalFormatting/MonthlyTemperatuesDatabar.ps1 index 8cfb0dd..d75cb1d 100644 --- a/Examples/ConditionalFormatting/MonthlyTemperatuesDatabar.ps1 +++ b/Examples/ConditionalFormatting/MonthlyTemperatuesDatabar.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} Remove-Item -Path .\test.xlsx -ErrorAction Ignore diff --git a/Examples/ConditionalFormatting/RangeFormatting.ps1 b/Examples/ConditionalFormatting/RangeFormatting.ps1 index 2ca3b60..aeee56b 100644 --- a/Examples/ConditionalFormatting/RangeFormatting.ps1 +++ b/Examples/ConditionalFormatting/RangeFormatting.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $f = ".\testExport.xlsx" Remove-Item $f -ErrorAction Ignore diff --git a/Examples/ConditionalFormatting/SalesReportWithDatabar.ps1 b/Examples/ConditionalFormatting/SalesReportWithDatabar.ps1 index 8a126c5..a36e444 100644 --- a/Examples/ConditionalFormatting/SalesReportWithDatabar.ps1 +++ b/Examples/ConditionalFormatting/SalesReportWithDatabar.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} Remove-Item -Path .\test.xlsx -ErrorAction Ignore diff --git a/Examples/ConvertFrom/ConvertFrom.ps1 b/Examples/ConvertFrom/ConvertFrom.ps1 index 0aeac85..8885a59 100644 --- a/Examples/ConvertFrom/ConvertFrom.ps1 +++ b/Examples/ConvertFrom/ConvertFrom.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} ConvertFrom-ExcelToSQLInsert People .\testSQLGen.xlsx diff --git a/Examples/CustomReporting/CustomReport.ps1 b/Examples/CustomReporting/CustomReport.ps1 index 70447bb..35c8e9f 100644 --- a/Examples/CustomReporting/CustomReport.ps1 +++ b/Examples/CustomReporting/CustomReport.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $f = "$env:temp\dashboard.xlsx" Remove-Item $f -ErrorAction Ignore diff --git a/Examples/ExcelDataValidation/MutipleValidations.ps1 b/Examples/ExcelDataValidation/MutipleValidations.ps1 index 4344843..b19ef2e 100644 --- a/Examples/ExcelDataValidation/MutipleValidations.ps1 +++ b/Examples/ExcelDataValidation/MutipleValidations.ps1 @@ -13,7 +13,7 @@ * Add .01 in column F #> -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $path = "$Env:TEMP\DataValidation.xlsx" Remove-Item $path -ErrorAction SilentlyContinue diff --git a/Examples/ExcelToSQLInsert/DemoSQLInsert.ps1 b/Examples/ExcelToSQLInsert/DemoSQLInsert.ps1 index 9825e1c..c29cf11 100644 --- a/Examples/ExcelToSQLInsert/DemoSQLInsert.ps1 +++ b/Examples/ExcelToSQLInsert/DemoSQLInsert.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} ConvertFrom-ExcelToSQLInsert -TableName "Movies" -Path ".\Movies.xlsx" -ConvertEmptyStringsToNull '' diff --git a/Examples/Fibonacci/ShowFibonacci.ps1 b/Examples/Fibonacci/ShowFibonacci.ps1 index 54bc2d1..eab3a94 100644 --- a/Examples/Fibonacci/ShowFibonacci.ps1 +++ b/Examples/Fibonacci/ShowFibonacci.ps1 @@ -1,6 +1,6 @@ param ($fibonacciDigits=10) -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $file = "fib.xlsx" Remove-Item "fib.xlsx" -ErrorAction Ignore diff --git a/Examples/FormatCellStyles/ApplyFormatInScriptBlock.ps1 b/Examples/FormatCellStyles/ApplyFormatInScriptBlock.ps1 index 9fb2b21..10e1f41 100644 --- a/Examples/FormatCellStyles/ApplyFormatInScriptBlock.ps1 +++ b/Examples/FormatCellStyles/ApplyFormatInScriptBlock.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $xlfile = "$env:temp\testFmt.xlsx" diff --git a/Examples/FormatCellStyles/PassInScriptBlock.ps1 b/Examples/FormatCellStyles/PassInScriptBlock.ps1 index ac9e0a2..2964a57 100644 --- a/Examples/FormatCellStyles/PassInScriptBlock.ps1 +++ b/Examples/FormatCellStyles/PassInScriptBlock.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $xlfile = "$env:temp\testFmt.xlsx" Remove-Item $xlfile -ErrorAction Ignore diff --git a/Examples/HyperLinks/Hyperlinks.ps1 b/Examples/HyperLinks/Hyperlinks.ps1 index 6e5c2be..4c5e627 100644 --- a/Examples/HyperLinks/Hyperlinks.ps1 +++ b/Examples/HyperLinks/Hyperlinks.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} @" site,link diff --git a/Examples/ImportHtml/DemoGraphics.ps1 b/Examples/ImportHtml/DemoGraphics.ps1 index 68c8868..b017e70 100644 --- a/Examples/ImportHtml/DemoGraphics.ps1 +++ b/Examples/ImportHtml/DemoGraphics.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} Import-Html "http://en.wikipedia.org/wiki/Demographics_of_India" 4 \ No newline at end of file diff --git a/Examples/ImportHtml/PeriodicElements.ps1 b/Examples/ImportHtml/PeriodicElements.ps1 index d4038a4..b9dd4ae 100644 --- a/Examples/ImportHtml/PeriodicElements.ps1 +++ b/Examples/ImportHtml/PeriodicElements.ps1 @@ -1,3 +1,3 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} Import-Html "http://www.science.co.il/PTelements.asp" 1 \ No newline at end of file diff --git a/Examples/ImportHtml/StarTrek.ps1 b/Examples/ImportHtml/StarTrek.ps1 index 17fd975..53ab094 100644 --- a/Examples/ImportHtml/StarTrek.ps1 +++ b/Examples/ImportHtml/StarTrek.ps1 @@ -1,3 +1,3 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} Import-Html "https://en.wikipedia.org/wiki/List_of_Star_Trek:_The_Original_Series_episodes" 2 \ No newline at end of file diff --git a/Examples/JoinWorksheet/JoinSalesData.ps1 b/Examples/JoinWorksheet/JoinSalesData.ps1 index f8938f1..f4463fb 100644 --- a/Examples/JoinWorksheet/JoinSalesData.ps1 +++ b/Examples/JoinWorksheet/JoinSalesData.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $xlfile = "$env:temp\AllSales.xlsx" diff --git a/Examples/JustCharts/CentralLimitTheorem.ps1 b/Examples/JustCharts/CentralLimitTheorem.ps1 index 1d59d3d..6945647 100644 --- a/Examples/JustCharts/CentralLimitTheorem.ps1 +++ b/Examples/JustCharts/CentralLimitTheorem.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} ColumnChart -Title "Central Limit Theorem" -NoLegend ($( for ($i = 1; $i -le 500; $i++) { diff --git a/Examples/JustCharts/PieChartHandles.ps1 b/Examples/JustCharts/PieChartHandles.ps1 index 7103275..12f5478 100644 --- a/Examples/JustCharts/PieChartHandles.ps1 +++ b/Examples/JustCharts/PieChartHandles.ps1 @@ -2,7 +2,7 @@ # Sum up handles by company # Show the Pie Chart -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} PieChart -Title "Total Handles by Company" ` (Invoke-Sum (Get-Process | Where-Object company) company handles) diff --git a/Examples/JustCharts/PieChartPM.ps1 b/Examples/JustCharts/PieChartPM.ps1 index 68c404f..1d24587 100644 --- a/Examples/JustCharts/PieChartPM.ps1 +++ b/Examples/JustCharts/PieChartPM.ps1 @@ -2,7 +2,7 @@ # Sum up PM by company # Show the Pie Chart -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} PieChart -Title "Total PM by Company" ` (Invoke-Sum (Get-Process|Where-Object company) company pm) diff --git a/Examples/JustCharts/TryBarChart.ps1 b/Examples/JustCharts/TryBarChart.ps1 index 57208de..d007dcd 100644 --- a/Examples/JustCharts/TryBarChart.ps1 +++ b/Examples/JustCharts/TryBarChart.ps1 @@ -1,3 +1,3 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} BarChart (.\TargetData.ps1) "A BarChart" \ No newline at end of file diff --git a/Examples/JustCharts/TryColumnChart.ps1 b/Examples/JustCharts/TryColumnChart.ps1 index d4bd515..945647a 100644 --- a/Examples/JustCharts/TryColumnChart.ps1 +++ b/Examples/JustCharts/TryColumnChart.ps1 @@ -1,3 +1,3 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} ColumnChart (.\TargetData.ps1) "A ColumnChart" diff --git a/Examples/JustCharts/TryPieChart.ps1 b/Examples/JustCharts/TryPieChart.ps1 index 09ccaad..016abf7 100644 --- a/Examples/JustCharts/TryPieChart.ps1 +++ b/Examples/JustCharts/TryPieChart.ps1 @@ -1,3 +1,3 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} PieChart (.\TargetData.ps1) "A PieChart" \ No newline at end of file diff --git a/Examples/MergeWorkSheet/MergeCSV.ps1 b/Examples/MergeWorkSheet/MergeCSV.ps1 index 49f677a..af4f3c1 100644 --- a/Examples/MergeWorkSheet/MergeCSV.ps1 +++ b/Examples/MergeWorkSheet/MergeCSV.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $xlFile = "$env:TEMP\mw.xlsx" diff --git a/Examples/MoveSheets/MoveSheets.ps1 b/Examples/MoveSheets/MoveSheets.ps1 index 6b6887b..330746a 100644 --- a/Examples/MoveSheets/MoveSheets.ps1 +++ b/Examples/MoveSheets/MoveSheets.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $xlfile = "$env:TEMP\testThis.xlsx" Remove-Item $xlfile -ErrorAction Ignore diff --git a/Examples/Nasa/FireBalls.ps1 b/Examples/Nasa/FireBalls.ps1 index cec1554..4dd99a5 100644 --- a/Examples/Nasa/FireBalls.ps1 +++ b/Examples/Nasa/FireBalls.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $header = echo ` 'Date/Time - Peak Brightness (UT)' ` diff --git a/Examples/NumberFormat/ColorizeNumbers.ps1 b/Examples/NumberFormat/ColorizeNumbers.ps1 index 1352432..0b6a026 100644 --- a/Examples/NumberFormat/ColorizeNumbers.ps1 +++ b/Examples/NumberFormat/ColorizeNumbers.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $file = "$env:TEMP\disks.xlsx" diff --git a/Examples/NumberFormat/CurrencyFormat.ps1 b/Examples/NumberFormat/CurrencyFormat.ps1 index d6f589d..490b9d7 100644 --- a/Examples/NumberFormat/CurrencyFormat.ps1 +++ b/Examples/NumberFormat/CurrencyFormat.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $file = "$env:temp\disks.xlsx" diff --git a/Examples/NumberFormat/PercentagFormat.ps1 b/Examples/NumberFormat/PercentagFormat.ps1 index b2e50ed..bd5d5e3 100644 --- a/Examples/NumberFormat/PercentagFormat.ps1 +++ b/Examples/NumberFormat/PercentagFormat.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $file = "disks.xlsx" diff --git a/Examples/NumberFormat/PosNegNumbers.ps1 b/Examples/NumberFormat/PosNegNumbers.ps1 index 5160822..4103837 100644 --- a/Examples/NumberFormat/PosNegNumbers.ps1 +++ b/Examples/NumberFormat/PosNegNumbers.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $file = "disks.xlsx" diff --git a/Examples/NumberFormat/Win32LogicalDisk.ps1 b/Examples/NumberFormat/Win32LogicalDisk.ps1 index fc981dc..97b3176 100644 --- a/Examples/NumberFormat/Win32LogicalDisk.ps1 +++ b/Examples/NumberFormat/Win32LogicalDisk.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $file = "disks.xlsx" diff --git a/Examples/NumberFormat/Win32LogicalDiskFormatted.ps1 b/Examples/NumberFormat/Win32LogicalDiskFormatted.ps1 index 671f979..dd14ae5 100644 --- a/Examples/NumberFormat/Win32LogicalDiskFormatted.ps1 +++ b/Examples/NumberFormat/Win32LogicalDiskFormatted.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $file = "disks.xlsx" diff --git a/Examples/PassThru/TryPassThru.ps1 b/Examples/PassThru/TryPassThru.ps1 index a80e176..424ce87 100644 --- a/Examples/PassThru/TryPassThru.ps1 +++ b/Examples/PassThru/TryPassThru.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $file = "$env:Temp\sales.xlsx" diff --git a/Examples/PivotTable/PivotTableWithName.ps1 b/Examples/PivotTable/PivotTableWithName.ps1 index ae0c395..9ce3f34 100644 --- a/Examples/PivotTable/PivotTableWithName.ps1 +++ b/Examples/PivotTable/PivotTableWithName.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $ExcelParams = @{ Path = "$env:TEMP\test1.xlsx" diff --git a/Examples/PivotTableFilters/testPivotFilter.ps1 b/Examples/PivotTableFilters/testPivotFilter.ps1 index 33b89fd..9963beb 100644 --- a/Examples/PivotTableFilters/testPivotFilter.ps1 +++ b/Examples/PivotTableFilters/testPivotFilter.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $xlFile="$env:TEMP\testPivot.xlsx" Remove-Item $xlFile -ErrorAction Ignore diff --git a/Examples/Plot/PlotCos.ps1 b/Examples/Plot/PlotCos.ps1 index 9be0cf5..6c4c6b8 100644 --- a/Examples/Plot/PlotCos.ps1 +++ b/Examples/Plot/PlotCos.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $plt = New-Plot $plt.Plot((Get-Range 0 5 .02|Foreach-Object {[math]::Cos(2*[math]::pi*$_)})) diff --git a/Examples/SQL+FillColumns+Pivot/Example.ps1 b/Examples/SQL+FillColumns+Pivot/Example.ps1 index 9300f04..4de0062 100644 --- a/Examples/SQL+FillColumns+Pivot/Example.ps1 +++ b/Examples/SQL+FillColumns+Pivot/Example.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $sql = @" SELECT rootfile.baseName , rootfile.extension , Image.fileWidth AS width , image.fileHeight AS height , diff --git a/Examples/SQL+FillColumns+Pivot/Example2.ps1 b/Examples/SQL+FillColumns+Pivot/Example2.ps1 index 58fa933..8fe0a65 100644 --- a/Examples/SQL+FillColumns+Pivot/Example2.ps1 +++ b/Examples/SQL+FillColumns+Pivot/Example2.ps1 @@ -1,6 +1,6 @@ #requires -modules "getSql" -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} #download f1Results from https://1drv.ms/f/s!AhfYu7-CJv4egbt5FD7Cdxi8jSz3aQ and update the path below Get-SQL -Session f1 -Excel -Connection C:\Users\mcp\OneDrive\Public\F1\f1Results.xlsx -showtables -Verbose diff --git a/Examples/SetColumnBackgroundColor/SetColumnBackgroundColor.ps1 b/Examples/SetColumnBackgroundColor/SetColumnBackgroundColor.ps1 index 36580c1..28542d0 100644 --- a/Examples/SetColumnBackgroundColor/SetColumnBackgroundColor.ps1 +++ b/Examples/SetColumnBackgroundColor/SetColumnBackgroundColor.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $path = "$env:TEMP\testBackgroundColor.xlsx" diff --git a/Examples/Sparklines/SalesByQuarter.ps1 b/Examples/Sparklines/SalesByQuarter.ps1 index 0053707..d2263a2 100644 --- a/Examples/Sparklines/SalesByQuarter.ps1 +++ b/Examples/Sparklines/SalesByQuarter.ps1 @@ -1,4 +1,4 @@ -try { . $PSScriptRoot\..\..\LoadPSD1.ps1 } catch { } +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $xlfile = "$env:TEMP\SalesByQuarter.xlsx" Remove-Item $xlfile -ErrorAction SilentlyContinue diff --git a/Examples/Sparklines/Sparklines.ps1 b/Examples/Sparklines/Sparklines.ps1 index 4cc6b44..2816d97 100644 --- a/Examples/Sparklines/Sparklines.ps1 +++ b/Examples/Sparklines/Sparklines.ps1 @@ -1,4 +1,4 @@ -try { . $PSScriptRoot\..\..\LoadPSD1.ps1 } catch { } +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} class data { [datetime]$Date diff --git a/Examples/SpreadsheetCells/CalculatedFields.ps1 b/Examples/SpreadsheetCells/CalculatedFields.ps1 index 2a4c139..be988d7 100644 --- a/Examples/SpreadsheetCells/CalculatedFields.ps1 +++ b/Examples/SpreadsheetCells/CalculatedFields.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} #. ..\New-PSItem.ps1 diff --git a/Examples/SpreadsheetCells/ExcelFormulasUsingAddMember.ps1 b/Examples/SpreadsheetCells/ExcelFormulasUsingAddMember.ps1 index 672324c..e55fab3 100644 --- a/Examples/SpreadsheetCells/ExcelFormulasUsingAddMember.ps1 +++ b/Examples/SpreadsheetCells/ExcelFormulasUsingAddMember.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} Remove-Item .\testFormula.xlsx -ErrorAction Ignore diff --git a/Examples/SpreadsheetCells/ExcelFunctions.ps1 b/Examples/SpreadsheetCells/ExcelFunctions.ps1 index a5aa6f4..aac6f69 100644 --- a/Examples/SpreadsheetCells/ExcelFunctions.ps1 +++ b/Examples/SpreadsheetCells/ExcelFunctions.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} Remove-Item "$env:temp\functions.xlsx" -ErrorAction SilentlyContinue diff --git a/Examples/SpreadsheetCells/HyperLink.ps1 b/Examples/SpreadsheetCells/HyperLink.ps1 index 36e92fe..3f4a111 100644 --- a/Examples/SpreadsheetCells/HyperLink.ps1 +++ b/Examples/SpreadsheetCells/HyperLink.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} Remove-Item "$env:temp\hyperlink.xlsx" -ErrorAction SilentlyContinue diff --git a/Examples/Styles/MultipleStyles.ps1 b/Examples/Styles/MultipleStyles.ps1 index 3c0de35..70b57ff 100644 --- a/Examples/Styles/MultipleStyles.ps1 +++ b/Examples/Styles/MultipleStyles.ps1 @@ -1,4 +1,4 @@ -try { . $PSScriptRoot\..\..\LoadPSD1.ps1 } catch { } +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $xlfile = "$env:TEMP\test.xlsx" Remove-Item $xlfile -ErrorAction SilentlyContinue diff --git a/Examples/Styles/NewExcelStyle.ps1 b/Examples/Styles/NewExcelStyle.ps1 index b5a3ddf..77286f0 100644 --- a/Examples/Styles/NewExcelStyle.ps1 +++ b/Examples/Styles/NewExcelStyle.ps1 @@ -1,5 +1,5 @@ # https://raw.githubusercontent.com/dfinke/ImportExcel/master/images/NewExcelStyle.png -try { . $PSScriptRoot\..\..\LoadPSD1.ps1 } catch { } +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $xlfile = "$env:TEMP\test.xlsx" Remove-Item $xlfile -ErrorAction SilentlyContinue diff --git a/Examples/Tables/MultipleTables.ps1 b/Examples/Tables/MultipleTables.ps1 index 03f8a89..d2c0188 100644 --- a/Examples/Tables/MultipleTables.ps1 +++ b/Examples/Tables/MultipleTables.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $xlfile = "$env:Temp\testData.xlsx" Remove-Item $xlfile -ErrorAction SilentlyContinue diff --git a/Examples/TestRestAPI/RunAndShowUnitTests.ps1 b/Examples/TestRestAPI/RunAndShowUnitTests.ps1 index 8a02b80..6f1bf44 100644 --- a/Examples/TestRestAPI/RunAndShowUnitTests.ps1 +++ b/Examples/TestRestAPI/RunAndShowUnitTests.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $xlfilename=".\test.xlsx" rm $xlfilename -ErrorAction Ignore diff --git a/Examples/TestRestAPI/TryIt.ps1 b/Examples/TestRestAPI/TryIt.ps1 index 66c0037..d6d6eae 100644 --- a/Examples/TestRestAPI/TryIt.ps1 +++ b/Examples/TestRestAPI/TryIt.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} . $PSScriptRoot\TestAPIReadXls.ps1 diff --git a/Examples/TryMultiplePivotTablesFromOneSheet.ps1 b/Examples/TryMultiplePivotTablesFromOneSheet.ps1 index 1533a78..eb76f8c 100644 --- a/Examples/TryMultiplePivotTablesFromOneSheet.ps1 +++ b/Examples/TryMultiplePivotTablesFromOneSheet.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $file = "C:\Temp\test.xlsx" diff --git a/Examples/XlRangeToImage/XlRangeToImage.ps1 b/Examples/XlRangeToImage/XlRangeToImage.ps1 index be7cfa2..de9fec5 100644 --- a/Examples/XlRangeToImage/XlRangeToImage.ps1 +++ b/Examples/XlRangeToImage/XlRangeToImage.ps1 @@ -1,4 +1,4 @@ -try {. $PSScriptRoot\..\..\LoadPSD1.ps1} catch {} +try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} . .\ConvertExcelToImageFile.ps1 diff --git a/LoadPSD1.ps1 b/LoadPSD1.ps1 deleted file mode 100644 index 68a9ec5..0000000 --- a/LoadPSD1.ps1 +++ /dev/null @@ -1,3 +0,0 @@ -if($null -eq (Get-Module -ListAvailable ImportExcel) ) { - Import-Module $PSScriptRoot\ImportExcel.psd1 -force -} \ No newline at end of file From 2e0cd4f97de16bb461eb2a53c21bfff1c2e07d13 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Wed, 20 Nov 2019 18:27:17 +0000 Subject: [PATCH 06/25] Linting --- ArgumentCompletion.ps1 | 2 + ExportedCommands/Compare-WorkSheet.ps1 | 8 +- .../Convert-ExcelRangeToImage.ps1 | 6 +- ExportedCommands/Expand-NumberFormat.ps1 | 2 +- .../Export-MultipleExcelSheets.ps1 | 2 + ExportedCommands/Get-ExcelColumnName.ps1 | 2 +- ExportedCommands/Import-Excel.ps1 | 207 +----------------- ExportedCommands/New-ExcelStyle.ps1 | 2 + InferData/InferData.ps1 | 3 +- InstallModule.ps1 | 14 +- 10 files changed, 30 insertions(+), 218 deletions(-) diff --git a/ArgumentCompletion.ps1 b/ArgumentCompletion.ps1 index 55823e0..b0268da 100644 --- a/ArgumentCompletion.ps1 +++ b/ArgumentCompletion.ps1 @@ -6,6 +6,8 @@ } function ListFonts { + [cmdletbinding()] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingEmptyCatchBlock", "")] param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) if (-not $script:FontFamilies) { $script:FontFamilies = @("","") diff --git a/ExportedCommands/Compare-WorkSheet.ps1 b/ExportedCommands/Compare-WorkSheet.ps1 index 8d478ed..6f5bf64 100644 --- a/ExportedCommands/Compare-WorkSheet.ps1 +++ b/ExportedCommands/Compare-WorkSheet.ps1 @@ -88,13 +88,13 @@ $ws = $xl.Workbook.Worksheets[$_] if ($headerName) {$range = "A" + $startrow + ":" + $ws.dimension.end.address} else {$range = "A" + ($startrow + 1) + ":" + $ws.dimension.end.address} - Set-Format -WorkSheet $ws -BackgroundColor $AllDataBackgroundColor -Range $Range + Set-ExcelRange -WorkSheet $ws -BackgroundColor $AllDataBackgroundColor -Range $Range } } foreach ($row in $file.group) { $ws = $xl.Workbook.Worksheets[$row._Sheet] $range = $ws.Dimension -replace "\d+",$row._row - Set-Format -WorkSheet $ws -Range $range -BackgroundColor $BackgroundColor + Set-ExcelRange -WorkSheet $ws -Range $range -BackgroundColor $BackgroundColor } if ($PSBoundParameters.ContainsKey("TabColor")) { if ($TabColor -is [string]) {$TabColor = [System.Drawing.Color]::$TabColor } @@ -123,8 +123,8 @@ $ws2 = $xl1.Workbook.Worksheets[$u.Group[1]._sheet] } if($u.Group[0].$p -ne $u.Group[1].$p ) { - Set-Format -WorkSheet $ws1 -Range ($Columns[$p] + $u.Group[0]._Row) -FontColor $FontColor - Set-Format -WorkSheet $ws2 -Range ($Columns[$p] + $u.Group[1]._Row) -FontColor $FontColor + Set-ExcelRange -WorkSheet $ws1 -Range ($Columns[$p] + $u.Group[0]._Row) -FontColor $FontColor + Set-ExcelRange -WorkSheet $ws2 -Range ($Columns[$p] + $u.Group[1]._Row) -FontColor $FontColor } } } diff --git a/ExportedCommands/Convert-ExcelRangeToImage.ps1 b/ExportedCommands/Convert-ExcelRangeToImage.ps1 index 988a931..affca6a 100644 --- a/ExportedCommands/Convert-ExcelRangeToImage.ps1 +++ b/ExportedCommands/Convert-ExcelRangeToImage.ps1 @@ -43,9 +43,9 @@ $myData = Get-Process | Select-Object -Property Name,WS,CPU,Description,c $excelPackage = $myData | Export-Excel -KillExcel -Path $Path -WorkSheetname $workSheetname -ClearSheet -AutoSize -AutoFilter -BoldTopRow -FreezeTopRow -PassThru $workSheet = $excelPackage.Workbook.Worksheets[$workSheetname] $range = $workSheet.Dimension.Address -Set-Format -WorkSheet $workSheet -Range "b:b" -NumberFormat "#,###" -AutoFit -Set-Format -WorkSheet $workSheet -Range "C:C" -NumberFormat "#,##0.00" -AutoFit -Set-Format -WorkSheet $workSheet -Range "F:F" -NumberFormat "dd MMMM HH:mm:ss" -AutoFit +Set-ExcelRange -WorkSheet $workSheet -Range "b:b" -NumberFormat "#,###" -AutoFit +Set-ExcelRange -WorkSheet $workSheet -Range "C:C" -NumberFormat "#,##0.00" -AutoFit +Set-ExcelRange -WorkSheet $workSheet -Range "F:F" -NumberFormat "dd MMMM HH:mm:ss" -AutoFit Add-ConditionalFormatting -WorkSheet $workSheet -Range "c2:c1000" -DataBarColor Blue Add-ConditionalFormatting -WorkSheet $workSheet -Range "b2:B1000" -RuleType GreaterThan -ConditionValue '104857600' -ForeGroundColor "Red" -Bold diff --git a/ExportedCommands/Expand-NumberFormat.ps1 b/ExportedCommands/Expand-NumberFormat.ps1 index 2027f47..cbefdbb 100644 --- a/ExportedCommands/Expand-NumberFormat.ps1 +++ b/ExportedCommands/Expand-NumberFormat.ps1 @@ -1,4 +1,4 @@ - + function Expand-NumberFormat { <# .SYNOPSIS diff --git a/ExportedCommands/Export-MultipleExcelSheets.ps1 b/ExportedCommands/Export-MultipleExcelSheets.ps1 index 378ceb8..d8012e2 100644 --- a/ExportedCommands/Export-MultipleExcelSheets.ps1 +++ b/ExportedCommands/Export-MultipleExcelSheets.ps1 @@ -1,5 +1,7 @@ function Export-MultipleExcelSheets { [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification="No suitable singular")] + param( [Parameter(Mandatory = $true)] $Path, diff --git a/ExportedCommands/Get-ExcelColumnName.ps1 b/ExportedCommands/Get-ExcelColumnName.ps1 index a71ef10..d2f6a86 100644 --- a/ExportedCommands/Get-ExcelColumnName.ps1 +++ b/ExportedCommands/Get-ExcelColumnName.ps1 @@ -7,7 +7,7 @@ function Get-ExcelColumnName { Process { $dividend = $columnNumber $columnName = New-Object System.Collections.ArrayList($null) - + while($dividend -gt 0) { $modulo = ($dividend - 1) % 26 if ($columnName.length -eq 0) { diff --git a/ExportedCommands/Import-Excel.ps1 b/ExportedCommands/Import-Excel.ps1 index 0eae2e3..7f5c5a9 100644 --- a/ExportedCommands/Import-Excel.ps1 +++ b/ExportedCommands/Import-Excel.ps1 @@ -1,211 +1,8 @@ - -function Import-Excel { - <# - .SYNOPSIS - Create custom objects from the rows in an Excel worksheet. - - .DESCRIPTION - The Import-Excel cmdlet creates custom objects from the rows in an Excel worksheet. Each row represents one object. All of this is possible without installing Microsoft Excel and by using the .NET library ‘EPPLus.dll’. - - By default, the property names of the objects are retrieved from the column headers. Because an object cannot have a blank property name, only columns with column headers will be imported. - - If the default behavior is not desired and you want to import the complete worksheet ‘as is’, the parameter ‘-NoHeader’ can be used. In case you want to provide your own property names, you can use the parameter ‘-HeaderName’. - - .PARAMETER Path - Specifies the path to the Excel file. - .PARAMETER ExcelPackage - Instead of specifying a path provides an Excel Package object (from Open-ExcelPackage) - Using this avoids re-reading the whole file when importing multiple parts of it. - To allow multiple read operations Import-Excel does NOT close the package, and you should use - Close-ExcelPackage -noSave to close it. - .PARAMETER WorksheetName - Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported. - - .PARAMETER DataOnly - Import only rows and columns that contain data, empty rows and empty columns are not imported. - - .PARAMETER HeaderName - Specifies custom property names to use, instead of the values defined in the column headers of the TopRow. - If you provide fewer header names than there are columns of data in the worksheet, then data will only be imported from that number of columns - the others will be ignored. - If you provide more header names than there are columns of data in the worksheet, it will result in blank properties being added to the objects returned. - - .PARAMETER NoHeader - Automatically generate property names (P1, P2, P3, ..) instead of the ones defined in the column headers of the TopRow. - This switch is best used when you want to import the complete worksheet ‘as is’ and are not concerned with the property names. - - .PARAMETER StartRow - The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row. - When the parameters ‘-NoHeader’ and ‘-HeaderName’ are not provided, this row will contain the column headers that will be used as property names. When one of both parameters are provided, the property names are automatically created and this row will be treated as a regular row containing data. - - .PARAMETER EndRow - By default all rows up to the last cell in the sheet will be imported. If specified, import stops at this row. - - .PARAMETER StartColumn - The number of the first column to read data from (1 by default). - - .PARAMETER EndColumn - By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number. - - .PARAMETER AsText - Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. * is supported as a wildcard. - - .PARAMETER Password - Accepts a string that will be used to open a password protected Excel file. - - .EXAMPLE - 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. - - ---------------------------------------------- - | 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 - - 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 - Import 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, ..). - - ---------------------------------------------- - | 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 -NoHeader - - P1: First Name - P2: - P3: Address - - P1: Chuck - P2: Norris - P3: California - - P1: Jean-Claude - P2: Vandamme - P3: Brussels - - Notice that the column header (row 1) is imported as an object too. - - .EXAMPLE - Import data from an Excel worksheet. One object is created for each row. The property names of the objects consist of the names 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. - - ---------------------------------------------------------- - | 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 C:\> 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 : - - 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 blanc for all objects. - - .EXAMPLE - Import data from an Excel worksheet. One object is created for each row. The property names of the objects are automatically generated by using the switch ‘-NoHeader’ (P1, P@, P#, ..). The switch ‘-DataOnly’ will speed up the import because empty rows and empty columns are not imported. - - ---------------------------------------------------------- - | 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 C:\> 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 - - Notice that empty rows and empty columns are not imported. - - .EXAMPLE - 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. - - ---------------------------------------------------------- - | File: Movies.xlsx - Sheet: Actors | - ---------------------------------------------------------- - | A B C D | - |1 Chuck Norris California | - |2 | - |3 Jean-Claude Vandamme Brussels | - ---------------------------------------------------------- - - PS C:\> Import-Excel -Path 'C:\Movies.xlsx' -WorkSheetname Actors -DataOnly -HeaderName 'FirstName', 'SecondName', 'City' –StartRow 2 - - FirstName : Jean-Claude - SecondName: Vandamme - City : Brussels - - 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 - > - 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 pipe the data to the Write-SqlTableData 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. - - .LINK - https://github.com/dfinke/ImportExcel - - .NOTES - #> +function Import-Excel { [CmdLetBinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSPossibleIncorrectUsageOfAssignmentOperator', '', Justification = 'Intentional')] Param ( [Alias('FullName')] [Parameter(ParameterSetName = "PathA", Mandatory, ValueFromPipelineByPropertyName, ValueFromPipeline, Position = 0 )] diff --git a/ExportedCommands/New-ExcelStyle.ps1 b/ExportedCommands/New-ExcelStyle.ps1 index f15b48f..a88d122 100644 --- a/ExportedCommands/New-ExcelStyle.ps1 +++ b/ExportedCommands/New-ExcelStyle.ps1 @@ -1,4 +1,6 @@ function New-ExcelStyle { + [cmdletbinding()] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Does not change system State')] param ( [Alias("Address")] $Range , diff --git a/InferData/InferData.ps1 b/InferData/InferData.ps1 index 8badcfc..06bf3df 100644 --- a/InferData/InferData.ps1 +++ b/InferData/InferData.ps1 @@ -60,7 +60,8 @@ $tests = [ordered]@{ TestString = Get-Command Test-String } -function Invoke-AllTests { +function Invoke-TestSet { + [alias("Invoke-AllTests")] param( $target, [Switch]$OnlyPassing, diff --git a/InstallModule.ps1 b/InstallModule.ps1 index d217c5f..ac08d1e 100644 --- a/InstallModule.ps1 +++ b/InstallModule.ps1 @@ -1,3 +1,11 @@ -$fullPath = 'C:\Program Files\WindowsPowerShell\Modules\ImportExcel' - -Robocopy . $fullPath /mir /XD .vscode .git examples data /XF appveyor.yml azure-pipelines.yml .gitattributes .gitignore \ No newline at end of file +param ($fullPath) +#$fullPath = 'C:\Program Files\WindowsPowerShell\Modules\ImportExcel' +if (-not $fullPath) { + $fullpath = $env:PSModulePath -split ":(?!\\)|;|," | + Where-Object {$_ -notlike ([System.Environment]::GetFolderPath("UserProfile")+"*") -and $_ -notlike "$pshome*"} | + Select-Object -First 1 + $fullPath = Join-Path $fullPath -ChildPath "ImportExcel" +} +Push-location $PSScriptRoot +Robocopy . $fullPath /mir /XD .vscode .git CI __tests__ data mdHelp /XF appveyor.yml azure-pipelines.yml .gitattributes .gitignore filelist.txt install.ps1 InstallModule.ps1 +Pop-Location \ No newline at end of file From aaf18b4d9acd7f8d00bafa7dd671b9319682a924 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Wed, 20 Nov 2019 19:07:22 +0000 Subject: [PATCH 07/25] Linting mostly --- __tests__/ImportExcelFileList.tests.ps1 | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 __tests__/ImportExcelFileList.tests.ps1 diff --git a/__tests__/ImportExcelFileList.tests.ps1 b/__tests__/ImportExcelFileList.tests.ps1 deleted file mode 100644 index 3428b00..0000000 --- a/__tests__/ImportExcelFileList.tests.ps1 +++ /dev/null @@ -1,10 +0,0 @@ -Describe "ImportExcel File List" { - It "All files should exist".PadRight(90) { - $fileList = Get-Content "$PSScriptRoot\..\filelist.txt" - - foreach ($file in $fileList) { - $targetFile = "$PSScriptRoot\..\$file" - Test-Path $targetFile | Should Be $true - } - } -} \ No newline at end of file From 5fee49967adae47fc0daedd66ca56ca26a647921 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Thu, 21 Nov 2019 08:42:51 +0000 Subject: [PATCH 08/25] sync export with master updtes for #720 --- ExportedCommands/Export-Excel.ps1 | 51 ++++++++++++++++++++----------- 1 file changed, 33 insertions(+), 18 deletions(-) diff --git a/ExportedCommands/Export-Excel.ps1 b/ExportedCommands/Export-Excel.ps1 index 0c5cfa3..0ab635f 100644 --- a/ExportedCommands/Export-Excel.ps1 +++ b/ExportedCommands/Export-Excel.ps1 @@ -153,8 +153,10 @@ } #if we did not get a table name but there is a table which covers the active part of the sheet, set table name to that, and don't do anything with autofilter - if ($null -eq $TableName -and $ws.Tables.Where({$_.address.address -eq $ws.dimension.address})) { - $TableName = $ws.Tables.Where({$_.address.address -eq $ws.dimension.address},'First', 1).Name + $existingTable = $ws.Tables.Where({$_.address.address -eq $ws.dimension.address},'First', 1) + if ($null -eq $TableName -and $existingTable) { + $TableName = $existingTable.Name + $TableStyle = $existingTable.Tablestyle $AutoFilter = $false } #if we did not get $autofilter but a filter range is set and it covers the right area, set autofilter to true @@ -197,28 +199,41 @@ else { $setNumformat = ($Numberformat -ne $ws.Cells.Style.Numberformat.Format) } } catch {throw "Failed preparing to export to worksheet '$WorksheetName' to '$Path': $_"} - #region Special case -inputobject passed a dataTable object + #region Special case -inputobject passed a dataTable object <# If inputObject was passed via the pipeline it won't be visible until the process block, we will only see it here if it was passed as a parameter if it is a data table don't do foreach on it (slow) - put the whole table in and set dates on date columns, set things up for the end block, and skip the process block #> if ($InputObject -is [System.Data.DataTable]) { - #Change TableName if $TableName is non-empty; don't leave caller with a renamed table! - $orginalTableName = $InputObject.TableName - if ($TableName) { - $InputObject.TableName = $TableName + if ($Append) { + $row ++ + $null = $ws.Cells[$row,$StartColumn].LoadFromDataTable($InputObject, $false ) + if ($TableName) { + Add-ExcelTable -Range $ws.Cells[$ws.Dimension] -TableName $TableName -TableStyle $TableStyle + } } - while ($InputObject.TableName -in $pkg.Workbook.Worksheets.Tables.name) { - Write-Warning "Table name $($InputObject.TableName) is not unique, adding '_' to it " - $InputObject.TableName += "_" + else { + #Change TableName if $TableName is non-empty; don't leave caller with a renamed table! + $orginalTableName = $InputObject.TableName + if ($PSBoundParameters.ContainsKey("TableName")) { + $InputObject.TableName = $TableName + } + while ($InputObject.TableName -in $pkg.Workbook.Worksheets.Tables.name) { + Write-Warning "Table name $($InputObject.TableName) is not unique, adding '_' to it " + $InputObject.TableName += "_" + } + #Insert as a table, if Tablestyle didn't arrive as a default, or $TableName non-null - even if empty + if ($null -ne $TableName -or $PSBoundParameters.ContainsKey("TableStyle")) { + $null = $ws.Cells[$row,$StartColumn].LoadFromDataTable($InputObject, (-not $noHeader),$TableStyle ) + # Workaround for EPPlus not marking the empty row on an empty table as dummy row. + if ($InputObject.Rows.Count -eq 0) { + ($ws.Tables | Select-Object -Last 1).TableXml.table.SetAttribute('insertRow', 1) + } + } + else { + $null = $ws.Cells[$row,$StartColumn].LoadFromDataTable($InputObject, (-not $noHeader) ) + } + $InputObject.TableName = $orginalTableName } - #Insert as a table, if Tablestyle didn't arrive as a default, or $TableName non-null - even if empty - if ($null -ne $TableName -or $PSBoundParameters.ContainsKey("TableStyle")) { - $null = $ws.Cells[$row,$StartColumn].LoadFromDataTable($InputObject, (-not $noHeader),$TableStyle ) - } - else { - $null = $ws.Cells[$row,$StartColumn].LoadFromDataTable($InputObject, (-not $noHeader) ) - } - $InputObject.TableName = $orginalTableName foreach ($c in $InputObject.Columns.where({$_.datatype -eq [datetime]})) { Set-ExcelColumn -Worksheet $ws -Column ($c.Ordinal + $StartColumn) -NumberFormat 'Date-Time' } From e42f23cd7cf2fa4747d195f9e8ce4eea268430ac Mon Sep 17 00:00:00 2001 From: jhoneill Date: Thu, 21 Nov 2019 17:29:58 +0000 Subject: [PATCH 09/25] Major linting push --- Examples/AddWorkSheet/AddMultiWorkSheet.ps1 | 8 +-- Examples/Charts/plot.ps1 | 2 +- .../ConditionalFormatting/CodeGenExamples.ps1 | 4 +- .../ConditionalFormatting/ContainsBlanks.ps1 | 2 +- Examples/ConditionalFormatting/Databar.ps1 | 16 +++--- .../FormatCalculations.ps1 | 2 +- Examples/ConditionalFormatting/GenDates.ps1 | 4 +- .../HighlightDuplicates.ps1 | 2 +- .../ConditionalFormatting/RangeFormatting.ps1 | 2 +- .../SalesReportWithDatabar.ps1 | 4 +- .../ConditionalFormatting/TextComparisons.ps1 | 8 +-- Examples/CustomReporting/CustomReport.ps1 | 52 +++++++++---------- .../FormatCellStyles/PassInScriptBlock.ps1 | 2 +- .../GenerateData/GenDataForCustomReport.ps1 | 14 ++--- .../Join-worksheet-blocks.sample.ps1 | 2 +- Examples/JustCharts/TargetData.ps1 | 2 +- .../MortgageCalculator/MortgageCalculator.ps1 | 23 ++++---- Examples/Nasa/FireBalls.ps1 | 21 ++++---- Examples/New-PSItem.ps1 | 3 +- Examples/OutTabulator/start-demo.ps1 | 50 +++++++++--------- Examples/PivotTable/MultiplePivotTables.ps1 | 10 ++-- Examples/ReadAllSheets/Get-ExcelSheets.ps1 | 8 +-- Examples/ReadAllSheets/ReadAllSheets.ps1 | 4 +- Examples/SQL+FillColumns+Pivot/Example.ps1 | 20 +++---- Examples/SQL+FillColumns+Pivot/Example2.ps1 | 2 +- Examples/Sparklines/SalesByQuarter.ps1 | 2 +- Examples/Sparklines/Sparklines.ps1 | 12 ++--- .../SpreadsheetCells/CalculatedFields.ps1 | 2 +- Examples/SpreadsheetCells/ExcelFunctions.ps1 | 2 +- Examples/Stocks/Get-StockInfo.ps1 | 5 +- Examples/TestRestAPI/RunAndShowUnitTests.ps1 | 10 ++-- Examples/TestRestAPI/ShowPesterResults.ps1 | 2 + Examples/TestRestAPI/TestAPIReadXls.ps1 | 1 + Examples/TryMultiplePivotTables.ps1 | 12 ++--- Examples/VBA/HelloWorldVBA.ps1 | 4 +- __tests__/Compare-WorkSheet.tests.ps1 | 2 + __tests__/Copy-ExcelWorksheet.Tests.ps1 | 9 ++-- __tests__/Export-Excel.Tests.ps1 | 12 +++-- __tests__/First10Races.tests.ps1 | 4 +- __tests__/ImportExcelHeaderName.tests.ps1 | 42 +++++++-------- __tests__/ImportExcelTests/Simple.tests.ps1 | 4 +- __tests__/InputItemParameter.tests.ps1 | 2 + __tests__/Join-Worksheet.tests.ps1 | 4 +- __tests__/RangePassing.ps1 | 2 + .../Set-Row_Set-Column-SetFormat.tests.ps1 | 5 ++ __tests__/Validation.tests.ps1 | 2 + spikes/ConvertFrom-ExcelColumnName.ps1 | 2 +- 47 files changed, 219 insertions(+), 190 deletions(-) diff --git a/Examples/AddWorkSheet/AddMultiWorkSheet.ps1 b/Examples/AddWorkSheet/AddMultiWorkSheet.ps1 index 6318980..b16a91b 100644 --- a/Examples/AddWorkSheet/AddMultiWorkSheet.ps1 +++ b/Examples/AddWorkSheet/AddMultiWorkSheet.ps1 @@ -1,15 +1,15 @@ try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $xlSourcefile = "$env:TEMP\Source.xlsx" -write-host "Save location: $xlSourcefile" +Write-Verbose -Verbose -Message "Save location: $xlSourcefile" Remove-Item $xlSourcefile -ErrorAction Ignore #Put some simple data in a worksheet and Get an excel package object to represent the file -$TabData1 = 1..5 | Export-Excel $xlSourcefile -WorksheetName 'Tab1' -AutoSize -AutoFilter +1..5 | Export-Excel $xlSourcefile -WorksheetName 'Tab1' -AutoSize -AutoFilter #Add another tab. Replace the $TabData2 with your data -$TabData2 = 1..10 | Export-Excel $xlSourcefile -WorksheetName 'Tab 2' -AutoSize -AutoFilter +1..10 | Export-Excel $xlSourcefile -WorksheetName 'Tab 2' -AutoSize -AutoFilter #Add another tab. Replace the $TabData3 with your data -$TabData3 = 1..15 | Export-Excel $xlSourcefile -WorksheetName 'Tab 3' -AutoSize -AutoFilter -Show +1..15 | Export-Excel $xlSourcefile -WorksheetName 'Tab 3' -AutoSize -AutoFilter -Show diff --git a/Examples/Charts/plot.ps1 b/Examples/Charts/plot.ps1 index c311fe9..839a816 100644 --- a/Examples/Charts/plot.ps1 +++ b/Examples/Charts/plot.ps1 @@ -25,4 +25,4 @@ function plot { function pi {[math]::pi} -plot {[math]::Tan($args[0])} (pi) (3*(pi)/2-.01) \ No newline at end of file +plot -f {[math]::Tan($args[0])} -minx (pi) -maxx (3*(pi)/2-.01) \ No newline at end of file diff --git a/Examples/ConditionalFormatting/CodeGenExamples.ps1 b/Examples/ConditionalFormatting/CodeGenExamples.ps1 index 861bc66..2927d4a 100644 --- a/Examples/ConditionalFormatting/CodeGenExamples.ps1 +++ b/Examples/ConditionalFormatting/CodeGenExamples.ps1 @@ -1,9 +1,9 @@ -echo Last7Days LastMonth LastWeek NextMonth NextWeek ThisMonth ThisWeek Today Tomorrow Yesterday | +"Last7Days", "LastMonth", "LastWeek", "NextMonth", "NextWeek", "ThisMonth", "ThisWeek", "Today", "Tomorrow", "Yesterday" | Foreach-Object { $text = @" `$f = ".\testExport.xlsx" -rm `$f -ErrorAction Ignore +remove-item `$f -ErrorAction Ignore .\GenDates.ps1 | Export-Excel `$f -Show -AutoSize -ConditionalText `$( diff --git a/Examples/ConditionalFormatting/ContainsBlanks.ps1 b/Examples/ConditionalFormatting/ContainsBlanks.ps1 index 3ced09a..bbbde4b 100644 --- a/Examples/ConditionalFormatting/ContainsBlanks.ps1 +++ b/Examples/ConditionalFormatting/ContainsBlanks.ps1 @@ -4,7 +4,7 @@ try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $ContainsBlanks = New-ConditionalText -ConditionalType ContainsBlanks $data = $( - New-PSItem a b c (echo p1 p2 p3) + New-PSItem a b c @('p1', 'p2', 'p3') New-PSItem New-PSItem d e f New-PSItem diff --git a/Examples/ConditionalFormatting/Databar.ps1 b/Examples/ConditionalFormatting/Databar.ps1 index d117244..951330f 100644 --- a/Examples/ConditionalFormatting/Databar.ps1 +++ b/Examples/ConditionalFormatting/Databar.ps1 @@ -10,23 +10,23 @@ $excel = Get-Process | $sheet = $excel.Workbook.Worksheets["Processes"] -#Apply fixed formatting to columns. Set-Format is an Alias for Set-Excel Range, -NFormat is an alias for numberformat +#Apply fixed formatting to columns. -NFormat is an alias for numberformat $sheet.Column(1) | Set-ExcelRange -Bold -AutoFit -$sheet.Column(2) | Set-Format -Width 29 -WrapText -$sheet.Column(3) | Set-Format -HorizontalAlignment Right -NFormat "#,###" +$sheet.Column(2) | Set-ExcelRange -Width 29 -WrapText +$sheet.Column(3) | Set-ExcelRange -HorizontalAlignment Right -NFormat "#,###" Set-ExcelRange -Range -Address $sheet.Cells["E1:H1048576"] -HorizontalAlignment Right -NFormat "#,###" -#Set-Format is an alias for Set-ExcelRange -Set-Format -Range $sheet.Column(4) -HorizontalAlignment Right -NFormat "#,##0.0" -Bold -#In Set-ExcelRange / Set-Format "-Address" is an alias for "-Range" -Set-Format -Address $sheet.Row(1) -Bold -HorizontalAlignment Center + +Set-ExcelRange -Range $sheet.Column(4) -HorizontalAlignment Right -NFormat "#,##0.0" -Bold +#In Set-ExcelRange "-Address" is an alias for "-Range" +Set-ExcelRange -Address $sheet.Row(1) -Bold -HorizontalAlignment Center #Create a Red Data-bar for the values in Column D Add-ConditionalFormatting -WorkSheet $sheet -Address "D2:D1048576" -DataBarColor Red # Conditional formatting applies to "Addreses" aliases allow either "Range" or "Address" to be used in Set-ExcelRange or Add-Conditional formatting. Add-ConditionalFormatting -WorkSheet $sheet -Range "G2:G1048576" -RuleType GreaterThan -ConditionValue "104857600" -ForeGroundColor Red -foreach ($c in 5..9) {Set-Format -Address $sheet.Column($c) -AutoFit } +foreach ($c in 5..9) {Set-ExcelRange -Address $sheet.Column($c) -AutoFit } #Create a pivot and save the file. Export-Excel -ExcelPackage $excel -WorkSheetname "Processes" -IncludePivotChart -ChartType ColumnClustered -NoLegend -PivotRows company -PivotData @{'Name'='Count'} -Show \ No newline at end of file diff --git a/Examples/ConditionalFormatting/FormatCalculations.ps1 b/Examples/ConditionalFormatting/FormatCalculations.ps1 index f343b0c..3c77b6c 100644 --- a/Examples/ConditionalFormatting/FormatCalculations.ps1 +++ b/Examples/ConditionalFormatting/FormatCalculations.ps1 @@ -6,7 +6,7 @@ Remove-Item $f -ErrorAction Ignore $data = $( - New-PSItem North 111 (echo Region Amount ) + New-PSItem North 111 @( 'Region', 'Amount' ) New-PSItem East 111 New-PSItem West 122 New-PSItem South 200 diff --git a/Examples/ConditionalFormatting/GenDates.ps1 b/Examples/ConditionalFormatting/GenDates.ps1 index 5a9a994..6a32e36 100644 --- a/Examples/ConditionalFormatting/GenDates.ps1 +++ b/Examples/ConditionalFormatting/GenDates.ps1 @@ -1,6 +1,6 @@ function Get-DateOffset { param($days=0) - + (Get-Date).AddDays($days).ToShortDateString() } @@ -8,7 +8,7 @@ function Get-Number { Get-Random -Minimum 10 -Maximum 100 } -New-PSItem (Get-DateOffset -7) (Get-Number) 'LastWeek,Last7Days,ThisMonth' (echo Date Amount Label) +New-PSItem (Get-DateOffset -7) (Get-Number) 'LastWeek,Last7Days,ThisMonth' @('Date', 'Amount', 'Label') New-PSItem (Get-DateOffset) (Get-Number) 'Today,ThisMonth,ThisWeek' New-PSItem (Get-DateOffset -30) (Get-Number) LastMonth New-PSItem (Get-DateOffset -1) (Get-Number) 'Yesterday,ThisMonth,ThisWeek' diff --git a/Examples/ConditionalFormatting/HighlightDuplicates.ps1 b/Examples/ConditionalFormatting/HighlightDuplicates.ps1 index 66d71c0..58bd4c3 100644 --- a/Examples/ConditionalFormatting/HighlightDuplicates.ps1 +++ b/Examples/ConditionalFormatting/HighlightDuplicates.ps1 @@ -6,7 +6,7 @@ Remove-Item $f -ErrorAction Ignore $data = $( - New-PSItem North 111 (echo Region Amount ) + New-PSItem North 111 @('Region', 'Amount' ) New-PSItem East 11 New-PSItem West 12 New-PSItem South 1000 diff --git a/Examples/ConditionalFormatting/RangeFormatting.ps1 b/Examples/ConditionalFormatting/RangeFormatting.ps1 index aeee56b..05c65b4 100644 --- a/Examples/ConditionalFormatting/RangeFormatting.ps1 +++ b/Examples/ConditionalFormatting/RangeFormatting.ps1 @@ -8,7 +8,7 @@ function Get-DateOffset ($days=0) { } $( - New-PSItem (Get-DateOffset -1) (Get-DateOffset 1) (echo Start End) + New-PSItem (Get-DateOffset -1) (Get-DateOffset 1) @("Start", "End") New-PSItem (Get-DateOffset) (Get-DateOffset 7) New-PSItem (Get-DateOffset -10) (Get-DateOffset -1) ) | diff --git a/Examples/ConditionalFormatting/SalesReportWithDatabar.ps1 b/Examples/ConditionalFormatting/SalesReportWithDatabar.ps1 index a36e444..4870766 100644 --- a/Examples/ConditionalFormatting/SalesReportWithDatabar.ps1 +++ b/Examples/ConditionalFormatting/SalesReportWithDatabar.ps1 @@ -16,7 +16,7 @@ Jun,621 $sheet = $excel.Workbook.Worksheets["Sheet1"] Add-ConditionalFormatting -WorkSheet $sheet -Range "B1:B7" -DataBarColor LawnGreen -Set-Format -Address $sheet.Cells["A8"] -Value "Total" -Set-Format -Address $sheet.Cells["B8"] -Formula "=Sum(Sales)" +Set-ExcelRange -Address $sheet.Cells["A8"] -Value "Total" +Set-ExcelRange -Address $sheet.Cells["B8"] -Formula "=Sum(Sales)" Close-ExcelPackage $excel -Show \ No newline at end of file diff --git a/Examples/ConditionalFormatting/TextComparisons.ps1 b/Examples/ConditionalFormatting/TextComparisons.ps1 index 0a759bd..729f38f 100644 --- a/Examples/ConditionalFormatting/TextComparisons.ps1 +++ b/Examples/ConditionalFormatting/TextComparisons.ps1 @@ -1,7 +1,7 @@ -try {ipmo ..\..\ImportExcel.psd1 -Force} catch {} +try {Import-Module ..\..\ImportExcel.psd1 -Force} catch {throw ; return} $data = $( - New-PSItem 100 (echo test testx) + New-PSItem 100 @('test', 'testx') New-PSItem 200 New-PSItem 300 New-PSItem 400 @@ -11,8 +11,8 @@ $data = $( $file1 = "$env:Temp\tryComparison1.xlsx" $file2 = "$env:Temp\tryComparison2.xlsx" -rm $file1 -ErrorAction Ignore -rm $file2 -ErrorAction Ignore +Remove-Item -Path $file1 -ErrorAction Ignore +Remove-Item -Path $file2 -ErrorAction Ignore $data | Export-Excel $file1 -Show -ConditionalText $( New-ConditionalText -ConditionalType GreaterThan 300 diff --git a/Examples/CustomReporting/CustomReport.ps1 b/Examples/CustomReporting/CustomReport.ps1 index 35c8e9f..58dffb4 100644 --- a/Examples/CustomReporting/CustomReport.ps1 +++ b/Examples/CustomReporting/CustomReport.ps1 @@ -22,51 +22,51 @@ $sheet1 = $excel.Workbook.Worksheets["sheet1"] $sheet1.View.ShowGridLines = $false $sheet1.View.ShowHeaders = $false -Set-Format -Address $sheet1.Cells["C:C"] -NumberFormat "$#,##0" -WrapText -HorizontalAlignment Center -Set-Format -Address $sheet1.Cells["D:D"] -NumberFormat "#.#0%" -WrapText -HorizontalAlignment Center +Set-ExcelRange -Address $sheet1.Cells["C:C"] -NumberFormat "$#,##0" -WrapText -HorizontalAlignment Center +Set-ExcelRange -Address $sheet1.Cells["D:D"] -NumberFormat "#.#0%" -WrapText -HorizontalAlignment Center -Set-Format -Address $sheet1.Cells["E:E"] -NumberFormat "$#,##0" -WrapText -HorizontalAlignment Center -Set-Format -Address $sheet1.Cells["F:F"] -NumberFormat "#.#0%" -WrapText -HorizontalAlignment Center +Set-ExcelRange -Address $sheet1.Cells["E:E"] -NumberFormat "$#,##0" -WrapText -HorizontalAlignment Center +Set-ExcelRange -Address $sheet1.Cells["F:F"] -NumberFormat "#.#0%" -WrapText -HorizontalAlignment Center -Set-Format -Address $sheet1.Cells["G:H"] -WrapText -HorizontalAlignment Center +Set-ExcelRange -Address $sheet1.Cells["G:H"] -WrapText -HorizontalAlignment Center ## Insert Rows/Columns $sheet1.InsertRow(1, 1) -foreach ($col in Write-Output 2 4 6 8 10 12 14) { +foreach ($col in @(2, 4, 6, 8, 10, 12, 14)) { $sheet1.InsertColumn($col, 1) $sheet1.Column($col).width = .75 } -Set-Format -Address $sheet1.Cells["E:E"] -Width 12 -Set-Format -Address $sheet1.Cells["I:I"] -Width 12 +Set-ExcelRange -Address $sheet1.Cells["E:E"] -Width 12 +Set-ExcelRange -Address $sheet1.Cells["I:I"] -Width 12 $BorderBottom = "Thick" $BorderColor = "Black" -Set-Format -Address $sheet1.Cells["A2"] -BorderBottom $BorderBottom -BorderColor $BorderColor +Set-ExcelRange -Address $sheet1.Cells["A2"] -BorderBottom $BorderBottom -BorderColor $BorderColor -Set-Format -Address $sheet1.Cells["C2"] -BorderBottom $BorderBottom -BorderColor $BorderColor -Set-Format -Address $sheet1.Cells["E2:G2"] -BorderBottom $BorderBottom -BorderColor $BorderColor -Set-Format -Address $sheet1.Cells["I2:K2"] -BorderBottom $BorderBottom -BorderColor $BorderColor -Set-Format -Address $sheet1.Cells["M2:O2"] -BorderBottom $BorderBottom -BorderColor $BorderColor +Set-ExcelRange -Address $sheet1.Cells["C2"] -BorderBottom $BorderBottom -BorderColor $BorderColor +Set-ExcelRange -Address $sheet1.Cells["E2:G2"] -BorderBottom $BorderBottom -BorderColor $BorderColor +Set-ExcelRange -Address $sheet1.Cells["I2:K2"] -BorderBottom $BorderBottom -BorderColor $BorderColor +Set-ExcelRange -Address $sheet1.Cells["M2:O2"] -BorderBottom $BorderBottom -BorderColor $BorderColor -Set-Format -Address $sheet1.Cells["A2:C8"] -FontColor Gray +Set-ExcelRange -Address $sheet1.Cells["A2:C8"] -FontColor Gray $HorizontalAlignment = "Center" -Set-Format -Address $sheet1.Cells["F1"] -HorizontalAlignment $HorizontalAlignment -Bold -Value Revenue -Set-Format -Address $sheet1.Cells["J1"] -HorizontalAlignment $HorizontalAlignment -Bold -Value Margin -Set-Format -Address $sheet1.Cells["N1"] -HorizontalAlignment $HorizontalAlignment -Bold -Value Passenger +Set-ExcelRange -Address $sheet1.Cells["F1"] -HorizontalAlignment $HorizontalAlignment -Bold -Value Revenue +Set-ExcelRange -Address $sheet1.Cells["J1"] -HorizontalAlignment $HorizontalAlignment -Bold -Value Margin +Set-ExcelRange -Address $sheet1.Cells["N1"] -HorizontalAlignment $HorizontalAlignment -Bold -Value Passenger -Set-Format -Address $sheet1.Cells["E2"] -Value '($)' -Set-Format -Address $sheet1.Cells["G2"] -Value '%' -Set-Format -Address $sheet1.Cells["I2"] -Value '($)' -Set-Format -Address $sheet1.Cells["K2"] -Value '%' +Set-ExcelRange -Address $sheet1.Cells["E2"] -Value '($)' +Set-ExcelRange -Address $sheet1.Cells["G2"] -Value '%' +Set-ExcelRange -Address $sheet1.Cells["I2"] -Value '($)' +Set-ExcelRange -Address $sheet1.Cells["K2"] -Value '%' -Set-Format -Address $sheet1.Cells["C10"] -HorizontalAlignment Right -Bold -Value "Grand Total Calculation" -Set-Format -Address $sheet1.Cells["E10"] -Formula "=Sum(E3:E8)" -Bold -Set-Format -Address $sheet1.Cells["I10"] -Formula "=Sum(I3:I8)" -Bold -Set-Format -Address $sheet1.Cells["M10"] -Formula "=Sum(M3:M8)" -Bold -Set-Format -Address $sheet1.Cells["O10"] -Formula "=Sum(O3:O8)" -Bold +Set-ExcelRange -Address $sheet1.Cells["C10"] -HorizontalAlignment Right -Bold -Value "Grand Total Calculation" +Set-ExcelRange -Address $sheet1.Cells["E10"] -Formula "=Sum(E3:E8)" -Bold +Set-ExcelRange -Address $sheet1.Cells["I10"] -Formula "=Sum(I3:I8)" -Bold +Set-ExcelRange -Address $sheet1.Cells["M10"] -Formula "=Sum(M3:M8)" -Bold +Set-ExcelRange -Address $sheet1.Cells["O10"] -Formula "=Sum(O3:O8)" -Bold Close-ExcelPackage $excel -Show diff --git a/Examples/FormatCellStyles/PassInScriptBlock.ps1 b/Examples/FormatCellStyles/PassInScriptBlock.ps1 index 2964a57..fca55bc 100644 --- a/Examples/FormatCellStyles/PassInScriptBlock.ps1 +++ b/Examples/FormatCellStyles/PassInScriptBlock.ps1 @@ -11,7 +11,7 @@ $RandomStyle = { ) 2..$totalRows | ForEach-Object{ - Set-CellStyle $workSheet $_ $LastColumn Solid (Write-Output LightGreen Gray Red|Get-Random) + Set-CellStyle $workSheet $_ $LastColumn Solid (Get-Random @("LightGreen", "Gray", "Red")) } } diff --git a/Examples/GenerateData/GenDataForCustomReport.ps1 b/Examples/GenerateData/GenDataForCustomReport.ps1 index 1381fba..d2b243f 100644 --- a/Examples/GenerateData/GenDataForCustomReport.ps1 +++ b/Examples/GenerateData/GenDataForCustomReport.ps1 @@ -1,26 +1,26 @@ -if(!(gcm ig -ErrorAction SilentlyContinue)) { +if(!(Get-Command ig -ErrorAction SilentlyContinue)) { "Use ``Install-Module NameIT`` to get the needed module from the gallery to support running this script" return -} +} -$sign=@{sign=echo + -} -$location=@{location=echo Atlanta Newark Washington Chicago Philadelphia Houston Phoneix} +$sign=@{sign=@( "+", "-" )} +$location=@{location=@("Atlanta", "Newark", "Washington", "Chicago", "Philadelphia", "Houston", "Phoneix")} $(1..6 | Foreach-Object { - + $from=$to="" while($from -eq $to) { $from=ig "[location]" -CustomData $location $to=ig "[location]" -CustomData $location - } + } [double]$a=ig "########" [double]$b=ig ".####" [double]$c=ig "#######" [double]$d=ig "[sign].##" -CustomData $sign - [double]$e=ig "###" + [double]$e=ig "###" [double]$f=ig "[sign]##" -CustomData $sign #"{0},{1},{2},{3},{4},{5},{6},{7}" -f $from, $to, $a, $b, $c, $d, $e, $f diff --git a/Examples/JoinWorksheet/Join-worksheet-blocks.sample.ps1 b/Examples/JoinWorksheet/Join-worksheet-blocks.sample.ps1 index b19fcdb..2f7a950 100644 --- a/Examples/JoinWorksheet/Join-worksheet-blocks.sample.ps1 +++ b/Examples/JoinWorksheet/Join-worksheet-blocks.sample.ps1 @@ -2,7 +2,7 @@ $path = "$env:TEMP\Test.xlsx" Remove-item -Path $path -ErrorAction SilentlyContinue #Export disk volume, and Network adapter to their own sheets. -Get-WmiObject -Class win32_logicaldisk | +Get-CimInstance -ClassName Win32_LogicalDisk | Select-Object -Property DeviceId,VolumeName, Size,Freespace | Export-Excel -Path $path -WorkSheetname Volumes -NumberFormat "0,000" Get-NetAdapter | diff --git a/Examples/JustCharts/TargetData.ps1 b/Examples/JustCharts/TargetData.ps1 index 2607920..23ff8e2 100644 --- a/Examples/JustCharts/TargetData.ps1 +++ b/Examples/JustCharts/TargetData.ps1 @@ -1,4 +1,4 @@ -$PropertyNames = echo Cost Date Name +$PropertyNames = @("Cost", "Date", "Name") New-PSItem 1.1 1/1/2015 John $PropertyNames New-PSItem 2.1 1/2/2015 Tom diff --git a/Examples/MortgageCalculator/MortgageCalculator.ps1 b/Examples/MortgageCalculator/MortgageCalculator.ps1 index dcdb6ff..9185df1 100644 --- a/Examples/MortgageCalculator/MortgageCalculator.ps1 +++ b/Examples/MortgageCalculator/MortgageCalculator.ps1 @@ -9,6 +9,7 @@ param( ) function New-CellData { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification='Does not change system state')] param( $Range, $Value, @@ -28,7 +29,7 @@ function New-CellData { $setFormatParams.Value = $Value } - Set-Format @setFormatParams + Set-ExcelRange @setFormatParams } $f = "$PSScriptRoot\mortgage.xlsx" @@ -37,19 +38,19 @@ Remove-Item $f -ErrorAction SilentlyContinue $pkg = "" | Export-Excel $f -Title 'Fixed Rate Loan Payments' -PassThru -AutoSize $ws = $pkg.Workbook.Worksheets["Sheet1"] -New-CellData A3 'Amount' -New-CellData B3 $Amount '$#,##0' +New-CellData -Range A3 -Value 'Amount' +New-CellData -Range B3 -Value $Amount -Format '$#,##0' -New-CellData A4 "Interest Rate" -New-CellData B4 $InterestRate 'Percentage' +New-CellData -Range A4 -Value "Interest Rate" +New-CellData -Range B4 -Value $InterestRate -Format 'Percentage' -New-CellData A5 "Term (Years)" -New-CellData B5 $Term +New-CellData -Range A5 -Value "Term (Years)" +New-CellData -Range B5 -Value $Term -New-CellData D3 "Monthly Payment" -New-CellData F3 "=-PMT(F4, B5*12, B3)" '$#,##0.#0' +New-CellData -Range D3 -Value "Monthly Payment" +New-CellData -Range F3 -Value "=-PMT(F4, B5*12, B3)" -Format '$#,##0.#0' -New-CellData D4 "Monthly Rate" -New-CellData F4 "=((1+B4)^(1/12))-1" 'Percentage' +New-CellData -Range D4 -Value "Monthly Rate" +New-CellData -Range F4 -Value "=((1+B4)^(1/12))-1" -Format 'Percentage' Close-ExcelPackage $pkg -Show \ No newline at end of file diff --git a/Examples/Nasa/FireBalls.ps1 b/Examples/Nasa/FireBalls.ps1 index 4dd99a5..625aa87 100644 --- a/Examples/Nasa/FireBalls.ps1 +++ b/Examples/Nasa/FireBalls.ps1 @@ -1,16 +1,17 @@ try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} -$header = echo ` - 'Date/Time - Peak Brightness (UT)' ` - 'Latitude (Deg)' ` - 'Longitude (Deg)' ` - 'Altitude (km)' ` - 'Velocity (km/s)' ` - 'Velocity Components (km/s) vx' ` - 'Velocity Components (km/s) vy' ` - 'Velocity Components (km/s) vz' ` - 'Total Radiated Energy (J)' ` +$header = @( + 'Date/Time - Peak Brightness (UT)' , + 'Latitude (Deg)' , + 'Longitude (Deg)' , + 'Altitude (km)' , + 'Velocity (km/s)' , + 'Velocity Components (km/s) vx' , + 'Velocity Components (km/s) vy' , + 'Velocity Components (km/s) vz' , + 'Total Radiated Energy (J)' , 'Calculated Total Impact Energy (kt)' +) $splat=@{ url='http://neo.jpl.nasa.gov/fireballs/' diff --git a/Examples/New-PSItem.ps1 b/Examples/New-PSItem.ps1 index b186dcc..85a41c3 100644 --- a/Examples/New-PSItem.ps1 +++ b/Examples/New-PSItem.ps1 @@ -1,5 +1,6 @@ function New-PSItem { - + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification='Does not change system state')] + param() $totalArgs = $args.Count if($args[-1] -is [array]) { diff --git a/Examples/OutTabulator/start-demo.ps1 b/Examples/OutTabulator/start-demo.ps1 index e5d4ada..5211e0d 100644 --- a/Examples/OutTabulator/start-demo.ps1 +++ b/Examples/OutTabulator/start-demo.ps1 @@ -3,10 +3,10 @@ ## This is an overhaul of Jeffrey Snover's original Start-Demo script by Joel "Jaykul" Bennett ## ## I've switched it to using ReadKey instead of ReadLine (you don't have to hit Enter each time) -## As a result, I've changed the names and keys for a lot of the operations, so that they make +## As a result, I've changed the names and keys for a lot of the operations, so that they make ## sense with only a single letter to tell them apart (sorry if you had them memorized). ## -## I've also been adding features as I come across needs for them, and you'll contribute your +## I've also been adding features as I come across needs for them, and you'll contribute your ## improvements back to the PowerShell Script repository as well. ################################################################################################## ## Revision History (version 3.3) @@ -32,12 +32,14 @@ ## so you have a chance to "go back" after the last line of you demo ################################################################################################## ## +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification='Correct and desirable usage')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingInvokeExpression', '', Justification='Correct and desirable usage')] param( - $file=".\demo.txt", - [int]$command=0, - [System.ConsoleColor]$promptColor="Yellow", - [System.ConsoleColor]$commandColor="White", - [System.ConsoleColor]$commentColor="Green", + $file=".\demo.txt", + [int]$command=0, + [System.ConsoleColor]$promptColor="Yellow", + [System.ConsoleColor]$commandColor="White", + [System.ConsoleColor]$commentColor="Green", [switch]$FullAuto, [int]$AutoSpeed = 3, [switch]$NoPauseAfterExecute @@ -46,7 +48,7 @@ param( $RawUI = $Host.UI.RawUI $hostWidth = $RawUI.BufferSize.Width -# A function for reading in a character +# A function for reading in a character function Read-Char() { $_OldColor = $RawUI.ForeGroundColor $RawUI.ForeGroundColor = "Red" @@ -93,20 +95,20 @@ Write-Host -nonew -back black -fore $promptColor "for help.$(' ' * ($hostWidth - Write-Host -nonew -back black -fore $promptColor $(" " * $hostWidth) # We use a FOR and an INDEX ($_i) instead of a FOREACH because -# it is possible to start at a different location and/or jump +# it is possible to start at a different location and/or jump # around in the order. for ($_i = $Command; $_i -lt $_lines.count; $_i++) -{ +{ # Put the current command in the Window Title along with the demo duration $Dur = [DateTime]::Now - $_StartTime - $RawUI.WindowTitle = "$(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s {3}" -f + $RawUI.WindowTitle = "$(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s {3}" -f $dur.Hours, $dur.Minutes, $dur.Seconds, $($_Lines[$_i]) # Echo out the commmand to the console with a prompt as though it were real Write-Host -nonew -fore $promptColor "[$_i]$([char]0x2265) " - if ($_lines[$_i].Trim(" ").StartsWith("#") -or $_lines[$_i].Trim(" ").Length -le 0) { + if ($_lines[$_i].Trim(" ").StartsWith("#") -or $_lines[$_i].Trim(" ").Length -le 0) { Write-Host -fore $commentColor "$($_Lines[$_i]) " - continue + continue } else { Write-Host -nonew -fore $commandColor "$($_Lines[$_i]) " } @@ -119,7 +121,7 @@ for ($_i = $Command; $_i -lt $_lines.count; $_i++) Running demo: $file (n) Next (p) Previous -(q) Quit (s) Suspend +(q) Quit (s) Suspend (t) Timecheck (v) View $(split-path $file -leaf) (g) Go to line by number (f) Find lines by string @@ -148,15 +150,15 @@ Running demo: $file break; } "v" { # View Source - $lines[0..($_i-1)] | Write-Host -Fore Yellow + $lines[0..($_i-1)] | Write-Host -Fore Yellow $lines[$_i] | Write-Host -Fore Green - $lines[($_i+1)..$lines.Count] | Write-Host -Fore Yellow + $lines[($_i+1)..$lines.Count] | Write-Host -Fore Yellow $_i-- # back a line, we're gonna step forward when we loop } "t" { # Time Check $dur = [DateTime]::Now - $_StartTime Write-Host -Fore $promptColor $( - "{3} -- $(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s" -f + "{3} -- $(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s" -f $dur.Hours, $dur.Minutes, $dur.Seconds, ([DateTime]::Now.ToShortTimeString())) $_i-- # back a line, we're gonna step forward when we loop } @@ -170,7 +172,7 @@ Running demo: $file if($i -le $_lines.Count) { if($i -gt 0) { # extra line back because we're gonna step forward when we loop - $_i = Rewind $_lines $_i (($_i-$i)+1) + $_i = Rewind -lines $_lines -index $_i -steps (($_i-$i)+1) } else { $_i = -1 # Start negative, because we step forward when we loop } @@ -178,18 +180,18 @@ Running demo: $file } "f" { # Find by pattern $match = $_lines | Select-String (Read-Host "search string") - if($match -eq $null) { + if($null -eq $match) { Write-Host -Fore Red "Can't find a matching line" } else { - $match | % { Write-Host -Fore $promptColor $("[{0,2}] {1}" -f ($_.LineNumber - 1), $_.Line) } + $match | ForEach-Object { Write-Host -Fore $promptColor $("[{0,2}] {1}" -f ($_.LineNumber - 1), $_.Line) } if($match.Count -lt 1) { $_i = $match.lineNumber - 2 # back a line, we're gonna step forward when we loop - } else { + } else { $_i-- # back a line, we're gonna step forward when we loop } } } - "c" { + "c" { Clear-Host $_i-- # back a line, we're gonna step forward when we loop } @@ -197,7 +199,7 @@ Running demo: $file Write-Host trap [System.Exception] {Write-Error $_; continue;} Invoke-Expression ($_lines[$_i]) | out-default - if(-not $NoPauseAfterExecute -and -not $FullAuto) { + if(-not $NoPauseAfterExecute -and -not $FullAuto) { $null = $RawUI.ReadKey("NoEcho,IncludeKeyUp") # Pause after output for no apparent reason... ;) } } @@ -210,7 +212,7 @@ Running demo: $file } $dur = [DateTime]::Now - $_StartTime Write-Host -Fore $promptColor $( - "" -f + "" -f $dur.Hours, $dur.Minutes, $dur.Seconds, [DateTime]::Now.ToLongTimeString()) Write-Host -Fore $promptColor $([DateTime]::now) Write-Host \ No newline at end of file diff --git a/Examples/PivotTable/MultiplePivotTables.ps1 b/Examples/PivotTable/MultiplePivotTables.ps1 index b4af519..9aac6c0 100644 --- a/Examples/PivotTable/MultiplePivotTables.ps1 +++ b/Examples/PivotTable/MultiplePivotTables.ps1 @@ -20,11 +20,11 @@ $pivotTableParams = @{ PivotTableName = "ByRegion" Address = $excel.Sheet1.cells["F1"] SourceWorkSheet = $excel.Sheet1 - PivotRows = echo Region Fruit Date + PivotRows = @("Region", "Fruit", "Date") PivotData = @{'sold' = 'sum'} PivotTableStyle = 'Light21' GroupDateRow = "Date" - GroupDatePart = echo Years Quarters + GroupDatePart = @("Years", "Quarters") } $pt = Add-PivotTable @pivotTableParams -PassThru @@ -33,21 +33,21 @@ $pt.RowHeaderCaption = "By " + ($pivotTableParams.PivotRows -join ",") $pivotTableParams.PivotTableName = "ByFruit" $pivotTableParams.Address = $excel.Sheet1.cells["J1"] -$pivotTableParams.PivotRows = echo Fruit Region Date +$pivotTableParams.PivotRows = @("Fruit", "Region", "Date") $pt = Add-PivotTable @pivotTableParams -PassThru $pt.RowHeaderCaption = "By Fruit,Region" $pivotTableParams.PivotTableName = "ByDate" $pivotTableParams.Address = $excel.Sheet1.cells["N1"] -$pivotTableParams.PivotRows = echo Date Region Fruit +$pivotTableParams.PivotRows = @("Date", "Region", "Fruit") $pt = Add-PivotTable @pivotTableParams -PassThru $pt.RowHeaderCaption = "By Date,Region,Fruit" $pivotTableParams.PivotTableName = "ByYears" $pivotTableParams.Address = $excel.Sheet1.cells["S1"] -$pivotTableParams.GroupDatePart = echo Years +$pivotTableParams.GroupDatePart = "Years" $pt = Add-PivotTable @pivotTableParams -PassThru $pt.RowHeaderCaption = "By Years,Region" diff --git a/Examples/ReadAllSheets/Get-ExcelSheets.ps1 b/Examples/ReadAllSheets/Get-ExcelSheets.ps1 index 0b089ae..3aacdc9 100644 --- a/Examples/ReadAllSheets/Get-ExcelSheets.ps1 +++ b/Examples/ReadAllSheets/Get-ExcelSheets.ps1 @@ -10,10 +10,10 @@ $hash = @{ } $e = Open-ExcelPackage $path -foreach ($sheet in $e.workbook.worksheets) { - $hash[$sheet.name] = Import-Excel -ExcelPackage $e -WorksheetName $sheet.name -} +foreach ($sheet in $e.workbook.worksheets) { + $hash[$sheet.name] = Import-Excel -ExcelPackage $e -WorksheetName $sheet.name +} -Close-ExcelPackage $e -NoSave +Close-ExcelPackage $e -NoSave $hash \ No newline at end of file diff --git a/Examples/ReadAllSheets/ReadAllSheets.ps1 b/Examples/ReadAllSheets/ReadAllSheets.ps1 index 5bc26d4..cf48ca5 100644 --- a/Examples/ReadAllSheets/ReadAllSheets.ps1 +++ b/Examples/ReadAllSheets/ReadAllSheets.ps1 @@ -1,4 +1,4 @@ $xlfile = "$env:TEMP\MultipleSheets.xlsx" -.\GenerateXlsx.ps1 $xlfile -.\Get-ExcelSheets.ps1 $xlfile \ No newline at end of file +.\GenerateXlsx.ps1 $xlfile +.\Get-ExcelSheets.ps1 $xlfile \ No newline at end of file diff --git a/Examples/SQL+FillColumns+Pivot/Example.ps1 b/Examples/SQL+FillColumns+Pivot/Example.ps1 index 4de0062..702674f 100644 --- a/Examples/SQL+FillColumns+Pivot/Example.ps1 +++ b/Examples/SQL+FillColumns+Pivot/Example.ps1 @@ -44,17 +44,17 @@ Remove-Item -Path "~\Documents\temp.xlsx" -ErrorAction SilentlyContinue $e = Send-SQLDataToExcel -Path "~\Documents\temp.xlsx" -WorkSheetname "Sheet1" -Connection "DSN=LR" -SQL $sql -AutoSize -Passthru #Add columns, then format them and hide the ones which aren't of interest. -Set-Column -Worksheet $e.workbook.Worksheets["sheet1"] -Column 21 -Value $Avalue -Heading "Apperture" -Set-Column -Worksheet $e.workbook.Worksheets["sheet1"] -Column 22 -Value $Svalue -Heading "Shutter" -Set-Column -Worksheet $e.workbook.Worksheets["sheet1"] -Column 23 -Value $Evvalue -Heading "Ev" -Set-Format -Address $e.workbook.Worksheets["sheet1" ].Column(21) -HorizontalAlignment Left -AutoFit -Set-Format -Address $e.workbook.Worksheets["sheet1" ].Column(22) -HorizontalAlignment Right -AutoFit +Set-ExcelColumn -Worksheet $e.workbook.Worksheets["sheet1"] -Column 21 -Value $Avalue -Heading "Apperture" +Set-ExcelColumn -Worksheet $e.workbook.Worksheets["sheet1"] -Column 22 -Value $Svalue -Heading "Shutter" +Set-ExcelColumn -Worksheet $e.workbook.Worksheets["sheet1"] -Column 23 -Value $Evvalue -Heading "Ev" +Set-ExcelRange -Address $e.workbook.Worksheets["sheet1" ].Column(21) -HorizontalAlignment Left -AutoFit +Set-ExcelRange -Address $e.workbook.Worksheets["sheet1" ].Column(22) -HorizontalAlignment Right -AutoFit @(5,6,7,13,15,16,17,18) | ForEach-Object { - Set-Format -Address $e.workbook.Worksheets["sheet1" ].Column($_) -Hidden + Set-ExcelRange -Address $e.workbook.Worksheets["sheet1" ].Column($_) -Hidden } #Center the column labels. -Set-Format -Address $e.workbook.Worksheets["sheet1" ].Row(1) -HorizontalAlignment Center +Set-ExcelRange -Address $e.workbook.Worksheets["sheet1" ].Row(1) -HorizontalAlignment Center #Format the data as a nice Table, Create the pivot table & chart defined above, show the file in Excel in excel after saving. Export-Excel -ExcelPackage $e -WorkSheetname "sheet1" -TableName "Table" -PivotTableDefinition $pt -Show @@ -78,10 +78,10 @@ $SQL = @" #Run the query and put the results in workshet "Winners", autosize the columns and hold on to the ExcelPackage object $Excel = Send-SQLDataToExcel -SQL $sql -Session $session -path .\demo3.xlsx -WorkSheetname "Winners" -AutoSize -Passthru #Create and format columns for the ratio of Wins to poles and fast laps. -Set-Column -ExcelPackage $Excel -WorkSheetname "Winners" -column 6 -Heading "WinsToPoles" -Value {"=D$row/C$row"} -Set-Column -ExcelPackage $Excel -WorkSheetname "Winners" -column 7 -Heading "WinsToFast" -Value {"=E$row/C$row"} +Set-ExcelColumn -ExcelPackage $Excel -WorkSheetname "Winners" -column 6 -Heading "WinsToPoles" -Value {"=D$row/C$row"} +Set-ExcelColumn -ExcelPackage $Excel -WorkSheetname "Winners" -column 7 -Heading "WinsToFast" -Value {"=E$row/C$row"} 6..7 | ForEach-Object { - Set-Format -Address $Excel.Workbook.Worksheets["Winners"].column($_) -NumberFormat "0.0%" -AutoFit } + Set-ExcelRange -Address $Excel.Workbook.Worksheets["Winners"].column($_) -NumberFormat "0.0%" -AutoFit } #Define a chart to show the relationship of lest on an XY Grid, create the ranges required in the, add the chart and show the file in Excel in excel after saving. $chart = New-ExcelChart -NoLegend -ChartType XYScatter -XRange WinsToFast -YRange WinsToPoles -ShowCategory -Column 7 -Width 2000 -Height 700 Export-Excel -ExcelPackage $Excel -WorkSheetname "Winners" -AutoNameRange -ExcelChartDefinition $chart -Show diff --git a/Examples/SQL+FillColumns+Pivot/Example2.ps1 b/Examples/SQL+FillColumns+Pivot/Example2.ps1 index 8fe0a65..9c80f6d 100644 --- a/Examples/SQL+FillColumns+Pivot/Example2.ps1 +++ b/Examples/SQL+FillColumns+Pivot/Example2.ps1 @@ -19,6 +19,6 @@ Set-Row -Worksheet $ws -Heading "Average" -Value {"=Average($columnName`2 Set-Column -Worksheet $ws -Heading "WinsToPoles" -Value {"=D$row/C$row"} -Column 6 -AutoSize -AutoNameRange Set-Column -Worksheet $ws -Heading "WinsToFast" -Value {"=E$row/C$row"} -Column 7 -AutoSize -AutoNameRange -Set-Format -WorkSheet $ws -Range "F2:G50" -NumberFormat "0.0%" +Set-ExcelRange -WorkSheet $ws -Range "F2:G50" -NumberFormat "0.0%" $chart = New-ExcelChart -NoLegend -ChartType XYScatter -XRange WinsToFast -YRange WinsToPoles -Column 7 -Width 2000 -Height 700 -Title "Poles vs fastlaps" Export-Excel -ExcelPackage $Excel -WorkSheetname "Winners" -ExcelChartDefinition $chart -Show \ No newline at end of file diff --git a/Examples/Sparklines/SalesByQuarter.ps1 b/Examples/Sparklines/SalesByQuarter.ps1 index d2263a2..4c888d2 100644 --- a/Examples/Sparklines/SalesByQuarter.ps1 +++ b/Examples/Sparklines/SalesByQuarter.ps1 @@ -15,7 +15,7 @@ $excel = $data | Export-Excel $xlfile -Passthru -AutoSize -TableName SalesByQuar $ws = $excel.Sheet1 -Set-Format -WorkSheet $ws -Range "B2:E5" -NumberFormat "$#,##0" -AutoSize +Set-ExcelRange -WorkSheet $ws -Range "B2:E5" -NumberFormat "$#,##0" -AutoSize $sparkLineType = "line" $null = $ws.SparklineGroups.Add( $sparkLineType, $ws.Cells["F2"], $ws.Cells["B2:E2"] ) $null = $ws.SparklineGroups.Add( $sparkLineType, $ws.Cells["F3"], $ws.Cells["B3:E3"] ) diff --git a/Examples/Sparklines/Sparklines.ps1 b/Examples/Sparklines/Sparklines.ps1 index 2816d97..1802233 100644 --- a/Examples/Sparklines/Sparklines.ps1 +++ b/Examples/Sparklines/Sparklines.ps1 @@ -41,8 +41,8 @@ Remove-Item $xlfile -ErrorAction SilentlyContinue $excel = $data | Export-Excel $xlfile -WorksheetName SEKRates -AutoSize -PassThru # Add a column sparkline for all currencies -Set-Format -WorkSheet $excel.SEKRates -Range "A2:A12" -NumberFormat "yyyy-mm-dd" -AutoSize -Set-Format -WorkSheet $excel.SEKRates -Range A15 -Value Column -AutoSize +Set-ExcelRange -WorkSheet $excel.SEKRates -Range "A2:A12" -NumberFormat "yyyy-mm-dd" -AutoSize +Set-ExcelRange -WorkSheet $excel.SEKRates -Range A15 -Value Column -AutoSize $sparklineCol = $excel.SEKRates.SparklineGroups.Add( "Column", @@ -54,7 +54,7 @@ $sparklineCol.High = $true $sparklineCol.ColorHigh.SetColor("Red") # Add a line sparkline for all currencies -Set-Format -WorkSheet $excel.SEKRates -Range A16 -Value Line -AutoSize +Set-ExcelRange -WorkSheet $excel.SEKRates -Range A16 -Value Line -AutoSize $sparklineLine = $excel.SEKRates.SparklineGroups.Add( "Line", $excel.SEKRates.Cells["B16:Q16"], @@ -64,7 +64,7 @@ $sparklineLine = $excel.SEKRates.SparklineGroups.Add( $sparklineLine.DateAxisRange = $excel.SEKRates.Cells["A2:A12"] # Add some more random values and add a stacked sparkline. -Set-Format -WorkSheet $excel.SEKRates -Range A17 -Value Stacked -AutoSize +Set-ExcelRange -WorkSheet $excel.SEKRates -Range A17 -Value Stacked -AutoSize $numbers = 2, -1, 3, -4, 8, 5, -12, 18, 99, 1, -4, 12, -8, 9, 0, -8 @@ -86,7 +86,7 @@ $sparklineStacked.ColorLow.SetColor("Green") $sparklineStacked.Negative = $true $sparklineStacked.ColorNegative.SetColor("Blue") -Set-Format -WorkSheet $excel.SEKRates -Range "A15:A17" -Bold -Height 50 -AutoSize +Set-ExcelRange -WorkSheet $excel.SEKRates -Range "A15:A17" -Bold -Height 50 -AutoSize $v = @" High - Red @@ -94,6 +94,6 @@ Low - Green Negative - Blue "@ -Set-Format -WorkSheet $excel.SEKRates -Range S17 -Value $v -WrapText -Width 20 -HorizontalAlignment Center -VerticalAlignment Center +Set-ExcelRange -WorkSheet $excel.SEKRates -Range S17 -Value $v -WrapText -Width 20 -HorizontalAlignment Center -VerticalAlignment Center Close-ExcelPackage $excel -Show \ No newline at end of file diff --git a/Examples/SpreadsheetCells/CalculatedFields.ps1 b/Examples/SpreadsheetCells/CalculatedFields.ps1 index be988d7..f03b317 100644 --- a/Examples/SpreadsheetCells/CalculatedFields.ps1 +++ b/Examples/SpreadsheetCells/CalculatedFields.ps1 @@ -6,7 +6,7 @@ try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} Remove-Item "$env:temp\functions.xlsx" -ErrorAction SilentlyContinue $( - New-PSItem 12001 Nails 37 3.99 =C2*D2 (echo ID Product Quantity Price Total) + New-PSItem 12001 Nails 37 3.99 =C2*D2 @("ID", "Product", "Quantity", "Price", "Total") New-PSItem 12002 Hammer 5 12.10 =C3*D3 New-PSItem 12003 Saw 12 15.37 =C4*D4 New-PSItem 12010 Drill 20 8 =C5*D5 diff --git a/Examples/SpreadsheetCells/ExcelFunctions.ps1 b/Examples/SpreadsheetCells/ExcelFunctions.ps1 index aac6f69..49ec396 100644 --- a/Examples/SpreadsheetCells/ExcelFunctions.ps1 +++ b/Examples/SpreadsheetCells/ExcelFunctions.ps1 @@ -3,7 +3,7 @@ try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} Remove-Item "$env:temp\functions.xlsx" -ErrorAction SilentlyContinue $( - New-PSItem =2%/12 60 500000 "=pmt(rate,nper,pv)" (echo rate nper pv pmt) + New-PSItem =2%/12 60 500000 "=pmt(rate,nper,pv)" @("rate", "nper", "pv", "pmt") New-PSItem =3%/12 60 500000 "=pmt(rate,nper,pv)" New-PSItem =4%/12 60 500000 "=pmt(rate,nper,pv)" New-PSItem =5%/12 60 500000 "=pmt(rate,nper,pv)" diff --git a/Examples/Stocks/Get-StockInfo.ps1 b/Examples/Stocks/Get-StockInfo.ps1 index 24f125a..b5a5fde 100644 --- a/Examples/Stocks/Get-StockInfo.ps1 +++ b/Examples/Stocks/Get-StockInfo.ps1 @@ -7,13 +7,10 @@ function Get-StockInfo { ) $xlfile = "$env:TEMP\stocks.xlsx" - rm $xlfile -ErrorAction Ignore + Remove-Item -Path $xlfile -ErrorAction Ignore $result = Invoke-RestMethod "https://api.iextrading.com/1.0/stock/market/batch?symbols=$($symbols)&types=quote&last=1" - $symbolCount = $symbols.Split(",").count - - $ecd = New-ExcelChartDefinition -Row 1 -Column 1 -SeriesHeader $dataPlot ` -XRange symbol -YRange $dataPlot ` -Title "$($dataPlot)`r`n As Of $((Get-Date).ToShortDateString())" diff --git a/Examples/TestRestAPI/RunAndShowUnitTests.ps1 b/Examples/TestRestAPI/RunAndShowUnitTests.ps1 index 6f1bf44..084033a 100644 --- a/Examples/TestRestAPI/RunAndShowUnitTests.ps1 +++ b/Examples/TestRestAPI/RunAndShowUnitTests.ps1 @@ -1,7 +1,7 @@ try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return} $xlfilename=".\test.xlsx" -rm $xlfilename -ErrorAction Ignore +Remove-Item $xlfilename -ErrorAction Ignore $ConditionalText = @() $ConditionalText += New-ConditionalText -Range "C:C" -Text failed -BackgroundColor red -ConditionalTextColor black @@ -26,12 +26,12 @@ $sheet1 = $xlPkg.Workbook.Worksheets["sheet1"] $sheet1.View.ShowGridLines = $false $sheet1.View.ShowHeaders = $false -Set-Format -Address $sheet1.Cells["A:A"] -AutoSize -Set-Format -Address $sheet1.Cells["B:D"] -WrapText +Set-ExcelRange -Address $sheet1.Cells["A:A"] -AutoSize +Set-ExcelRange -Address $sheet1.Cells["B:D"] -WrapText $sheet1.InsertColumn(1, 1) -Set-Format -Address $sheet1.Cells["A:A"] -Width 5 +Set-ExcelRange -Address $sheet1.Cells["A:A"] -Width 5 -Set-Format -Address $sheet1.Cells["B1:E1"] -HorizontalAlignment Center -BorderBottom Thick -BorderColor Cyan +Set-ExcelRange -Address $sheet1.Cells["B1:E1"] -HorizontalAlignment Center -BorderBottom Thick -BorderColor Cyan Close-ExcelPackage $xlPkg -Show \ No newline at end of file diff --git a/Examples/TestRestAPI/ShowPesterResults.ps1 b/Examples/TestRestAPI/ShowPesterResults.ps1 index aa3b7ba..55e8e16 100644 --- a/Examples/TestRestAPI/ShowPesterResults.ps1 +++ b/Examples/TestRestAPI/ShowPesterResults.ps1 @@ -1,4 +1,6 @@ function Show-PesterResults { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification="No suitable singular")] + Param() $xlfilename = ".\test.xlsx" Remove-Item $xlfilename -ErrorAction Ignore diff --git a/Examples/TestRestAPI/TestAPIReadXls.ps1 b/Examples/TestRestAPI/TestAPIReadXls.ps1 index ff2e5d3..4dc1810 100644 --- a/Examples/TestRestAPI/TestAPIReadXls.ps1 +++ b/Examples/TestRestAPI/TestAPIReadXls.ps1 @@ -1,4 +1,5 @@ function Test-APIReadXls { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification="False Positive")] param( [parameter(Mandatory)] $XlFilename, diff --git a/Examples/TryMultiplePivotTables.ps1 b/Examples/TryMultiplePivotTables.ps1 index f53338f..6b5c332 100644 --- a/Examples/TryMultiplePivotTables.ps1 +++ b/Examples/TryMultiplePivotTables.ps1 @@ -1,12 +1,12 @@ -# To ship, is to choose +# To ship, is to choose #ipmo .\ImportExcel.psd1 -Force $pt=[ordered]@{} -$pt.ServiceInfo=@{ +$pt.ServiceInfo=@{ SourceWorkSheet='Services' - PivotRows = "Status" + PivotRows = "Status" PivotData= @{'Status'='count'} IncludePivotChart=$true ChartType='BarClustered3D' @@ -14,7 +14,7 @@ $pt.ServiceInfo=@{ $pt.ProcessInfo=@{ SourceWorkSheet='Processes' - PivotRows = "Company" + PivotRows = "Company" PivotData= @{'Company'='count'} IncludePivotChart=$true ChartType='PieExploded3D' @@ -24,7 +24,7 @@ $gsv=Get-Service | Select-Object status, Name, displayName, starttype $ps=Get-Process | Select-Object Name,Company, Handles $file = "c:\temp\testPT.xlsx" -rm $file -ErrorAction Ignore +Remove-Item $file -ErrorAction Ignore $gsv| Export-Excel -Path $file -AutoSize -WorkSheetname Services -$ps | Export-Excel -Path $file -AutoSize -WorkSheetname Processes -PivotTableDefinition $pt -Show +$ps | Export-Excel -Path $file -AutoSize -WorkSheetname Processes -PivotTableDefinition $pt -Show diff --git a/Examples/VBA/HelloWorldVBA.ps1 b/Examples/VBA/HelloWorldVBA.ps1 index aa3c1e4..855df0f 100644 --- a/Examples/VBA/HelloWorldVBA.ps1 +++ b/Examples/VBA/HelloWorldVBA.ps1 @@ -32,7 +32,7 @@ End Function $module = $wb.VbaProject.Modules.AddModule("PSExcelModule") $module.Code = $code -Set-Format -WorkSheet $sheet -Range "h7" -Formula "HelloWorld()" -AutoSize -Set-Format -WorkSheet $sheet -Range "h8" -Formula "DoSum()" -AutoSize +Set-ExcelRange -WorkSheet $sheet -Range "h7" -Formula "HelloWorld()" -AutoSize +Set-ExcelRange -WorkSheet $sheet -Range "h8" -Formula "DoSum()" -AutoSize Close-ExcelPackage $Excel -Show \ No newline at end of file diff --git a/__tests__/Compare-WorkSheet.tests.ps1 b/__tests__/Compare-WorkSheet.tests.ps1 index ce88404..e14e609 100644 --- a/__tests__/Compare-WorkSheet.tests.ps1 +++ b/__tests__/Compare-WorkSheet.tests.ps1 @@ -1,4 +1,6 @@ #Requires -Modules Pester +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')] +param() if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { Import-Module $PSScriptRoot\..\ImportExcel.psd1 } diff --git a/__tests__/Copy-ExcelWorksheet.Tests.ps1 b/__tests__/Copy-ExcelWorksheet.Tests.ps1 index d260522..4e2b9c1 100644 --- a/__tests__/Copy-ExcelWorksheet.Tests.ps1 +++ b/__tests__/Copy-ExcelWorksheet.Tests.ps1 @@ -1,3 +1,6 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')] +param() + Describe "Copy-Worksheet" { $path1 = "TestDrive:\Test1.xlsx" $path2 = "TestDrive:\Test2.xlsx" @@ -94,7 +97,7 @@ Describe "Copy-Worksheet" { Remove-Item $xlfile -ErrorAction SilentlyContinue Remove-Item $xlfileArchive -ErrorAction SilentlyContinue - $sheets = echo 1.1.2019 1.2.2019 1.3.2019 1.4.2019 1.5.2019 + $sheets = "1.1.2019", "1.2.2019", "1.3.2019", "1.4.2019", "1.5.2019" $sheets | ForEach-Object { "Hello World" | Export-Excel $xlfile -WorksheetName $_ @@ -102,7 +105,7 @@ Describe "Copy-Worksheet" { } it "Should copy and remove sheets " { - $targetSheets = echo 1.1.2019 1.4.2019 + $targetSheets = "1.1.2019", "1.4.2019" $targetSheets | ForEach-Object { Copy-ExcelWorkSheet -SourceWorkbook $xlfile -DestinationWorkbook $xlfileArchive -SourceWorkSheet $_ -DestinationWorkSheet $_ @@ -122,7 +125,7 @@ Describe "Copy-Worksheet" { Remove-Item $xlfile -ErrorAction SilentlyContinue Remove-Item $xlfileArchive -ErrorAction SilentlyContinue - $sheets = echo 1.1.2019 1.2.2019 1.3.2019 1.4.2019 1.5.2019 + $sheets = "1.1.2019", "1.2.2019", "1.3.2019", "1.4.2019", "1.5.2019" $sheets | ForEach-Object { "Hello World" | Export-Excel $xlfile -WorksheetName $_ diff --git a/__tests__/Export-Excel.Tests.ps1 b/__tests__/Export-Excel.Tests.ps1 index c7df4cc..ad34a80 100644 --- a/__tests__/Export-Excel.Tests.ps1 +++ b/__tests__/Export-Excel.Tests.ps1 @@ -1,5 +1,7 @@ #Requires -Modules Pester - +[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidAssignmentToAutomaticVariable", "", Justification='Sets IsWindows on pre-6.0 only')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')] +param() if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { Import-Module $PSScriptRoot\..\ImportExcel.psd1 } @@ -20,7 +22,7 @@ Describe ExportExcel { $path = "TestDrive:\test.xlsx" Remove-item -Path $path -ErrorAction SilentlyContinue #Test with a maximum of 100 processes for speed; export all properties, then export smaller subsets. - $processes = Get-Process | where {$_.StartTime} | Select-Object -first 100 -Property * -excludeProperty Parent + $processes = Get-Process | Where-Object {$_.StartTime} | Select-Object -First 100 -Property * -ExcludeProperty Parent $propertyNames = $Processes[0].psobject.properties.name $rowcount = $Processes.Count $Processes | Export-Excel $path #-show @@ -371,7 +373,7 @@ Describe ExportExcel { $path = "TestDrive:\test.xlsx" Remove-item -Path $path -ErrorAction SilentlyContinue #Test -ConditionalText with a single conditional spec. - Write-Output 489 668 299 777 860 151 119 497 234 788 | Export-Excel -Path $path -ConditionalText $ct + 489, 668, 299, 777, 860, 151, 119, 497, 234, 788 | Export-Excel -Path $path -ConditionalText $ct it "Created a new file " { Test-Path -Path $path -ErrorAction SilentlyContinue | Should be $true @@ -612,9 +614,9 @@ Describe ExportExcel { Get-Process | Select-Object -last 10 -Property Name, cpu, pm, handles, company | Export-Excel -Path $path -AutoNameRange -WorkSheetname NoOffset -Append -Numberformat 'Number' $Excel = Open-ExcelPackage $path $dataWs = $Excel.Workbook.Worksheets["NoOffset"] - + #table should be 20 rows + header after extending the data. CPU range should be 1x20 it "Created a new sheet and auto-extended a table and explicitly extended named ranges " { - $dataWs.Tables["ProcTab"].Address.Address | Should be "A1:E11" + $dataWs.Tables["ProcTab"].Address.Address | Should be "A1:E21" $dataWs.Names["CPU"].Rows | Should be 20 $dataWs.Names["CPU"].Columns | Should be 1 } diff --git a/__tests__/First10Races.tests.ps1 b/__tests__/First10Races.tests.ps1 index 77d8a6f..4d913b5 100644 --- a/__tests__/First10Races.tests.ps1 +++ b/__tests__/First10Races.tests.ps1 @@ -1,4 +1,6 @@ -$scriptPath = Split-Path -Path $MyInvocation.MyCommand.path -Parent +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')] +param() +$scriptPath = Split-Path -Path $MyInvocation.MyCommand.path -Parent $dataPath = Join-Path -Path $scriptPath -ChildPath "First10Races.csv" $WarningAction = "SilentlyContinue" diff --git a/__tests__/ImportExcelHeaderName.tests.ps1 b/__tests__/ImportExcelHeaderName.tests.ps1 index d5c9ac1..dfc2f72 100644 --- a/__tests__/ImportExcelHeaderName.tests.ps1 +++ b/__tests__/ImportExcelHeaderName.tests.ps1 @@ -5,17 +5,17 @@ Describe "Import-Excel on a sheet with no headings" { $xl = "" | export-excel $xlfile -PassThru - Set-Format -WorkSheet $xl.Sheet1 -Range A1 -Value 'A' - Set-Format -WorkSheet $xl.Sheet1 -Range B1 -Value 'B' - Set-Format -WorkSheet $xl.Sheet1 -Range C1 -Value 'C' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range A1 -Value 'A' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range B1 -Value 'B' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range C1 -Value 'C' - Set-Format -WorkSheet $xl.Sheet1 -Range A2 -Value 'D' - Set-Format -WorkSheet $xl.Sheet1 -Range B2 -Value 'E' - Set-Format -WorkSheet $xl.Sheet1 -Range C2 -Value 'F' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range A2 -Value 'D' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range B2 -Value 'E' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range C2 -Value 'F' - Set-Format -WorkSheet $xl.Sheet1 -Range A3 -Value 'G' - Set-Format -WorkSheet $xl.Sheet1 -Range B3 -Value 'H' - Set-Format -WorkSheet $xl.Sheet1 -Range C3 -Value 'I' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range A3 -Value 'G' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range B3 -Value 'H' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range C3 -Value 'I' Close-ExcelPackage $xl } @@ -160,20 +160,20 @@ Describe "Import-Excel on a sheet with no headings" { $xlfile = "TestDrive:\testImportExcelSparse.xlsx" $xl = "" | export-excel $xlfile -PassThru - Set-Format -WorkSheet $xl.Sheet1 -Range A1 -Value 'Chuck' - Set-Format -WorkSheet $xl.Sheet1 -Range B1 -Value '' - Set-Format -WorkSheet $xl.Sheet1 -Range C1 -Value 'Norris' - Set-Format -WorkSheet $xl.Sheet1 -Range D1 -Value 'California' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range A1 -Value 'Chuck' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range B1 -Value '' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range C1 -Value 'Norris' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range D1 -Value 'California' - Set-Format -WorkSheet $xl.Sheet1 -Range A2 -Value '' - Set-Format -WorkSheet $xl.Sheet1 -Range B2 -Value '' - Set-Format -WorkSheet $xl.Sheet1 -Range C2 -Value '' - Set-Format -WorkSheet $xl.Sheet1 -Range D2 -Value '' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range A2 -Value '' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range B2 -Value '' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range C2 -Value '' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range D2 -Value '' - Set-Format -WorkSheet $xl.Sheet1 -Range A3 -Value 'Jean-Claude' - Set-Format -WorkSheet $xl.Sheet1 -Range B3 -Value '' - Set-Format -WorkSheet $xl.Sheet1 -Range C3 -Value 'Vandamme' - Set-Format -WorkSheet $xl.Sheet1 -Range D3 -Value 'Brussels' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range A3 -Value 'Jean-Claude' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range B3 -Value '' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range C3 -Value 'Vandamme' + Set-ExcelRange -WorkSheet $xl.Sheet1 -Range D3 -Value 'Brussels' Close-ExcelPackage $xl diff --git a/__tests__/ImportExcelTests/Simple.tests.ps1 b/__tests__/ImportExcelTests/Simple.tests.ps1 index 1e91a1f..12049ec 100644 --- a/__tests__/ImportExcelTests/Simple.tests.ps1 +++ b/__tests__/ImportExcelTests/Simple.tests.ps1 @@ -1,4 +1,6 @@ -if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')] +Param() +if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { Import-Module $PSScriptRoot\..\..\ImportExcel.psd1 } Describe "Tests" { diff --git a/__tests__/InputItemParameter.tests.ps1 b/__tests__/InputItemParameter.tests.ps1 index 28ddc45..06162a6 100644 --- a/__tests__/InputItemParameter.tests.ps1 +++ b/__tests__/InputItemParameter.tests.ps1 @@ -1,3 +1,5 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')] +Param() Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking Import -asText" { BeforeAll { $path = "TestDrive:\Results.xlsx" diff --git a/__tests__/Join-Worksheet.tests.ps1 b/__tests__/Join-Worksheet.tests.ps1 index 31f4049..8ba42c8 100644 --- a/__tests__/Join-Worksheet.tests.ps1 +++ b/__tests__/Join-Worksheet.tests.ps1 @@ -1,4 +1,6 @@ -$data1 = ConvertFrom-Csv -InputObject @" +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')] +param() +$data1 = ConvertFrom-Csv -InputObject @" ID,Product,Quantity,Price,Total 12001,Nails,37,3.99,147.63 12002,Hammer,5,12.10,60.5 diff --git a/__tests__/RangePassing.ps1 b/__tests__/RangePassing.ps1 index e0dc770..25de3b7 100644 --- a/__tests__/RangePassing.ps1 +++ b/__tests__/RangePassing.ps1 @@ -1,3 +1,5 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingCmdletAliases','',Justification='Testing for presence of alias')] +param() $path = "TestDrive:\test.xlsx" describe "Consistent passing of ranges." { Context "Conditional Formatting" { diff --git a/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 b/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 index d85d67c..96442e4 100644 --- a/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 +++ b/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 @@ -1,3 +1,8 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingCmdletAliases','',Justification='Testing for presence of alias')] + +param() + $path = "TestDrive:\test.xlsx" $data = ConvertFrom-Csv -InputObject @" diff --git a/__tests__/Validation.tests.ps1 b/__tests__/Validation.tests.ps1 index 8fe59eb..49c7e21 100644 --- a/__tests__/Validation.tests.ps1 +++ b/__tests__/Validation.tests.ps1 @@ -1,3 +1,5 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')] +param() $data = ConvertFrom-Csv -InputObject @" ID,Product,Quantity,Price 12001,Nails,37,3.99 diff --git a/spikes/ConvertFrom-ExcelColumnName.ps1 b/spikes/ConvertFrom-ExcelColumnName.ps1 index c704277..6eab560 100644 --- a/spikes/ConvertFrom-ExcelColumnName.ps1 +++ b/spikes/ConvertFrom-ExcelColumnName.ps1 @@ -6,7 +6,7 @@ function ConvertFrom-ExcelColumnName { ForEach-Object { $sum*=26 $sum+=[char]$_.tostring().toupper()-[char]'A'+1 - } + } $sum } From 5595aee40744eda2df5595727ec04bd07744fe3e Mon Sep 17 00:00:00 2001 From: jhoneill Date: Thu, 21 Nov 2019 20:35:17 +0000 Subject: [PATCH 10/25] sync export changes from master into refactor --- ExportedCommands/Export-Excel.ps1 | 34 +++++++++++++++---------------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/ExportedCommands/Export-Excel.ps1 b/ExportedCommands/Export-Excel.ps1 index 0ab635f..a8c54c5 100644 --- a/ExportedCommands/Export-Excel.ps1 +++ b/ExportedCommands/Export-Excel.ps1 @@ -2,7 +2,7 @@ [CmdletBinding(DefaultParameterSetName = 'Default')] [OutputType([OfficeOpenXml.ExcelPackage])] [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] - Param( + param( [Parameter(ParameterSetName = 'Default', Position = 0)] [String]$Path, [Parameter(Mandatory = $true, ParameterSetName = "Package")] @@ -111,7 +111,7 @@ if (-not $PSBoundParameters.ContainsKey("TableName") -and -not $PSBoundParameters.ContainsKey("TableStyle") -and -not $AutoFilter) { - $TableName = 'Table1' + $TableName = '' # later rely on distinction between NULL and "" } } if ($ExcelPackage) { @@ -137,6 +137,7 @@ $headerRange = $ws.Dimension.Address -replace "\d+$", $StartRow #using a slightly odd syntax otherwise header ends up as a 2D array $ws.Cells[$headerRange].Value | ForEach-Object -Begin {$Script:header = @()} -Process {$Script:header += $_ } + $NoHeader = $true #if we did not get AutoNameRange, but headers have ranges of the same name make autoNameRange True, otherwise make it false if (-not $AutoNameRange) { $AutoNameRange = $true ; foreach ($h in $header) {if ($ws.names.name -notcontains $h) {$AutoNameRange = $false} } @@ -156,7 +157,7 @@ $existingTable = $ws.Tables.Where({$_.address.address -eq $ws.dimension.address},'First', 1) if ($null -eq $TableName -and $existingTable) { $TableName = $existingTable.Name - $TableStyle = $existingTable.Tablestyle + $TableStyle = $existingTable.StyleName -replace "^TableStyle","" $AutoFilter = $false } #if we did not get $autofilter but a filter range is set and it covers the right area, set autofilter to true @@ -199,15 +200,15 @@ else { $setNumformat = ($Numberformat -ne $ws.Cells.Style.Numberformat.Format) } } catch {throw "Failed preparing to export to worksheet '$WorksheetName' to '$Path': $_"} - #region Special case -inputobject passed a dataTable object + #region Special case -inputobject passed a dataTable object <# If inputObject was passed via the pipeline it won't be visible until the process block, we will only see it here if it was passed as a parameter if it is a data table don't do foreach on it (slow) - put the whole table in and set dates on date columns, set things up for the end block, and skip the process block #> - if ($InputObject -is [System.Data.DataTable]) { - if ($Append) { + if ($InputObject -is [System.Data.DataTable]) { + if ($Append -and $ws.dimension) { $row ++ $null = $ws.Cells[$row,$StartColumn].LoadFromDataTable($InputObject, $false ) - if ($TableName) { + if ($TableName -or $PSBoundParameters.ContainsKey('TableStyle')) { Add-ExcelTable -Range $ws.Cells[$ws.Dimension] -TableName $TableName -TableStyle $TableStyle } } @@ -248,9 +249,9 @@ } #endregion else {$firstTimeThru = $true} - } + } - process { if ($PSBoundParameters.ContainsKey("InputObject")) { + process { if ($PSBoundParameters.ContainsKey("InputObject")) { try { if ($null -eq $InputObject) {$row += 1} foreach ($TargetData in $InputObject) { @@ -349,7 +350,6 @@ else { $ws.Cells[$Row, $ColumnIndex].Value = $v } - } } catch {Write-Warning -Message "Could not insert the '$Name' property at Row $Row, Column $ColumnIndex"} @@ -360,10 +360,9 @@ } } catch {throw "Failed exporting data to worksheet '$WorksheetName' to '$Path': $_" } + }} - }} - - end { + end { if ($firstTimeThru -and $ws.Dimension) { $LastRow = $ws.Dimension.End.Row $LastCol = $ws.Dimension.End.Column @@ -428,6 +427,7 @@ } catch {Write-Warning -Message "Failed adding autofilter to worksheet '$WorksheetName': $_"} } + if ($PivotTableDefinition) { foreach ($item in $PivotTableDefinition.GetEnumerator()) { $params = $item.value @@ -500,7 +500,7 @@ } catch {Write-Warning -Message "Failed adding Freezing the panes in worksheet '$WorksheetName': $_"} - if ($PSBoundParameters.ContainsKey("BoldTopRow")) { #it sets bold as far as there are populated cells: for whole row could do $ws.row($x).style.font.bold = $true + if ($PSBoundParameters.ContainsKey("BoldTopRow")) { #it sets bold as far as there are populated cells: for whole row could do $ws.row($x).style.font.bold = $true try { if ($Title) { $range = $ws.Dimension.Address -replace '\d+', ($StartRow + 1) @@ -646,7 +646,6 @@ $ws.Protection.SetPassword($Password) Write-Verbose -Message 'Set password on workbook' } - catch {throw "Failed setting password for worksheet '$WorksheetName': $_"} } @@ -654,8 +653,8 @@ else { if ($ReturnRange) {$dataRange } - if ($Password) { $pkg.Save($Password) } - else { $pkg.Save() } + if ($Password) { $pkg.Save($Password) } + else { $pkg.Save() } Write-Verbose -Message "Saved workbook $($pkg.File)" if ($ReZip) { Write-Verbose -Message "Re-Zipping $($pkg.file) using .NET ZIP library" @@ -679,6 +678,5 @@ if ($Show) { Invoke-Item $Path } } - } } From e49b4ee6e86b35caa270f5c2c597c01bb1cc65c6 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Thu, 21 Nov 2019 21:04:32 +0000 Subject: [PATCH 11/25] Add test for new table support in export --- __tests__/InputItemParameter.tests.ps1 | 69 ++++++++++++++++++++++---- 1 file changed, 59 insertions(+), 10 deletions(-) diff --git a/__tests__/InputItemParameter.tests.ps1 b/__tests__/InputItemParameter.tests.ps1 index 06162a6..6eb6f9e 100644 --- a/__tests__/InputItemParameter.tests.ps1 +++ b/__tests__/InputItemParameter.tests.ps1 @@ -2,8 +2,9 @@ Param() Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking Import -asText" { BeforeAll { - $path = "TestDrive:\Results.xlsx" - Remove-Item -Path $path -ErrorAction SilentlyContinue + $path = "TestDrive:\Results.xlsx" + $path2 = "TestDrive:\Results2.xlsx" + Remove-Item -Path $path,$path2 -ErrorAction SilentlyContinue if (Test-path "$PSScriptRoot\Samples\Samples.ps1") {. "$PSScriptRoot\Samples\Samples.ps1"} $results = ((Get-Process) + (Get-Process -id $PID)) | Select-Object -last 10 -Property Name, cpu, pm, handles, StartTime $DataTable = [System.Data.DataTable]::new('Test') @@ -12,6 +13,8 @@ Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking I $null = $DataTable.Columns.Add('PM', [Long]) $null = $DataTable.Columns.Add('Handles', [Int]) $null = $DataTable.Columns.Add('StartTime', [DateTime]) + Send-SQLDataToExcel -path $path -DataTable $DataTable -WorkSheetname Sheet4 -force -TableName "Data" -WarningVariable WVOne -WarningAction SilentlyContinue + Send-SQLDataToExcel -path $path -DataTable ([System.Data.DataTable]::new('Test2')) -WorkSheetname Sheet5 -force -WarningVariable wvTwo -WarningAction SilentlyContinue foreach ($r in $results) { $null = $DataTable.Rows.Add($r.name, $r.CPU, $R.PM, $r.Handles, $r.StartTime) } @@ -23,10 +26,21 @@ Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking I Close-ExcelPackage $NowPkg Export-Excel -Path $path -InputObject $results -WorksheetName Sheet1 -RangeName "Whole" Export-Excel -Path $path -InputObject $DataTable -WorksheetName Sheet2 -AutoNameRange - Send-SQLDataToExcel -path $path -DataTable $DataTable -WorkSheetname Sheet3 -TableName "Data" - $DataTable.Rows.Clear() - Send-SQLDataToExcel -path $path -DataTable $DataTable -WorkSheetname Sheet4 -force -TableName "Data" -WarningVariable WVOne -WarningAction SilentlyContinue - Send-SQLDataToExcel -path $path -DataTable ([System.Data.DataTable]::new('Test2')) -WorkSheetname Sheet5 -force -WarningVariable wvTwo -WarningAction SilentlyContinue + Send-SQLDataToExcel -path $path -DataTable $DataTable -WorkSheetname Sheet3 -TableName "Data" -WarningVariable WVThree -WarningAction SilentlyContinue + + Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet1 -Append + Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet1 -Append + + Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet2 -Append -TableName "FirstLot" -TableStyle light7 + Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet2 -Append + + Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet3 -Append + Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet3 -Append -TableName "SecondLot" + + Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet4 -Append + Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet4 -Append -TableStyle Dark5 + + $excel = Open-ExcelPackage $path $sheet = $excel.Sheet1 } @@ -97,12 +111,15 @@ Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking I } it "Created a table " { $sheet.Tables.count | should be 1 - $sheet.Tables[0].Name | should be "Data" $sheet.Tables[0].Columns[4].name | should be "StartTime" } it "Formatted date fields with date type " { $sheet.Cells["E11"].Style.Numberformat.NumFmtID | should be 22 } + it "Handled two data tables with the same name " { + $sheet.Tables[0].Name | should be "Data_" + $wvThree[0] | should match "is not unique" + } } $Sheet = $excel.Sheet4 Context "Zero-row Data Table sent with Send-SQLDataToExcel -Force" { @@ -116,10 +133,9 @@ Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking I } it "Applied table formatting " { $sheet.Tables.Count | should be 1 + $sheet.Tables[0].Name | should be "Data" } - it "Handled two data tables with the same name " { - $wvone[1] | should match "is not unique" - } + } $Sheet = $excel.Sheet5 @@ -130,6 +146,39 @@ Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking I } } + Close-ExcelPackage $excel + $excel = Open-ExcelPackage $path2 + Context "Send-SQLDataToExcel -append works correctly" { + it "Works without table settings " { + $excel.sheet1.Dimension.Address | should be "A1:E21" + $excel.sheet1.cells[1,1].value | should be "Name" + $excel.sheet1.cells[12,1].value | should be $excel.sheet1.cells[2,1].value + $excel.sheet1.Tables.count | should be 0 + } + it "Extends an existing table when appending " { + $excel.sheet2.Dimension.Address | should be "A1:E21" + $excel.sheet2.cells[1,2].value | should be "CPU" + $excel.sheet2.cells[13,2].value | should be $excel.sheet2.cells[3,2].value + $excel.sheet2.Tables.count | should be 1 + $excel.sheet2.Tables[0].name | should be "FirstLot" + $excel.sheet2.Tables[0].StyleName | should be "TableStyleLight7" + } + it "Creates a new table by name when appending " { + $excel.sheet3.cells[1,3].value | should be "PM" + $excel.sheet3.cells[14,3].value | should be $excel.sheet3.cells[4,3].value + $excel.sheet3.Tables.count | should be 1 + $excel.sheet3.Tables[0].name | should be "SecondLot" + $excel.sheet3.Tables[0].StyleName | should be "TableStyleMedium6" + } + it "Creates a new table by style when appending " { + $excel.sheet4.cells[1,4].value | should be "Handles" + $excel.sheet4.cells[15,4].value | should be $excel.sheet4.cells[5,4].value + $excel.sheet4.Tables.count | should be 1 + $excel.sheet4.Tables[0].name | should be "Table1" + $excel.sheet4.Tables[0].StyleName | should be "TableStyleDark5" + } + } + Close-ExcelPackage $excel Context "Import As Text returns text values" { $x = import-excel $path -WorksheetName sheet3 -AsText StartTime,hand* | Select-Object -last 1 From 3fb3ba0e0e5f0f5beb697f3e7f27db7f83bb57bf Mon Sep 17 00:00:00 2001 From: jhoneill Date: Thu, 21 Nov 2019 21:04:32 +0000 Subject: [PATCH 12/25] Add test for new table support in export --- ExportedCommands/Export-Excel.ps1 | 2 +- __tests__/InputItemParameter.tests.ps1 | 69 ++++++++++++++++++++++---- 2 files changed, 60 insertions(+), 11 deletions(-) diff --git a/ExportedCommands/Export-Excel.ps1 b/ExportedCommands/Export-Excel.ps1 index a8c54c5..58e6ed8 100644 --- a/ExportedCommands/Export-Excel.ps1 +++ b/ExportedCommands/Export-Excel.ps1 @@ -13,7 +13,7 @@ [Switch]$Calculate, [Switch]$Show, [String]$WorksheetName = 'Sheet1', - [Alias("P")] + [Alias("PW")] [String]$Password, [switch]$ClearSheet, [switch]$Append, diff --git a/__tests__/InputItemParameter.tests.ps1 b/__tests__/InputItemParameter.tests.ps1 index 06162a6..6eb6f9e 100644 --- a/__tests__/InputItemParameter.tests.ps1 +++ b/__tests__/InputItemParameter.tests.ps1 @@ -2,8 +2,9 @@ Param() Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking Import -asText" { BeforeAll { - $path = "TestDrive:\Results.xlsx" - Remove-Item -Path $path -ErrorAction SilentlyContinue + $path = "TestDrive:\Results.xlsx" + $path2 = "TestDrive:\Results2.xlsx" + Remove-Item -Path $path,$path2 -ErrorAction SilentlyContinue if (Test-path "$PSScriptRoot\Samples\Samples.ps1") {. "$PSScriptRoot\Samples\Samples.ps1"} $results = ((Get-Process) + (Get-Process -id $PID)) | Select-Object -last 10 -Property Name, cpu, pm, handles, StartTime $DataTable = [System.Data.DataTable]::new('Test') @@ -12,6 +13,8 @@ Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking I $null = $DataTable.Columns.Add('PM', [Long]) $null = $DataTable.Columns.Add('Handles', [Int]) $null = $DataTable.Columns.Add('StartTime', [DateTime]) + Send-SQLDataToExcel -path $path -DataTable $DataTable -WorkSheetname Sheet4 -force -TableName "Data" -WarningVariable WVOne -WarningAction SilentlyContinue + Send-SQLDataToExcel -path $path -DataTable ([System.Data.DataTable]::new('Test2')) -WorkSheetname Sheet5 -force -WarningVariable wvTwo -WarningAction SilentlyContinue foreach ($r in $results) { $null = $DataTable.Rows.Add($r.name, $r.CPU, $R.PM, $r.Handles, $r.StartTime) } @@ -23,10 +26,21 @@ Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking I Close-ExcelPackage $NowPkg Export-Excel -Path $path -InputObject $results -WorksheetName Sheet1 -RangeName "Whole" Export-Excel -Path $path -InputObject $DataTable -WorksheetName Sheet2 -AutoNameRange - Send-SQLDataToExcel -path $path -DataTable $DataTable -WorkSheetname Sheet3 -TableName "Data" - $DataTable.Rows.Clear() - Send-SQLDataToExcel -path $path -DataTable $DataTable -WorkSheetname Sheet4 -force -TableName "Data" -WarningVariable WVOne -WarningAction SilentlyContinue - Send-SQLDataToExcel -path $path -DataTable ([System.Data.DataTable]::new('Test2')) -WorkSheetname Sheet5 -force -WarningVariable wvTwo -WarningAction SilentlyContinue + Send-SQLDataToExcel -path $path -DataTable $DataTable -WorkSheetname Sheet3 -TableName "Data" -WarningVariable WVThree -WarningAction SilentlyContinue + + Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet1 -Append + Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet1 -Append + + Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet2 -Append -TableName "FirstLot" -TableStyle light7 + Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet2 -Append + + Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet3 -Append + Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet3 -Append -TableName "SecondLot" + + Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet4 -Append + Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet4 -Append -TableStyle Dark5 + + $excel = Open-ExcelPackage $path $sheet = $excel.Sheet1 } @@ -97,12 +111,15 @@ Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking I } it "Created a table " { $sheet.Tables.count | should be 1 - $sheet.Tables[0].Name | should be "Data" $sheet.Tables[0].Columns[4].name | should be "StartTime" } it "Formatted date fields with date type " { $sheet.Cells["E11"].Style.Numberformat.NumFmtID | should be 22 } + it "Handled two data tables with the same name " { + $sheet.Tables[0].Name | should be "Data_" + $wvThree[0] | should match "is not unique" + } } $Sheet = $excel.Sheet4 Context "Zero-row Data Table sent with Send-SQLDataToExcel -Force" { @@ -116,10 +133,9 @@ Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking I } it "Applied table formatting " { $sheet.Tables.Count | should be 1 + $sheet.Tables[0].Name | should be "Data" } - it "Handled two data tables with the same name " { - $wvone[1] | should match "is not unique" - } + } $Sheet = $excel.Sheet5 @@ -130,6 +146,39 @@ Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking I } } + Close-ExcelPackage $excel + $excel = Open-ExcelPackage $path2 + Context "Send-SQLDataToExcel -append works correctly" { + it "Works without table settings " { + $excel.sheet1.Dimension.Address | should be "A1:E21" + $excel.sheet1.cells[1,1].value | should be "Name" + $excel.sheet1.cells[12,1].value | should be $excel.sheet1.cells[2,1].value + $excel.sheet1.Tables.count | should be 0 + } + it "Extends an existing table when appending " { + $excel.sheet2.Dimension.Address | should be "A1:E21" + $excel.sheet2.cells[1,2].value | should be "CPU" + $excel.sheet2.cells[13,2].value | should be $excel.sheet2.cells[3,2].value + $excel.sheet2.Tables.count | should be 1 + $excel.sheet2.Tables[0].name | should be "FirstLot" + $excel.sheet2.Tables[0].StyleName | should be "TableStyleLight7" + } + it "Creates a new table by name when appending " { + $excel.sheet3.cells[1,3].value | should be "PM" + $excel.sheet3.cells[14,3].value | should be $excel.sheet3.cells[4,3].value + $excel.sheet3.Tables.count | should be 1 + $excel.sheet3.Tables[0].name | should be "SecondLot" + $excel.sheet3.Tables[0].StyleName | should be "TableStyleMedium6" + } + it "Creates a new table by style when appending " { + $excel.sheet4.cells[1,4].value | should be "Handles" + $excel.sheet4.cells[15,4].value | should be $excel.sheet4.cells[5,4].value + $excel.sheet4.Tables.count | should be 1 + $excel.sheet4.Tables[0].name | should be "Table1" + $excel.sheet4.Tables[0].StyleName | should be "TableStyleDark5" + } + } + Close-ExcelPackage $excel Context "Import As Text returns text values" { $x = import-excel $path -WorksheetName sheet3 -AsText StartTime,hand* | Select-Object -last 1 From d4da73e8f4cbf14c9f0424af3f8c2cf64ed6d497 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Fri, 22 Nov 2019 00:52:34 +0000 Subject: [PATCH 13/25] file list no longer needed --- filelist.txt | 44 -------------------------------------------- 1 file changed, 44 deletions(-) delete mode 100644 filelist.txt diff --git a/filelist.txt b/filelist.txt deleted file mode 100644 index e6bd0dc..0000000 --- a/filelist.txt +++ /dev/null @@ -1,44 +0,0 @@ -*.dll -*.psd1 -*.psm1 -AddConditionalFormatting.ps1 -AddDataValidation.ps1 -Charting.ps1 -ColorCompletion.ps1 -Compare-WorkSheet.ps1 -ConvertExcelToImageFile.ps1 -ConvertFromExcelData.ps1 -ConvertFromExcelToSQLInsert.ps1 -ConvertToExcelXlsx.ps1 -Copy-ExcelWorkSheet.ps1 -Export-Excel.ps1 -Export-ExcelSheet.ps1 -Export-StocksToExcel.ps1 -Get-ExcelColumnName.ps1 -Get-ExcelSheetInfo.ps1 -Get-ExcelWorkbookInfo.ps1 -Get-HtmlTable.ps1 -Get-Range.ps1 -Get-XYRange.ps1 -Import-Html.ps1 -InferData.ps1 -Invoke-Sum.ps1 -Join-Worksheet.ps1 -Merge-Worksheet.ps1 -New-ConditionalFormattingIconSet.ps1 -New-ConditionalText.ps1 -New-ExcelChart.ps1 -New-PSItem.ps1 -Open-ExcelPackage.ps1 -Pivot.ps1 -PivotTable.ps1 -Plot.ps1 -RemoveWorksheet.ps1 -Send-SQLDataToExcel.ps1 -Set-CellStyle.ps1 -Set-Column.ps1 -Set-Row.ps1 -Set-WorkSheetProtection.ps1 -SetFormat.ps1 -TrackingUtils.ps1 -Update-FirstObjectProperties.ps1 \ No newline at end of file From f6c66e21a757cddbb4dd6eea09d5bd0625cb1fbf Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sat, 23 Nov 2019 16:12:29 +0000 Subject: [PATCH 14/25] Sync to Doug's 6.5.3 release --- ExportedCommands/Import-Excel.ps1 | 106 +++++++++++--------- ImportExcel.psd1 | 2 +- README.md | 13 +++ __tests__/ImportExcelTests/Simple.tests.ps1 | 21 ++++ __tests__/ImportExcelTests/TestData1.xlsx | Bin 0 -> 8626 bytes __tests__/ImportExcelTests/TestData2.xlsx | Bin 0 -> 8624 bytes 6 files changed, 91 insertions(+), 51 deletions(-) create mode 100644 __tests__/ImportExcelTests/TestData1.xlsx create mode 100644 __tests__/ImportExcelTests/TestData2.xlsx diff --git a/ExportedCommands/Import-Excel.ps1 b/ExportedCommands/Import-Excel.ps1 index 7f5c5a9..94ec48f 100644 --- a/ExportedCommands/Import-Excel.ps1 +++ b/ExportedCommands/Import-Excel.ps1 @@ -1,14 +1,13 @@ function Import-Excel { - - [CmdLetBinding()] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSPossibleIncorrectUsageOfAssignmentOperator', '', Justification = 'Intentional')] - Param ( + [CmdLetBinding()] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSPossibleIncorrectUsageOfAssignmentOperator', '', Justification = 'Intentional')] + param ( [Alias('FullName')] [Parameter(ParameterSetName = "PathA", Mandatory, ValueFromPipelineByPropertyName, ValueFromPipeline, Position = 0 )] [Parameter(ParameterSetName = "PathB", Mandatory, ValueFromPipelineByPropertyName, ValueFromPipeline, Position = 0 )] [Parameter(ParameterSetName = "PathC", Mandatory, ValueFromPipelineByPropertyName, ValueFromPipeline, Position = 0 )] - [String]$Path, + [String[]]$Path, [Parameter(ParameterSetName = "PackageA", Mandatory)] [Parameter(ParameterSetName = "PackageB", Mandatory)] [Parameter(ParameterSetName = "PackageC", Mandatory)] @@ -37,55 +36,61 @@ [ValidateNotNullOrEmpty()] [String]$Password ) - begin { - $sw = [System.Diagnostics.Stopwatch]::StartNew() + end { + $sw = [System.Diagnostics.Stopwatch]::StartNew() + if ($input) { + $Paths = $input + } + elseif ($Path) { + $Paths = $Path + } + else { + $Paths = '' + } + Function Get-PropertyNames { + <# + .SYNOPSIS + Create objects containing the column number and the column name for each of the different header types. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = "Name would be incorrect, and command is not exported")] + Param ( + [Parameter(Mandatory)] + [Int[]]$Columns, + [Parameter(Mandatory)] + [Int]$StartRow + ) - Function Get-PropertyNames { - <# - .SYNOPSIS - Create objects containing the column number and the column name for each of the different header types. - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = "Name would be incorrect, and command is not exported")] - Param ( - [Parameter(Mandatory)] - [Int[]]$Columns, - [Parameter(Mandatory)] - [Int]$StartRow - ) - - Try { - if ($HeaderName) { - $i = 0 - foreach ($H in $HeaderName) { - $H | Select-Object @{N = 'Column'; E = { $Columns[$i] } }, @{N = 'Value'; E = { $H } } - $i++ - } - } - elseif ($NoHeader) { - $i = 0 - foreach ($C in $Columns) { - $i++ - $C | Select-Object @{N = 'Column'; E = { $_ } }, @{N = 'Value'; E = { 'P' + $i } } - } - } - - else { - if ($StartRow -lt 1) { - throw 'The top row can never be less than 1 when we need to retrieve headers from the worksheet.' ; return - } - - foreach ($C in $Columns) { - $Worksheet.Cells[$StartRow, $C] | Where-Object { $_.Value } | Select-Object @{N = 'Column'; E = { $C } }, Value - } + Try { + if ($HeaderName) { + $i = 0 + foreach ($H in $HeaderName) { + $H | Select-Object @{N = 'Column'; E = { $Columns[$i] } }, @{N = 'Value'; E = { $H } } + $i++ } } - Catch { - throw "Failed creating property names: $_" ; return + elseif ($NoHeader) { + $i = 0 + foreach ($C in $Columns) { + $i++ + $C | Select-Object @{N = 'Column'; E = { $_ } }, @{N = 'Value'; E = { 'P' + $i } } + } + } + + else { + if ($StartRow -lt 1) { + throw 'The top row can never be less than 1 when we need to retrieve headers from the worksheet.' ; return + } + + foreach ($C in $Columns) { + $Worksheet.Cells[$StartRow, $C] | Where-Object { $_.Value } | Select-Object @{N = 'Column'; E = { $C } }, Value + } } } + Catch { + throw "Failed creating property names: $_" ; return + } } - - process { + foreach ($Path in $Paths) { if ($path) { $extension = [System.IO.Path]::GetExtension($Path) if ($extension -notmatch '.xlsx$|.xlsm$') { @@ -193,4 +198,5 @@ if ($Path) { $stream.close(); $ExcelPackage.Dispose() } } } -} + } +} \ No newline at end of file diff --git a/ImportExcel.psd1 b/ImportExcel.psd1 index c602500..6288b3d 100644 --- a/ImportExcel.psd1 +++ b/ImportExcel.psd1 @@ -4,7 +4,7 @@ RootModule = 'ImportExcel.psm1' # Version number of this module. - ModuleVersion = '6.5.2' + ModuleVersion = '6.5.3' # ID used to uniquely identify this module GUID = '60dd4136-feff-401a-ba27-a84458c57ede' diff --git a/README.md b/README.md index e5f7f52..dba7450 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,19 @@ Plus, wiring the [PowerShell ScriptAnalyzer Excel report](https://github.com/dfi ![](./images/ScriptAnalyzerReport.png) +# What's new 6.5.3 + +Thanks again to the community for making this module even better. + +- [Fix import excel headers](https://github.com/dfinke/ImportExcel/pull/713) +- Numerous improvements for DataTables and exporting it to Excel [James O'Neill](https://twitter.com/jamesoneill) + - Names, styles, proper appending +- Handles marking the empty row on an empty table as dummy row +- Re-work code based on linting recommendations +- Update existing tests and add more +- Support PipelineVariable thanks to [Luc Dekens](https://twitter.com/LucD22) for reporting and [Ili](https://twitter.com/ili_z) for the PR +- Fix quoting in ConvertFromExcelToSQLInsert [beckerben](https://github.com/beckerben) + # What's new 6.5.2 Thank you [uSlackr](https://github.com/uSlackr)ill diff --git a/__tests__/ImportExcelTests/Simple.tests.ps1 b/__tests__/ImportExcelTests/Simple.tests.ps1 index 12049ec..a8a48fe 100644 --- a/__tests__/ImportExcelTests/Simple.tests.ps1 +++ b/__tests__/ImportExcelTests/Simple.tests.ps1 @@ -42,4 +42,25 @@ Describe "Tests" { $data[0].p1 | Should be "a" $data[1].p1 | Should be "b" } + + It "Should take Paths from parameter".PadRight(90) { + $data = Import-Excel -Path (Get-ChildItem -Path $PSScriptRoot -Filter "TestData?.xlsx").FullName + $data.count | Should be 4 + $data[0].cola | Should be 1 + $data[2].cola | Should be 5 + } + + It "Should take Paths from pipeline".PadRight(90) { + $data = (Get-ChildItem -Path $PSScriptRoot -Filter "TestData?.xlsx").FullName | Import-Excel + $data.count | Should be 4 + $data[0].cola | Should be 1 + $data[2].cola | Should be 5 + } + + It "Should support PipelineVariable".PadRight(90) { + $data = Import-Excel $PSScriptRoot\Simple.xlsx -PipelineVariable 'Pv' | ForEach-Object { $Pv.p1 } + $data.count | Should be 2 + $data[0] | Should be "a" + $data[1] | Should be "b" + } } \ No newline at end of file diff --git a/__tests__/ImportExcelTests/TestData1.xlsx b/__tests__/ImportExcelTests/TestData1.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..7f554adb7cb810a4ef8ea8fc1d14f74bb68a30a8 GIT binary patch literal 8626 zcmeHsg;$)(^7g=>!5snwx8Uv)EWrm)2<|YrThQP>f#3uJBm@gOxH}{`!5xCT4*`CY zy}RG;X7~FG?(I4A_L+0ur%q4z^Hfz=fs}wqga8x(8UO&G0hk_SSsNk%00~F{0096E z@uiHTgPVnen~|2clZC4RhnKw_^?M{l<{SVb{Qdup|Kc4eNg7n`M@J-3WfXT+Lu*z7V(4zK8@q9jS@`Q+OYTv$)P%@7y4!V;RX7lxKl8e0S(sqj6l{1kOoq}P)GW^MJ;_w#9Gj*C76 z!5RdJtc}=TW=jRp1dmMvK;Y3Wm6PM=^M7*u zFV^5+{(1>SMXi$yGwkr$kMO?B$%O=5X(i7m&l+j8`~wx{acW}o=*bsanJ93z9)Av!?;MHsPoT996k%8NzQt1^U1Y0dr8u<}~LoSiqr z839voKWt-3MhGkKjinLwxtdzdl==19(VSmD)Yh~XwkbEwb`hcVHZr$sJC)67CAjrt zSIz9xpyk8A;u(J0%aC&(pjXXzJecL(C5YZx+;`L;98FcY2#-+z6v^#QFQ*g`0O&*o z0C3F5GBb#w&(j9Vqz29B9Rgs+Tj?t!Zd?caStjFVh}0vet~1v6&_V*>~T zB>>CVer3Y**25YyMg>i6n+Cd`o|cQ_`pZW~s*-z+-x{o3*54b=ts~75?<%Pu-+9>I zztYZ`hRVy`L_yzMfp3ChFT$&q0z?xaVl)$u_6xr+7>(JZyEanthdCMy2sfh1F5#>u$Omrvl>zSGdv33c^IIt{IU ztTX;eTbFtr`H_P>Y1zEgXCxCly>4?gqPZx;AZ#4}+oJE77f`$$r(MXcsB{0aX;4d> zuC-0tNXBt+QBS&gBeb?Zh4mYjQ8s#Fi_Wduv&6TvlBg7!3SSPFL@@NtEBp4P6)+Zu ztKxA_)XpB^18mB$FHb3GDeh0VN_A{n6o7=i-Z4M+8D%o2qeldy1pP@(IXgymkEFvC zShn)hWibW1z&9Pe!Zc z4ice#?)Va?x8ifSsM+lo*2y;fVT{0Ku}jpoS}c&ETrSPNttI$o^m2_FXAEn=DV0Vt zj)$<3UP>+~@5}j*J{9rKK5zMcLd6_QpJKt)yZmUTpr{gGN&~NyNC}y2-7a&-8J#gG z68G*9TMW8~t`G8DaeN++_*Mi^e05FbwXQ@*Jqe&WIofo|b@bctyja8un;I~S%3$lw zecn8oFw-E3Y?WQ1mM-M2=g~sFxx3<1(AXaC(JNH}tW`o^sZq{nL4K7T%qlWe$S+oq z@%o|OAhE>BgQ-I{feJGZ-Xg}j2pD#{^ZU6~F5k?O%}AMSL;Z$zo^fZ%y}Qwl)!F=` z#!Vqc><0cB*SA|)w{SWAQ*1#JNhzmrku|_0(nA0m0$gnW2}*yJ+#dl70iG|yCHvn! zN;FiIy0~zgG48^-JTp9q@MhdNY4@~uanSm!S>_mNc>T|o$R9TtJpZP|33LqeKK$D2 zamkOp3M4phXDy7vNAe-CI}}BB{CfHoh-SK9`Y8A*G6DYH&TjEO26nnDLA?Z|k1d-} z==&8j16g?92U^*)`mr!R+aWG@9$VKD$^p289;{vuguT|>D-Eu$t))(9vD~ht{{fx4H(^;pkcjgm%BhaY5HNQ;ynaz&x2uZP!uaYD&iOS3v;6m?|VuW zzyfjIc%Rm&eYoN#eKWw)I(Nc0cy?&H-rqa91V8D2Ql>;a;5#RrF1W}504e;9-~F?z zwS|S7E9Y+$_fJQinWPk-!G+skkgpo_3oQ*D8WFh+0zX05s>kKkaxP z0EGe%kkY7-9QaU7CdOQ8){0<~d2RMAA51&*-|G+jt03TX?k*G8sUBJD)E{i`Aj-*De>j9ZCP!j2d&luttmUJjhc88L{FB} zB9G5VH}!Hf%lS#%Ln<7jd$#d8$0S>pYM!EUP5LUD?{jA|#5^4GWA=BRCi7(D@Mgy8{JzSzicXy#^dVz6=K|d@p^(SjBe6l-qj5SiC`t3EZ@~ z>qoyE;~Qe|s2hy3X2x%D%lq|58#xo4r&b1AG8h=bUaqJ3isr?pFh zH4I3Zh{1Y!gruE3Vi!hm*ErS2@St3M#pjid?*S^Tm{FL}Pj|*~=ZMU_zJi(DIDH{g z_SyznemU^{(F8_Mx$gW4-?ts9@)^3?j``moT zODP67^P{~W%L(bbTRp?iE;Q$O<{^^-8Sz*x?+!2h4z-Cx+%KXe`OFGm4k}%BxU-PU zJZ6Tiaxjm|oM*9=mD)B!ILisZ7NteQjaYZy0E}&A?g?oY-$geps(XuV$$uqTI|*)! zD%@lBQ2)HZ{zfu4YYTe|&flKD@oVqJ*JyG^m=qAJ`79otzIvN#l$1-v)q%nECwFo+ZWLS)e;yW3c^D zntSK(f@j~4);kTnmbJ@$OQj$@_n5dFEiAFF%~B|6i7}@4SqI%a;$8~Mki}GD)&h-E zQaZ?$VX!I4_Z1Hf-5yr5Vu0_bCbbprL}{!T<|W;t3WnT@wa!ZEh|n#K14^3N6O(Li z(MPMkW0%bM`2N<{47ZykwVcGGI*hU#C@*9ja_)KRm5u$LkGh_0x7&_UqlM`C78n5w z^?T2EZ}nQCV;>Q$`GS)_K&M4^lN}OFut2cM+(z9)?Lp$j5hH`Dddi~s(5W1)fbuXZ z%!Xw-jL%P4B=kGOvn)Sa?M~$o8olhCQrb5J)t-StvI;JBVH}|~wx0E~MCKh^aRiH) zAy1kiEW_#vSjBr9n##{<1vm6!4tOL0fruLP3akCym}(Bpks^fb4xU|pm70B~uF&?CzBFjbTgGWbB*~$xVPU|BZ zBS#X!2ONqefXhwZ9Nkronb>lR?^sdzkspNG$240jWMU|b8)YIkro?$xmCGZ~4sbt* zM2s`YxEM2Na8%2fMhtdXP`{o%`MPNTxw8;FDeh-ZX98abmw&{kjh;bk4)r|^VOef| z%9d#Jbsm?1_NRQhbOH{0y8}{T-`%jg1z?_gj$2{A|gnFKREo;;Ms# z#Z1D`9$=Cz1V<3v>C0vn>)9P7WlU!X-~b8bb(#s@tjBf_M^-ZZ@EmyLiQtNY9RKq8 zCP^fN*Rs0#g(iVf^zoju>?1SxU-=B@2&IC*t{Q)D@ADDl~12%L7R*K>Yx{=_z| z$uDSt@$h6TTdk>LgO?`hU=X>xQQGqrQqyP*Dp%p0dIM9vEy57(RXTqv+k6ro`q&**Xdp-)R@g+pzP)+T(~uTE!J}4hT2Jo6yAz9p2bQB{staOd z)Ewy&b-1pvMXP;G#|OS9*dpzm@4_Hq%MU4q3 z#nFjGgFN1+nrC>)e6zb#e)`ydXVZ2-j?g{xIe~OHcnL6 z#~$B>A?TZo$a&a&?w#T|SleL#8j2Skt!(s#q-F)S+M++>=X{7qopn<)kn_Uc!#32i zMw}U`Sv7BD@0&=dVd=|5ET4t)Q3|o6W;!hF*+~b`uHb_jm)e(TwhR{jc`pi4lNCh^ zYsqhOZmC(#j5k(9h4U)vr$ z$Ax<*F&%&lI~ed-V?&1yj!l5JdU7cDicJS23k_rFt%iE;Zd5%CDMX;7{*kJiBodR$6*C=5bLxwUtqidDi|C5YNF>2?c?3P++WyoT9Y`j=XjO6M>x>MXv{ z1cC%QUv8!&(?I8W6!w!HQiC~b1Rx^Q=~xx9Ce@X9354|6oh*q-tYXw`=GT(ckn~L` zx*|LI&Q&_b!G$=ne5L-pW0HUyd!Q|eigjdzwXNwyni*vAhBkh^U{q)7;DJ+Q8Q8Eg z#ck7E)!JJgaeazL4jp|hdRFvQF&~}VuD97wNDW+?DOcc-4CD?fbZlRJv3*!{^sdP@ zVnFi-xL*iRd##ZDR?j+w;u&hzu6UH9fb6_R`&8IXdAcIUMTqD{oZ-Gq=K6^5A$@kQ zNrh7chO;S=FXD2aX2LLc-h=6!klSiU>gHeta${IsfUG0t!c%7+5h>Vf?}l$5g8L;d z*R}>U+ig*0v6k#^cie!j;C+h1cOQv9l9v`96<|^`0S8#paO3@9t&=3v2C-VK7~2QM zn4RJ$DnjX?zIKYEu-IOzJgjNQFgb%)kvI`_vn2Uy+lf=6o$qeliMWJO(W)Klo%C;m zxQulc>XCDG+pdeJ1UHkAMbsW*&Lu`mT5U$P7R9i8G~qySbuOyPZ!Kk{o__@wT~l z3SobQ@5z7_ExkIQm{7J~rIS8S`=oktp0pWf1kzk9;gdMUgwuCV?#Tb`$|6XeK$i=r zaUc9k_&c4gOFGQeeE8*5PN)2Q@rv4jsI%o(VBMp19URV{b~xb>B@kA+D+J zB1TC(&fyP7sM;)wc{b?6s(DelJOO^hbVi920eR!FIR-w=5!y2;l)eL~6iMShW{xla3o$q$SP4x;L+R~WgIGFPt? zD(3k!S*!eIIt?o21t3x{NCr6eLYX$WwHaI4?4DvPIkM{0yuyv@W}PNG>c^!Low z`z~RI?bluigk&wSN8KdHiz}PnI#HwXPo!)UGJojOR-?iy&7-_Ja`sfl zESaoLYN`smdJFqlC2VR}c;#QdoSYdQwGA~ks?5vdNY1Ra1;>W-qwe;2Au%kW>^%BX zULEU9R8B&mn;TGU!ulxSW9v3B3@r+TFAff_gZX%{e?b!>-?jJGifLw@OYM7bu zf!g;d~cxNlXI4;^XD16+=mh61!VF>pVa4 zQTOM#Hn8GlSh}mc!}!B~$NxC4Kjwewm4lT2Zs6~Iygz_H=M=am{?gU^ z75Hm!<4DsPzlYC1@c_Uo+`>PC m>96p=yTHG~4JiHs|J@;il#t=43jjQTe*)q0nu6-*um1x!x&aaZ literal 0 HcmV?d00001 diff --git a/__tests__/ImportExcelTests/TestData2.xlsx b/__tests__/ImportExcelTests/TestData2.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..fd7996700553b2b6158ada76a4b7bf7aa8a9d57c GIT binary patch literal 8624 zcmeHsg;$)(^7i0Pa3{FC1eah5&Hy37eQ=$@A!x7wL4pSe?yx{`8(afHgAN*ky95dF zo9x~FvYXxSFSxho%-d(qd7nBx-Op21T?JG@LM8&B0?+{f03E>mAk)Se0RV_Y1^@^F z=!gb#&Q5M1CpVL4-Yy`B5x1A418pucB5O7P5&r)F#((h+lqU|Wck|*Yd{g``_k~M& zvF0)Qqy6B10(MQQj-I!Dr4|NRwzl_KkvDjw_cuTC}jE zf(ANtj46eAdi(d7prqspV12#AY$D3XeB>r3F;?#Ysjdy(T7vScGRox?HpC=Sf$N#` z{m=22`HDLp4E)nv&ONrTTqw_8d?@Lq8uV>zk-E z;B~VQv5g6rLDu6Sy5Naf0MI_FmZXB;>C?*|Y2rN9;iE2E*bUPvAyv;ZrDbzgY@DS! z8NDOtN z1KZ-hdt)00AqU6F+X4J{r~ttIJrV%;H(A!{@G_jixuyzN9Tr@cCSZ^Qgopdb^M7*u zFV^5+{(5;7Am}F6d_1Y z1KRw*4=unXVs-}TF4hFgqX>w^8R|VN!cwkX-O<>Y!O2ft%U65wJ*Lm6FVdbWd$W49 z#j=+*7U!r8E;BrtJeIG<`^5c%0)w!CDvU%jEl9slO>fEkvJzohR(ro9tg1mcd*|(^ zcL6iWh1)pN5u&Pl6KTW)5OeFfO1}XIy7Mav9c>#?+bZ)cuo%6!iKRowsr)-A;jJH+ zdd7ejy&%CQ|EH(@OxfoF`n7_`!zh4n0N!0J_lt zfCuoM@p9ntbOzg-J3HI|h+E}4M$UO6L@!Nj?~zW#dxdB)inm!`WmgEcl#0PdhZQ+U zRjV;m9~CO;j07y(6Ha)DQMijy;#1zt_irxw`ib6FIa6+CmB|b^g$`gm!9B#(dwt*$ zde=S#V*;a&G$%Z&S?4(GKs#IA`?jp^sRe^6dT#`P)~wgs~UOLvZqT`}^uiIozECWMrq zVLbLF+`eXnI6j9DBEx0MIJ)An9aGRs8zGkj zIB#pOmH-EumA_lnejioGtc?Sv5ZZEN6XbbegCN(m&ci%4Ta;(hq0Dy7cQX10+zwP9 zO;%h|tTU8$ z+2Pl(VA!OpGo!`n#Pf_Mm0k-0-pukB`sdPg3eU;zC0tzS`Pu?@IbAddIUBGlsJx^< zNy!dKSNkdg@|z?UKS3gnPTuz~E`QaG<1ySRn!?F-Un!ItfhiCXW^Cw@Y2R~r<>cna zIZU0?m7qdGgO9`urRV(X@iL-w{lxC^Y5Xg zOpT=*n-RV)!rPr$=TA~lX%=}H{@5k`CM0Tsg0(+tAfYg94pWj_NgXVG1WR=VCY{XEI<7O5e{MeSPzmEen~wW?Ri|)rjdUw!1OGyEbow&UC~c z2eB3xCEl13%=Q@?G)LdDcz_RM$1chnBvR+wF`Q&R_mm(Fm|EPpW8iT{b}g=mG=;nAqw3;=mVjDbXg%Ba z1JSIQ5L?HKR#6}8`+pT%kW^yIDO_aD@Q6eKKu3U!?LR^3uaf&SKq0{MMYxs!?oqC# zrqaWU*M@Z$&g=QkgBX9#jfZ|uXZHd6U@hAMGo66{*)k=2vytv+6&@t#Fz>^WevfaD zaMzFs&pSDaUlSnv5IP)+qd1S8jv%3%?^iqweu_d!u(z{YwvUCI4k2ukN*LhGA`xdOf7Ub+CTKUx>&|Zn8KWM8JLuusFM-#uwD&54Ya1G9)7h*x?wjNmE>PbG zd((`cl4B@I;CKVZx2EVgE;|)2&`(;wTd8@E+IQw%V{cHEsXQ!wBLz3{m?hT*A)oN&6}p#T76@HhVO&k!3B z$PL2t`^5LdQD-FT#lGXk>tE(L7uWS?K?O6ICTYXMm34me?8i1m;jPQG&^d281mI9I z-QZOqPs~2Nzk|qJx^ZKHksb3(>347pm9q)h<8?^JO{5z}qX{g$la6F{@Wx4b&)Dw1 zvq`YE35y0YDHf~BL+p10`53^gP2|NC>=H^z+)cd&qp2m2j`G`{k$m)oVQ@5++dM@- zW57--)auZWl*35cr=`Gj;`4tyJa1@I;D!7G+$KHs1_+9Y$mGm_X`7RnNbfbuUT{^} z(fVmA0t@{4^70awhkySrQ;RM1`I7>VK+Dg)e(&!xM#xDex25jGd6yz=MTQE4oLTQJ z=)BjnHlUqhG_TZrbhWvusVoV`p_Au+0_09sqf;g^nek9^Q32-`m(NktRsz%-^{4UQ zV*AYKtGm^n%ga%WhmvxJC-$0&OGBA5J|?MgF5dTINzal15kWXRAIFhbFO=s=!3AMk;t#?Gbe#eZF{~b7cxO0YLnQV|qZIM2bfjl@& z5#52Huo@(N&}|GEUI&&Dc3N2^7JeNmT1QcrBw+T0Mfkgur$_f;`uKFkS8~4%vA0QdDEW@A zMTuLL*9QQ{vYo;&+Iv0fdSyey?ETUYOzB_Mb=p|apEx&PTN^524n3u%{a@*EJMWx<2wgseGiG!zq~@j)0)S6H0iRTkd+ zgYg{)(fenSuH+qZl4+Dg7uZR9(Zk{!JFG;4mYJjb6}uSTlk`(jhb*O%a1>}&kTE1& z8V8#LeP8m^G3?pu7^eF^oI3&d#%Gp4hT$>kZ)&c8E+{ z0^29eIGnOQEp1g@df^TI=mUN!Kp>(Pqte=7FSf=QdQD>#tLRG40@EZqfpZuEvuWcq zHXLQ0%ipAe?g|-R*Yon{CmESW>QZW5c$xPMs@8w!$etFa<;jxty*t`I4TnkwoNZlo zo76Pbv8yl;mn>D-+ta4VmdLSq z`vY#}a=^Duf$SG+T5~Z~pszTu2_g$cIw!QD)pF6)Wi4_M8#9vpYpPX|X9sw{g+xp; z$$?Fow76^K%p-=oK(w#sPezs;f9o!`pO*BqWH5uTgV#TzWTS7`hFfz_OH`ik5p{c% z_x&FiNBnGMIjGUHWJy$c;=J&23Kw65#k2T zm#9g$8I&#FgchjMZVbAfb&3zkfuE5JhrjcOep8br$^CX@az8tA+KYyZ5j;)%U*LJyFLo;+_OeETJ)_fupI%XiPAhn@%!RFqhQ|_cx_hlg3iNfky4qPWAiFFV1D`(pvq3 zhL{gewz4!@t2YGb5)Xz^dRt^YUm~}TN2Bo;FK9NiG}$4H(qE=OO66QkWZ+tNWtL{) zpN}2G)|UgpIx=3Xo^aOK5j7$cXW zT)3q#dAL+Dwd=q2%u_D~m33~C%uLmaQq!GG(*#$R$k_Uo@m!kjxSQ@ca3>{4|B34c zCa)tgvDe1MibC5)xXipvm=#sxrUh|PZCYz|CFW?_6Q8#NC20sia~=WOSU2stW>;@J zciYl7g?uiCXtxhByc4{^q^q3bBgr>@`+-GZ`FrT`QlT3 z6MMK!xB`-J1jngz9XVbE;z{YRr$6SPdFP7fCO+WB-^pMb1|!qVQl|-8)vk28EA3sT zE@zyh>T08jiETp?+Z4vn*VX0WKzkDz7!?BE8Q}|hS4AAZapk#YI%G4``g%e%@ePAm z6wo6#)iSH=QDo)EaSaX{GL5TwW@c&{_sI_p;mws9b02c z=+e>siHPKJC5!Yx=0|<^$DF&$nU~i?i>=dEXr4h5J}vG3d*!qAXnZ{%j6tFy&dUL<%z~-m?&`9Q^vSP!F=_!?#t2JMQccR!rkH4RI%T zuMrH*#uPkkf9s#&K3L!28VSXZic&TCNLsggz1D6x=jVEePn&sDH6`T!%3PE? zm+4ps7m_4TY77^h6NTKk0_{lEY$BU&?98XqEE1M(=wrVWj6a__z;ubMv^TCvaoe<1 zxAA_0_+^Gp0Rv+_YF_+QIUj@1p});fM8m!!L!rPa35hSL*tv5}Z~L(H=zS|BVo3W2 zX}=ht@k%KxS>GmvN)at{SMs&8ko=-n=SVsj4xxphm2YMX4Nhc zSgz*8zKAOW+Hs%w@-Sz!LvCxGY1@L8C{3>$1LU2tVNYH8#U5Y3@^1cI7(6KTZGCG< zyVDL$9%tF%cE=3~YQIla{Jw~|h_a&ir~sRm1!;&a4KLRJ8ahonYZUX018e)B47*$M zL`@_eIM7LT6c*D@lZP|w9HwCOGV(zL!#rue#&-OSc=!8TcVb>qH1t}hCKtooAYRkw zuqKq87adn+Gs2sRC}Nt`>GfTbnNn7l4gu!G&LF?n*Il0T=Xm5&3lEG-Y<3`3qmsI0 zJi40pUSR=CT+$z3cq&kR?AqW=HT=Ms$}+4Ir|Oharo;DO{pez53&E@V{BXHUA~dS5 z3h^NZg!KZrwmz4#I&PJ{{E2n!A>@7krMxsOk@Ru-m+~=?-ZiJ z2;Y+-YkEdaK?#v8zZw@q{?2L5vOHM}o(SXxD3Qz?<+#)LGIx~!mQ4!N#xdl;X*>Y` z68%AE8#6G-Qrit|>ty{qtL5LwV0Qf|f(Lt|e`qK%icn18M%Ktii`bq;O;FlbRd9AT zDjxnO^`PDMy=V!VIu(}Q?DI#g`M_qyw$S0L+PM((=v=LFIqthjW+ZjBJtU~{ z$Jvj<5k72|Mk@}3IkYcoR;KJ9vYb&rh)8(rwBu9sAr_fEF|9`y$*$1r{qZHpT11S2 zJMl{liS=1{z`?brkN4UVe8K-rkWDCy_Y~kaaeKH*@!_|2OJ@rp*x3cbW8n-2{n6a{ z-(?-Xb_6_Wq(WCGI+Q)B#Il!Cf7H$~D&5Grbx7vFSyQ(YjA*YjkFuB}n$3EpOGVPE=~WC=o%t6w;ZNLK_yBT|?T zW3E8LIDW~4!fk|TbDPJ3ZX_(4!O%9`=&AtRv!NcgMseHaZ7RuBS-^NeIXX_oO ztX^Wjm+m~=ElO#(8vr$MU>38Jjg%m)C6*-b0EK%{Ik>+8S0X1I$2pw#N!vF%9;!n} zW>7T_qOiS8gJP2(C~yxMTr@701C#m&B~%l5)r4IWicbB6Znl>0`IZ%^xqC!=p^bQG058WExtET3s2R#<%;JO*)u;@pJs#jaRu@?aau$P(3LB?sT(kI6w^(+? zhiad9hg$n7ws_g28_#%4JzMx}S$u_}zAJ?@CF#t6LuUy~uL{4OK85m1+^wH=pP%?> z`g30ySqm^N-__h<{pmUp5V_!<|KEG#e;(JL^S^Y;fhvDD@b@m>pTHk;3S1L^>FNCn z{I#?36WR(-wSMVy{0jbirS>Nj0AR!X9sK{P+x}|j*Ye#@ONQA0ZxR0}=KX5r*AmT7 zEA6=dTCn-mz^_T>PXm%9zZ>|Oa{dbaHK6~5Vw3*|`fGUq)xzK7=TAHUunf2Gk7)WU j{O>OCuW$pZzrg=+h(Hw-_~`-wnD9^Fk1{*Wk6-@>vFP3h literal 0 HcmV?d00001 From feb493e3970d20db30cb26ff3f5b0fa74e063b9a Mon Sep 17 00:00:00 2001 From: jhoneill Date: Mon, 25 Nov 2019 01:01:55 +0000 Subject: [PATCH 15/25] fix naming consitency (case mostly) --- CI/Test-SingleFunctions.ps1 | 44 ++++++++++++++++ Examples/AddWorkSheet/AddWorkSheet.ps1 | 2 +- Examples/ConditionalFormatting/Databar.ps1 | 4 +- .../FormatCalculations.ps1 | 4 +- .../MonthlyTemperatuesDatabar.ps1 | 2 +- .../SalesReportWithDatabar.ps1 | 2 +- .../MutipleValidations.ps1 | 2 +- Examples/FormatCellStyles/ApplyStyle.ps1 | 8 +-- Examples/Grouping/TimestampBucket.ps1 | 2 +- .../Merge_2_Servers_Services.ps1 | 2 +- .../Merge_3_Servers_Services.ps1 | 2 +- .../MortgageCalculator/MortgageCalculator.ps1 | 2 +- Examples/SQL+FillColumns+Pivot/Example2.ps1 | 2 +- Examples/Sparklines/SalesByQuarter.ps1 | 2 +- Examples/Sparklines/Sparklines.ps1 | 12 ++--- Examples/TestRestAPI/PSExcelPester.psm1 | 2 +- Examples/TestRestAPI/TestAPIReadXls.ps1 | 2 +- Examples/VBA/HelloWorldVBA.ps1 | 4 +- .../Add-ConditionalFormatting.ps1 | 28 +++++----- ExportedCommands/Add-ExcelChart.ps1 | 4 +- .../Add-ExcelDataValidationRule.ps1 | 8 +-- ExportedCommands/Add-PivotTable.ps1 | 2 +- ...re-WorkSheet.ps1 => Compare-Worksheet.ps1} | 12 ++--- .../Convert-ExcelRangeToImage.ps1 | 10 ++-- ...lWorkSheet.ps1 => Copy-ExcelWorksheet.ps1} | 6 +-- ExportedCommands/Export-Excel.ps1 | 14 ++--- ExportedCommands/Import-UPS.ps1 | 12 +---- ExportedCommands/Import-USPS.ps1 | 3 +- ExportedCommands/Join-Worksheet.ps1 | 4 +- ExportedCommands/Merge-Worksheet.ps1 | 2 +- ...ove-WorkSheet.ps1 => Remove-Worksheet.ps1} | 4 +- ExportedCommands/Set-CellStyle.ps1 | 4 +- ExportedCommands/Set-ExcelColumn.ps1 | 2 +- ExportedCommands/Set-ExcelRange.ps1 | 8 +-- ExportedCommands/Set-ExcelRow.ps1 | 2 +- ...otection.md => Set-WorksheetProtection.md} | 0 ...ection.ps1 => Set-WorksheetProtection.ps1} | 10 ++-- ImportExcel.psd1 | 10 ++-- ImportExcel.psm1 | 2 +- Install.ps1 | 6 +-- __tests__/AddTrendlinesToAChart.tests.ps1 | 2 +- __tests__/Compare-WorkSheet.tests.ps1 | 16 +++--- .../ConvertFromExcelToSQLInsert.tests.ps1 | 2 +- __tests__/Copy-ExcelWorksheet.Tests.ps1 | 10 ++-- __tests__/Export-Excel.Tests.ps1 | 28 +++++----- __tests__/First10Races.tests.ps1 | 8 +-- __tests__/FunctionAlias.tests.ps1 | 2 +- __tests__/ImportExcelHeaderName.tests.ps1 | 46 ++++++++-------- __tests__/ImportExcelTests/Simple.tests.ps1 | 2 +- __tests__/InputItemParameter.tests.ps1 | 2 +- __tests__/PasswordProtection.tests.ps1 | 2 +- __tests__/ProtectWorksheet.tests.ps1 | 2 +- __tests__/RangePassing.ps1 | 20 +++---- __tests__/Remove-WorkSheet.tests.ps1 | 12 ++--- .../Set-Row_Set-Column-SetFormat.tests.ps1 | 52 +++++++++---------- __tests__/Validation.tests.ps1 | 4 +- 56 files changed, 249 insertions(+), 214 deletions(-) create mode 100644 CI/Test-SingleFunctions.ps1 rename ExportedCommands/{Compare-WorkSheet.ps1 => Compare-Worksheet.ps1} (97%) rename ExportedCommands/{Copy-ExcelWorkSheet.ps1 => Copy-ExcelWorksheet.ps1} (97%) rename ExportedCommands/{Remove-WorkSheet.ps1 => Remove-Worksheet.ps1} (87%) rename ExportedCommands/{Set-WorkSheetProtection.md => Set-WorksheetProtection.md} (100%) rename ExportedCommands/{Set-WorkSheetProtection.ps1 => Set-WorksheetProtection.ps1} (89%) diff --git a/CI/Test-SingleFunctions.ps1 b/CI/Test-SingleFunctions.ps1 new file mode 100644 index 0000000..c8622cd --- /dev/null +++ b/CI/Test-SingleFunctions.ps1 @@ -0,0 +1,44 @@ + +Function Test-SingleFunction { + param ( + [parameter(ValueFromPipeline=$true)] + $path ) + begin { + Push-Location "C:\Users\mcp\Documents\GitHub\ImportExcel" + $exportedFunctions = (Import-LocalizedData -FileName "ImportExcel.psd1").functionsToExport + Pop-Location + $reg = [Regex]::new(@" + function\s*[-\w]+\s*{ # The function name and opening '{' + (?: + [^{}]+ # Match all non-braces + | + (? { ) # Match '{', and capture into 'open' + | + (?<-open> } ) # Match '}', and delete the 'open' capture + )* + (?(open)(?!)) # Fails if 'open' stack isn't empty + } # Functions closing '}' +"@, 33) # 33 = ignore case and white space. + + + }# + process { + $item = Get-item $Path + $name = $item.Name -replace "\.\w+$","" + Write-Verbose $name + $file = Get-Content $item -Raw + $m = $reg.Matches($file) + + + #based on https://stackoverflow.com/questions/7898310/using-regex-to-balance-match-parenthesis + if ($m.Count -eq 0) {return "Could not find $name function in $($item.name)"} + elseif ($m.Count -ge 2) {return "Multiple functions in $($item.name)"} + elseif ($exportedFunctions -cnotcontains $name) {return "$name not exported (or in the wrong case)"} + elseif ($m[0] -cnotmatch "^\w+\s+$name") {return "function $name in wrong case"} + elseif ($m[0] -inotmatch "^function\s*$name\s*{(\s*<\#.*?\#>|\s*\[.*?\])*\s*param") {return "No param block in $name"} + elseif ($m[0] -inotmatch "\[cmdletbinding\(" -and + $m[0] -inotmatch "\[parameter\(" ) {return "$name has is not an advanced function"} + elseif (-not (& $Name -?).synopsis) {return "$name has no help"} + else {return "$name OK"} + } +} \ No newline at end of file diff --git a/Examples/AddWorkSheet/AddWorkSheet.ps1 b/Examples/AddWorkSheet/AddWorkSheet.ps1 index c4e798c..dc7fbbf 100644 --- a/Examples/AddWorkSheet/AddWorkSheet.ps1 +++ b/Examples/AddWorkSheet/AddWorkSheet.ps1 @@ -7,6 +7,6 @@ Remove-Item $xlSourcefile -ErrorAction Ignore #Put some simple data in a worksheet and Get an excel package object to represent the file $excel = 1..10 | Export-Excel $xlSourcefile -PassThru #Add a new worksheet named 'NewSheet' and copying the sheet that was just made (Sheet1) to the new sheet -Add-WorkSheet -ExcelPackage $excel -WorkSheetname "NewSheet" -CopySource $excel.Workbook.Worksheets["Sheet1"] +Add-Worksheet -ExcelPackage $excel -WorkSheetname "NewSheet" -CopySource $excel.Workbook.Worksheets["Sheet1"] #Save and open in Excel Close-ExcelPackage -ExcelPackage $excel -Show diff --git a/Examples/ConditionalFormatting/Databar.ps1 b/Examples/ConditionalFormatting/Databar.ps1 index 951330f..d5292f5 100644 --- a/Examples/ConditionalFormatting/Databar.ps1 +++ b/Examples/ConditionalFormatting/Databar.ps1 @@ -22,9 +22,9 @@ Set-ExcelRange -Range $sheet.Column(4) -HorizontalAlignment Right -NFormat "# Set-ExcelRange -Address $sheet.Row(1) -Bold -HorizontalAlignment Center #Create a Red Data-bar for the values in Column D -Add-ConditionalFormatting -WorkSheet $sheet -Address "D2:D1048576" -DataBarColor Red +Add-ConditionalFormatting -Worksheet $sheet -Address "D2:D1048576" -DataBarColor Red # Conditional formatting applies to "Addreses" aliases allow either "Range" or "Address" to be used in Set-ExcelRange or Add-Conditional formatting. -Add-ConditionalFormatting -WorkSheet $sheet -Range "G2:G1048576" -RuleType GreaterThan -ConditionValue "104857600" -ForeGroundColor Red +Add-ConditionalFormatting -Worksheet $sheet -Range "G2:G1048576" -RuleType GreaterThan -ConditionValue "104857600" -ForeGroundColor Red foreach ($c in 5..9) {Set-ExcelRange -Address $sheet.Column($c) -AutoFit } diff --git a/Examples/ConditionalFormatting/FormatCalculations.ps1 b/Examples/ConditionalFormatting/FormatCalculations.ps1 index 3c77b6c..3b80bb1 100644 --- a/Examples/ConditionalFormatting/FormatCalculations.ps1 +++ b/Examples/ConditionalFormatting/FormatCalculations.ps1 @@ -21,8 +21,8 @@ $data = $( New-PSItem Westerly 120 New-PSItem SouthWest 118 ) -# in this example instead of doing $variable = New-Conditional text .... ; Export-excel -conditionalText $variable -# the syntax is used is Export-excel -conditionalText (New-Conditional text ) +# in this example instead of doing $variable = New-Conditional text .... ; Export-excel -ConditionalText $variable +# the syntax is used is Export-excel -ConditionalText (New-Conditional text ) #$data | Export-Excel $f -Show -AutoSize -ConditionalText (New-ConditionalText -ConditionalType AboveAverage) diff --git a/Examples/ConditionalFormatting/MonthlyTemperatuesDatabar.ps1 b/Examples/ConditionalFormatting/MonthlyTemperatuesDatabar.ps1 index d75cb1d..3c374dd 100644 --- a/Examples/ConditionalFormatting/MonthlyTemperatuesDatabar.ps1 +++ b/Examples/ConditionalFormatting/MonthlyTemperatuesDatabar.ps1 @@ -20,6 +20,6 @@ Dec,44,63,46 Export-Excel -Path .\test.xlsx -WorkSheetname Sheet1 -AutoNameRange -AutoSize -Title "Monthly Temperatures" -PassThru $sheet = $excel.Workbook.Worksheets["Sheet1"] -Add-ConditionalFormatting -WorkSheet $sheet -Range "B1:D14" -DataBarColor CornflowerBlue +Add-ConditionalFormatting -Worksheet $sheet -Range "B1:D14" -DataBarColor CornflowerBlue Close-ExcelPackage $excel -Show \ No newline at end of file diff --git a/Examples/ConditionalFormatting/SalesReportWithDatabar.ps1 b/Examples/ConditionalFormatting/SalesReportWithDatabar.ps1 index 4870766..35cc92f 100644 --- a/Examples/ConditionalFormatting/SalesReportWithDatabar.ps1 +++ b/Examples/ConditionalFormatting/SalesReportWithDatabar.ps1 @@ -14,7 +14,7 @@ Jun,621 Export-Excel -Path .\test.xlsx -WorkSheetname Sheet1 -AutoNameRange -PassThru $sheet = $excel.Workbook.Worksheets["Sheet1"] -Add-ConditionalFormatting -WorkSheet $sheet -Range "B1:B7" -DataBarColor LawnGreen +Add-ConditionalFormatting -Worksheet $sheet -Range "B1:B7" -DataBarColor LawnGreen Set-ExcelRange -Address $sheet.Cells["A8"] -Value "Total" Set-ExcelRange -Address $sheet.Cells["B8"] -Formula "=Sum(Sales)" diff --git a/Examples/ExcelDataValidation/MutipleValidations.ps1 b/Examples/ExcelDataValidation/MutipleValidations.ps1 index b19ef2e..8b813b7 100644 --- a/Examples/ExcelDataValidation/MutipleValidations.ps1 +++ b/Examples/ExcelDataValidation/MutipleValidations.ps1 @@ -39,7 +39,7 @@ $excelPackage = @('Chisel', 'Crowbar', 'Drill', 'Hammer', 'Nails', 'Saw', 'Screw #region Creating a list using a PowerShell array $ValidationParams = @{ - WorkSheet = $excelPackage.sales + Worksheet = $excelPackage.sales ShowErrorMessage = $true ErrorStyle = 'stop' ErrorTitle = 'Invalid Data' diff --git a/Examples/FormatCellStyles/ApplyStyle.ps1 b/Examples/FormatCellStyles/ApplyStyle.ps1 index fdaace7..ce483d2 100644 --- a/Examples/FormatCellStyles/ApplyStyle.ps1 +++ b/Examples/FormatCellStyles/ApplyStyle.ps1 @@ -16,9 +16,9 @@ $pkg = $data | Export-Excel -Path $f -AutoSize -PassThru $ws = $pkg.Workbook.Worksheets["Sheet1"] -Set-ExcelRange -WorkSheet $ws -Range "A2:C6" -BackgroundColor PeachPuff -FontColor Purple -FontSize 12 -Width 12 -Set-ExcelRange -WorkSheet $ws -Range "D2:D6" -BackgroundColor WhiteSmoke -FontColor Orange -Bold -FontSize 12 -Width 12 -Set-ExcelRange -WorkSheet $ws -Range "A1:D1" -BackgroundColor BlueViolet -FontColor Wheat -FontSize 12 -Width 12 -Set-ExcelRange -WorkSheet $ws -Range "A:A" -Width 15 +Set-ExcelRange -Worksheet $ws -Range "A2:C6" -BackgroundColor PeachPuff -FontColor Purple -FontSize 12 -Width 12 +Set-ExcelRange -Worksheet $ws -Range "D2:D6" -BackgroundColor WhiteSmoke -FontColor Orange -Bold -FontSize 12 -Width 12 +Set-ExcelRange -Worksheet $ws -Range "A1:D1" -BackgroundColor BlueViolet -FontColor Wheat -FontSize 12 -Width 12 +Set-ExcelRange -Worksheet $ws -Range "A:A" -Width 15 Close-ExcelPackage -ExcelPackage $pkg -Show \ No newline at end of file diff --git a/Examples/Grouping/TimestampBucket.ps1 b/Examples/Grouping/TimestampBucket.ps1 index 7acb421..da99152 100644 --- a/Examples/Grouping/TimestampBucket.ps1 +++ b/Examples/Grouping/TimestampBucket.ps1 @@ -13,7 +13,7 @@ Timestamp,Tenant 10/29/2018 3:01:40.989,1 10/29/2018 3:01:50.545,1 10/29/2018 3:02:00.999,1 -"@ | Select-Object @{n = 'Timestamp'; e = {get-date $_.timestamp}}, tenant, @{n = 'Bucket'; e = { - (get-date $_.timestamp).Second % 30}} +"@ | Select-Object @{n = 'Timestamp'; e = {Get-date $_.timestamp}}, tenant, @{n = 'Bucket'; e = { - (Get-date $_.timestamp).Second % 30}} $f = "$env:temp\pivottest.xlsx" Remove-Item $f -ErrorAction SilentlyContinue diff --git a/Examples/MergeWorkSheet/Merge_2_Servers_Services.ps1 b/Examples/MergeWorkSheet/Merge_2_Servers_Services.ps1 index d6c7b29..b419fee 100644 --- a/Examples/MergeWorkSheet/Merge_2_Servers_Services.ps1 +++ b/Examples/MergeWorkSheet/Merge_2_Servers_Services.ps1 @@ -1,7 +1,7 @@ Remove-Item -Path "$env:temp\server*.xlsx" , "$env:temp\Combined*.xlsx" -ErrorAction SilentlyContinue #Get a subset of services into $s and export them -[System.Collections.ArrayList]$s = get-service | Select-Object -first 25 -Property * +[System.Collections.ArrayList]$s = Get-service | Select-Object -first 25 -Property * $s | Export-Excel -Path $env:temp\server1.xlsx #$s is a zero based array, excel rows are 1 based and excel has a header row so Excel rows will be 2 + index in $s. diff --git a/Examples/MergeWorkSheet/Merge_3_Servers_Services.ps1 b/Examples/MergeWorkSheet/Merge_3_Servers_Services.ps1 index fec6917..d57b639 100644 --- a/Examples/MergeWorkSheet/Merge_3_Servers_Services.ps1 +++ b/Examples/MergeWorkSheet/Merge_3_Servers_Services.ps1 @@ -1,7 +1,7 @@ Remove-Item -Path "$env:temp\server*.xlsx" , "$env:temp\Combined*.xlsx" -ErrorAction SilentlyContinue #Get a subset of services into $s and export them -[System.Collections.ArrayList]$s = get-service | Select-Object -first 25 -Property Name,DisplayName,StartType +[System.Collections.ArrayList]$s = Get-service | Select-Object -first 25 -Property Name,DisplayName,StartType $s | Export-Excel -Path $env:temp\server1.xlsx #$s is a zero based array, excel rows are 1 based and excel has a header row so Excel rows will be 2 + index in $s. diff --git a/Examples/MortgageCalculator/MortgageCalculator.ps1 b/Examples/MortgageCalculator/MortgageCalculator.ps1 index 9185df1..783d54b 100644 --- a/Examples/MortgageCalculator/MortgageCalculator.ps1 +++ b/Examples/MortgageCalculator/MortgageCalculator.ps1 @@ -17,7 +17,7 @@ function New-CellData { ) $setFormatParams = @{ - WorkSheet = $ws + Worksheet = $ws Range = $Range NumberFormat = $Format } diff --git a/Examples/SQL+FillColumns+Pivot/Example2.ps1 b/Examples/SQL+FillColumns+Pivot/Example2.ps1 index 9c80f6d..548c668 100644 --- a/Examples/SQL+FillColumns+Pivot/Example2.ps1 +++ b/Examples/SQL+FillColumns+Pivot/Example2.ps1 @@ -19,6 +19,6 @@ Set-Row -Worksheet $ws -Heading "Average" -Value {"=Average($columnName`2 Set-Column -Worksheet $ws -Heading "WinsToPoles" -Value {"=D$row/C$row"} -Column 6 -AutoSize -AutoNameRange Set-Column -Worksheet $ws -Heading "WinsToFast" -Value {"=E$row/C$row"} -Column 7 -AutoSize -AutoNameRange -Set-ExcelRange -WorkSheet $ws -Range "F2:G50" -NumberFormat "0.0%" +Set-ExcelRange -Worksheet $ws -Range "F2:G50" -NumberFormat "0.0%" $chart = New-ExcelChart -NoLegend -ChartType XYScatter -XRange WinsToFast -YRange WinsToPoles -Column 7 -Width 2000 -Height 700 -Title "Poles vs fastlaps" Export-Excel -ExcelPackage $Excel -WorkSheetname "Winners" -ExcelChartDefinition $chart -Show \ No newline at end of file diff --git a/Examples/Sparklines/SalesByQuarter.ps1 b/Examples/Sparklines/SalesByQuarter.ps1 index 4c888d2..57ebe28 100644 --- a/Examples/Sparklines/SalesByQuarter.ps1 +++ b/Examples/Sparklines/SalesByQuarter.ps1 @@ -15,7 +15,7 @@ $excel = $data | Export-Excel $xlfile -Passthru -AutoSize -TableName SalesByQuar $ws = $excel.Sheet1 -Set-ExcelRange -WorkSheet $ws -Range "B2:E5" -NumberFormat "$#,##0" -AutoSize +Set-ExcelRange -Worksheet $ws -Range "B2:E5" -NumberFormat "$#,##0" -AutoSize $sparkLineType = "line" $null = $ws.SparklineGroups.Add( $sparkLineType, $ws.Cells["F2"], $ws.Cells["B2:E2"] ) $null = $ws.SparklineGroups.Add( $sparkLineType, $ws.Cells["F3"], $ws.Cells["B3:E3"] ) diff --git a/Examples/Sparklines/Sparklines.ps1 b/Examples/Sparklines/Sparklines.ps1 index 1802233..46718ed 100644 --- a/Examples/Sparklines/Sparklines.ps1 +++ b/Examples/Sparklines/Sparklines.ps1 @@ -41,8 +41,8 @@ Remove-Item $xlfile -ErrorAction SilentlyContinue $excel = $data | Export-Excel $xlfile -WorksheetName SEKRates -AutoSize -PassThru # Add a column sparkline for all currencies -Set-ExcelRange -WorkSheet $excel.SEKRates -Range "A2:A12" -NumberFormat "yyyy-mm-dd" -AutoSize -Set-ExcelRange -WorkSheet $excel.SEKRates -Range A15 -Value Column -AutoSize +Set-ExcelRange -Worksheet $excel.SEKRates -Range "A2:A12" -NumberFormat "yyyy-mm-dd" -AutoSize +Set-ExcelRange -Worksheet $excel.SEKRates -Range A15 -Value Column -AutoSize $sparklineCol = $excel.SEKRates.SparklineGroups.Add( "Column", @@ -54,7 +54,7 @@ $sparklineCol.High = $true $sparklineCol.ColorHigh.SetColor("Red") # Add a line sparkline for all currencies -Set-ExcelRange -WorkSheet $excel.SEKRates -Range A16 -Value Line -AutoSize +Set-ExcelRange -Worksheet $excel.SEKRates -Range A16 -Value Line -AutoSize $sparklineLine = $excel.SEKRates.SparklineGroups.Add( "Line", $excel.SEKRates.Cells["B16:Q16"], @@ -64,7 +64,7 @@ $sparklineLine = $excel.SEKRates.SparklineGroups.Add( $sparklineLine.DateAxisRange = $excel.SEKRates.Cells["A2:A12"] # Add some more random values and add a stacked sparkline. -Set-ExcelRange -WorkSheet $excel.SEKRates -Range A17 -Value Stacked -AutoSize +Set-ExcelRange -Worksheet $excel.SEKRates -Range A17 -Value Stacked -AutoSize $numbers = 2, -1, 3, -4, 8, 5, -12, 18, 99, 1, -4, 12, -8, 9, 0, -8 @@ -86,7 +86,7 @@ $sparklineStacked.ColorLow.SetColor("Green") $sparklineStacked.Negative = $true $sparklineStacked.ColorNegative.SetColor("Blue") -Set-ExcelRange -WorkSheet $excel.SEKRates -Range "A15:A17" -Bold -Height 50 -AutoSize +Set-ExcelRange -Worksheet $excel.SEKRates -Range "A15:A17" -Bold -Height 50 -AutoSize $v = @" High - Red @@ -94,6 +94,6 @@ Low - Green Negative - Blue "@ -Set-ExcelRange -WorkSheet $excel.SEKRates -Range S17 -Value $v -WrapText -Width 20 -HorizontalAlignment Center -VerticalAlignment Center +Set-ExcelRange -Worksheet $excel.SEKRates -Range S17 -Value $v -WrapText -Width 20 -HorizontalAlignment Center -VerticalAlignment Center Close-ExcelPackage $excel -Show \ No newline at end of file diff --git a/Examples/TestRestAPI/PSExcelPester.psm1 b/Examples/TestRestAPI/PSExcelPester.psm1 index 23e74a9..7c95a32 100644 --- a/Examples/TestRestAPI/PSExcelPester.psm1 +++ b/Examples/TestRestAPI/PSExcelPester.psm1 @@ -5,7 +5,7 @@ function ConvertTo-PesterTest { $WorksheetName = 'Sheet1' ) - $testFileName = "{0}.tests.ps1" -f (get-date).ToString("yyyyMMddHHmmss") + $testFileName = "{0}.tests.ps1" -f (Get-date).ToString("yyyyMMddHHmmss") $records = Import-Excel $XlFilename diff --git a/Examples/TestRestAPI/TestAPIReadXls.ps1 b/Examples/TestRestAPI/TestAPIReadXls.ps1 index 4dc1810..4aebc8c 100644 --- a/Examples/TestRestAPI/TestAPIReadXls.ps1 +++ b/Examples/TestRestAPI/TestAPIReadXls.ps1 @@ -6,7 +6,7 @@ function Test-APIReadXls { $WorksheetName = 'Sheet1' ) - $testFileName = "{0}.tests.ps1" -f (get-date).ToString("yyyyMMddHHmmss") + $testFileName = "{0}.tests.ps1" -f (Get-date).ToString("yyyyMMddHHmmss") $records = Import-Excel $XlFilename diff --git a/Examples/VBA/HelloWorldVBA.ps1 b/Examples/VBA/HelloWorldVBA.ps1 index 855df0f..dc511b5 100644 --- a/Examples/VBA/HelloWorldVBA.ps1 +++ b/Examples/VBA/HelloWorldVBA.ps1 @@ -32,7 +32,7 @@ End Function $module = $wb.VbaProject.Modules.AddModule("PSExcelModule") $module.Code = $code -Set-ExcelRange -WorkSheet $sheet -Range "h7" -Formula "HelloWorld()" -AutoSize -Set-ExcelRange -WorkSheet $sheet -Range "h8" -Formula "DoSum()" -AutoSize +Set-ExcelRange -Worksheet $sheet -Range "h7" -Formula "HelloWorld()" -AutoSize +Set-ExcelRange -Worksheet $sheet -Range "h8" -Formula "DoSum()" -AutoSize Close-ExcelPackage $Excel -Show \ No newline at end of file diff --git a/ExportedCommands/Add-ConditionalFormatting.ps1 b/ExportedCommands/Add-ConditionalFormatting.ps1 index cf204b8..92ce94b 100644 --- a/ExportedCommands/Add-ConditionalFormatting.ps1 +++ b/ExportedCommands/Add-ConditionalFormatting.ps1 @@ -3,7 +3,7 @@ [Parameter(Mandatory = $true, Position = 0)] [Alias("Range")] $Address , - [OfficeOpenXml.ExcelWorksheet]$WorkSheet , + [OfficeOpenXml.ExcelWorksheet]$Worksheet , [Parameter(Mandatory = $true, ParameterSetName = "NamedRule", Position = 1)] [OfficeOpenXml.ConditionalFormatting.eExcelConditionalFormattingRuleType]$RuleType , [Parameter(ParameterSetName = "NamedRule")] @@ -51,18 +51,18 @@ #Allow conditional formatting to work like Set-ExcelRange (with single ADDRESS parameter), split it to get worksheet and range of cells. If ($Address -is [OfficeOpenXml.Table.ExcelTable]) { - $WorkSheet = $Address.Address.Worksheet + $Worksheet = $Address.Address.Worksheet $Address = $Address.Address.Address } - elseif ($Address.Address -and $Address.Worksheet -and -not $WorkSheet) { #Address is a rangebase or similar - $WorkSheet = $Address.Worksheet[0] + elseif ($Address.Address -and $Address.Worksheet -and -not $Worksheet) { #Address is a rangebase or similar + $Worksheet = $Address.Worksheet[0] $Address = $Address.Address } - elseif ($Address -is [String] -and $WorkSheet -and $WorkSheet.Names[$Address] ) { #Address is the name of a named range. - $Address = $WorkSheet.Names[$Address].Address + elseif ($Address -is [String] -and $Worksheet -and $Worksheet.Names[$Address] ) { #Address is the name of a named range. + $Address = $Worksheet.Names[$Address].Address } - if (($Address -is [OfficeOpenXml.ExcelRow] -and -not $WorkSheet) -or - ($Address -is [OfficeOpenXml.ExcelColumn] -and -not $WorkSheet) ){ #EPPLUs Can't get the worksheet object from a row or column object, so bail if that was tried + if (($Address -is [OfficeOpenXml.ExcelRow] -and -not $Worksheet) -or + ($Address -is [OfficeOpenXml.ExcelColumn] -and -not $Worksheet) ){ #EPPLUs Can't get the worksheet object from a row or column object, so bail if that was tried Write-Warning -Message "Add-ConditionalFormatting does not support Row or Column objects as an address; use a worksheet and/or specify 'R:R' or 'C:C' instead. "; return } elseif ($Address -is [OfficeOpenXml.ExcelRow]) { #But if we have a column or row object and a worksheet (I don't know *why*) turn them into a string for the range @@ -74,16 +74,16 @@ } if ( $Address -is [string] -and $Address -match "!") {$Address = $Address -replace '^.*!',''} #By this point we should have a worksheet object whose ConditionalFormatting collection we will add to. If not, bail. - if (-not $worksheet -or $WorkSheet -isnot [OfficeOpenXml.ExcelWorksheet]) {write-warning "You need to provide a worksheet object." ; return} + if (-not $worksheet -or $Worksheet -isnot [OfficeOpenXml.ExcelWorksheet]) {write-warning "You need to provide a worksheet object." ; return} #region create a rule of the right type if ($RuleType -match 'IconSet$') {Write-warning -Message "You cannot configure a Icon-Set rule in this way; please use -$RuleType ." ; return} if ($PSBoundParameters.ContainsKey("DataBarColor" ) ) {if ($DataBarColor -is [string]) {$DataBarColor = [System.Drawing.Color]::$DataBarColor } - $rule = $WorkSheet.ConditionalFormatting.AddDatabar( $Address , $DataBarColor ) + $rule = $Worksheet.ConditionalFormatting.AddDatabar( $Address , $DataBarColor ) } - elseif ($PSBoundParameters.ContainsKey("ThreeIconsSet" ) ) {$rule = $WorkSheet.ConditionalFormatting.AddThreeIconSet($Address , $ThreeIconsSet)} - elseif ($PSBoundParameters.ContainsKey("FourIconsSet" ) ) {$rule = $WorkSheet.ConditionalFormatting.AddFourIconSet( $Address , $FourIconsSet )} - elseif ($PSBoundParameters.ContainsKey("FiveIconsSet" ) ) {$rule = $WorkSheet.ConditionalFormatting.AddFiveIconSet( $Address , $FiveIconsSet )} - else {$rule = ($WorkSheet.ConditionalFormatting)."Add$RuleType"($Address ) } + elseif ($PSBoundParameters.ContainsKey("ThreeIconsSet" ) ) {$rule = $Worksheet.ConditionalFormatting.AddThreeIconSet($Address , $ThreeIconsSet)} + elseif ($PSBoundParameters.ContainsKey("FourIconsSet" ) ) {$rule = $Worksheet.ConditionalFormatting.AddFourIconSet( $Address , $FourIconsSet )} + elseif ($PSBoundParameters.ContainsKey("FiveIconsSet" ) ) {$rule = $Worksheet.ConditionalFormatting.AddFiveIconSet( $Address , $FiveIconsSet )} + else {$rule = ($Worksheet.ConditionalFormatting)."Add$RuleType"($Address ) } if ($Reverse) { if ($rule.type -match 'IconSet$' ) {$rule.reverse = $true} elseif ($rule.type -match 'ColorScale$') {$temp =$rule.LowValue.Color ; $rule.LowValue.Color = $rule.HighValue.Color; $rule.HighValue.Color = $temp} diff --git a/ExportedCommands/Add-ExcelChart.ps1 b/ExportedCommands/Add-ExcelChart.ps1 index 6f77258..1fbaf62 100644 --- a/ExportedCommands/Add-ExcelChart.ps1 +++ b/ExportedCommands/Add-ExcelChart.ps1 @@ -49,7 +49,7 @@ function Add-ExcelChart { ) try { if ($PivotTable) { - $Worksheet = $PivotTable.WorkSheet + $Worksheet = $PivotTable.Worksheet $chart = $Worksheet.Drawings.AddChart(("Chart" + $PivotTable.Name ), $ChartType, $PivotTable) } else { @@ -138,5 +138,5 @@ function Add-ExcelChart { if ($PassThru) { return $chart } } - catch { Write-Warning -Message "Failed adding Chart to worksheet '$($WorkSheet).name': $_" } + catch { Write-Warning -Message "Failed adding Chart to worksheet '$($Worksheet).name': $_" } } diff --git a/ExportedCommands/Add-ExcelDataValidationRule.ps1 b/ExportedCommands/Add-ExcelDataValidationRule.ps1 index a98ba8f..6658ca3 100644 --- a/ExportedCommands/Add-ExcelDataValidationRule.ps1 +++ b/ExportedCommands/Add-ExcelDataValidationRule.ps1 @@ -4,7 +4,7 @@ [Parameter(ValueFromPipeline = $true,Position=0)] [Alias("Address")] $Range , - [OfficeOpenXml.ExcelWorksheet]$WorkSheet , + [OfficeOpenXml.ExcelWorksheet]$Worksheet , [ValidateSet('Any','Custom','DateTime','Decimal','Integer','List','TextLength','Time')] $ValidationType, [OfficeOpenXml.DataValidation.ExcelDataValidationOperator]$Operator = [OfficeOpenXml.DataValidation.ExcelDataValidationOperator]::equal , @@ -28,13 +28,13 @@ } else { #We should accept, a worksheet and a name of a range or a cell address; a table; the address of a table; a named range; a row, a column or .Cells[ ] - if (-not $WorkSheet -and $Range.worksheet) {$WorkSheet = $Range.worksheet} + if (-not $Worksheet -and $Range.worksheet) {$Worksheet = $Range.worksheet} if ($Range.Address) {$Range = $Range.Address} - if ($Range -isnot [string] -or -not $WorkSheet) {Write-Warning -Message "You need to provide a worksheet and range of cells." ;return} + if ($Range -isnot [string] -or -not $Worksheet) {Write-Warning -Message "You need to provide a worksheet and range of cells." ;return} #else we assume Range is a range. - $validation = $WorkSheet.DataValidations."Add$ValidationType`Validation"($Range) + $validation = $Worksheet.DataValidations."Add$ValidationType`Validation"($Range) if ($validation.AllowsOperator) {$validation.Operator = $Operator} if ($PSBoundParameters.ContainsKey('value')) { $validation.Formula.Value = $Value diff --git a/ExportedCommands/Add-PivotTable.ps1 b/ExportedCommands/Add-PivotTable.ps1 index cd7fc46..589870a 100644 --- a/ExportedCommands/Add-PivotTable.ps1 +++ b/ExportedCommands/Add-PivotTable.ps1 @@ -64,7 +64,7 @@ else { 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 + [OfficeOpenXml.ExcelWorksheet]$wsPivot = Add-Worksheet -ExcelPackage $ExcelPackage -WorksheetName $pivotTableName -Activate:$Activate 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"]} } diff --git a/ExportedCommands/Compare-WorkSheet.ps1 b/ExportedCommands/Compare-Worksheet.ps1 similarity index 97% rename from ExportedCommands/Compare-WorkSheet.ps1 rename to ExportedCommands/Compare-Worksheet.ps1 index 6f5bf64..2f23ffb 100644 --- a/ExportedCommands/Compare-WorkSheet.ps1 +++ b/ExportedCommands/Compare-Worksheet.ps1 @@ -1,4 +1,4 @@ -Function Compare-WorkSheet { +Function Compare-Worksheet { [cmdletbinding(DefaultParameterSetName)] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification="Write host used for sub-warning level message to operator which does not form output")] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification="False positives when initializing variable in begin block")] @@ -49,7 +49,7 @@ Catch {Write-Warning -Message "Could not read the worksheet from $Referencefile and/or $Differencefile." ; return } #Get Column headings and create a hash table of Name to column letter. - $headings = $Sheet1[-1].psobject.Properties.name # This preserves the sequence - using get-member would sort them alphabetically! + $headings = $Sheet1[-1].psobject.Properties.name # This preserves the sequence - using Get-member would sort them alphabetically! $headings | ForEach-Object -Begin {$columns = @{} ; $i= 1 } -Process {$Columns[$_] = [OfficeOpenXml.ExcelAddress]::GetAddress(1,($i ++)) -replace "\d","" } #Make a list of property headings using the Property (default "*") and ExcludeProperty parameters @@ -88,13 +88,13 @@ $ws = $xl.Workbook.Worksheets[$_] if ($headerName) {$range = "A" + $startrow + ":" + $ws.dimension.end.address} else {$range = "A" + ($startrow + 1) + ":" + $ws.dimension.end.address} - Set-ExcelRange -WorkSheet $ws -BackgroundColor $AllDataBackgroundColor -Range $Range + Set-ExcelRange -Worksheet $ws -BackgroundColor $AllDataBackgroundColor -Range $Range } } foreach ($row in $file.group) { $ws = $xl.Workbook.Worksheets[$row._Sheet] $range = $ws.Dimension -replace "\d+",$row._row - Set-ExcelRange -WorkSheet $ws -Range $range -BackgroundColor $BackgroundColor + Set-ExcelRange -Worksheet $ws -Range $range -BackgroundColor $BackgroundColor } if ($PSBoundParameters.ContainsKey("TabColor")) { if ($TabColor -is [string]) {$TabColor = [System.Drawing.Color]::$TabColor } @@ -123,8 +123,8 @@ $ws2 = $xl1.Workbook.Worksheets[$u.Group[1]._sheet] } if($u.Group[0].$p -ne $u.Group[1].$p ) { - Set-ExcelRange -WorkSheet $ws1 -Range ($Columns[$p] + $u.Group[0]._Row) -FontColor $FontColor - Set-ExcelRange -WorkSheet $ws2 -Range ($Columns[$p] + $u.Group[1]._Row) -FontColor $FontColor + Set-ExcelRange -Worksheet $ws1 -Range ($Columns[$p] + $u.Group[0]._Row) -FontColor $FontColor + Set-ExcelRange -Worksheet $ws2 -Range ($Columns[$p] + $u.Group[1]._Row) -FontColor $FontColor } } } diff --git a/ExportedCommands/Convert-ExcelRangeToImage.ps1 b/ExportedCommands/Convert-ExcelRangeToImage.ps1 index affca6a..1569201 100644 --- a/ExportedCommands/Convert-ExcelRangeToImage.ps1 +++ b/ExportedCommands/Convert-ExcelRangeToImage.ps1 @@ -43,11 +43,11 @@ $myData = Get-Process | Select-Object -Property Name,WS,CPU,Description,c $excelPackage = $myData | Export-Excel -KillExcel -Path $Path -WorkSheetname $workSheetname -ClearSheet -AutoSize -AutoFilter -BoldTopRow -FreezeTopRow -PassThru $workSheet = $excelPackage.Workbook.Worksheets[$workSheetname] $range = $workSheet.Dimension.Address -Set-ExcelRange -WorkSheet $workSheet -Range "b:b" -NumberFormat "#,###" -AutoFit -Set-ExcelRange -WorkSheet $workSheet -Range "C:C" -NumberFormat "#,##0.00" -AutoFit -Set-ExcelRange -WorkSheet $workSheet -Range "F:F" -NumberFormat "dd MMMM HH:mm:ss" -AutoFit -Add-ConditionalFormatting -WorkSheet $workSheet -Range "c2:c1000" -DataBarColor Blue -Add-ConditionalFormatting -WorkSheet $workSheet -Range "b2:B1000" -RuleType GreaterThan -ConditionValue '104857600' -ForeGroundColor "Red" -Bold +Set-ExcelRange -Worksheet $workSheet -Range "b:b" -NumberFormat "#,###" -AutoFit +Set-ExcelRange -Worksheet $workSheet -Range "C:C" -NumberFormat "#,##0.00" -AutoFit +Set-ExcelRange -Worksheet $workSheet -Range "F:F" -NumberFormat "dd MMMM HH:mm:ss" -AutoFit +Add-ConditionalFormatting -Worksheet $workSheet -Range "c2:c1000" -DataBarColor Blue +Add-ConditionalFormatting -Worksheet $workSheet -Range "b2:B1000" -RuleType GreaterThan -ConditionValue '104857600' -ForeGroundColor "Red" -Bold Export-Excel -ExcelPackage $excelPackage -WorkSheetname $workSheetname diff --git a/ExportedCommands/Copy-ExcelWorkSheet.ps1 b/ExportedCommands/Copy-ExcelWorksheet.ps1 similarity index 97% rename from ExportedCommands/Copy-ExcelWorkSheet.ps1 rename to ExportedCommands/Copy-ExcelWorksheet.ps1 index ca79a29..7ba4b55 100644 --- a/ExportedCommands/Copy-ExcelWorkSheet.ps1 +++ b/ExportedCommands/Copy-ExcelWorksheet.ps1 @@ -1,4 +1,4 @@ -function Copy-ExcelWorkSheet { +function Copy-ExcelWorksheet { [CmdletBinding()] param( [Parameter(Mandatory = $true,ValueFromPipeline=$true)] @@ -39,7 +39,7 @@ return } else { - $null = Add-WorkSheet -ExcelPackage $excel -WorkSheetname $DestinationWorksheet -CopySource ($excel.Workbook.Worksheets[$SourceWorkSheet]) + $null = Add-Worksheet -ExcelPackage $excel -WorkSheetname $DestinationWorksheet -CopySource ($excel.Workbook.Worksheets[$SourceWorkSheet]) Close-ExcelPackage -ExcelPackage $excel -Show:$Show return } @@ -76,7 +76,7 @@ $DestinationWorkbook.Worksheets.Delete($DestinationWorksheet) } Write-Verbose "Copying '$($sourcews.name)' from $($SourceObject) to '$($DestinationWorksheet)' in $($PSBoundParameters['DestinationWorkbook'])" - $null = Add-WorkSheet -ExcelWorkbook $DestinationWorkbook -WorkSheetname $DestinationWorksheet -CopySource $sourceWs + $null = Add-Worksheet -ExcelWorkbook $DestinationWorkbook -WorkSheetname $DestinationWorksheet -CopySource $sourceWs #Leave the destination open but close the source - if we're copying more than one sheet we'll re-open it and live with the inefficiency if ($stream) {$stream.Close() } if ($package1) {Close-ExcelPackage -ExcelPackage $package1 -NoSave } diff --git a/ExportedCommands/Export-Excel.ps1 b/ExportedCommands/Export-Excel.ps1 index 58e6ed8..1024d41 100644 --- a/ExportedCommands/Export-Excel.ps1 +++ b/ExportedCommands/Export-Excel.ps1 @@ -124,7 +124,7 @@ try { $params = @{WorksheetName=$WorksheetName} foreach ($p in @("ClearSheet", "MoveToStart", "MoveToEnd", "MoveBefore", "MoveAfter", "Activate")) {if ($PSBoundParameters[$p]) {$params[$p] = $PSBoundParameters[$p]}} - $ws = $pkg | Add-WorkSheet @params + $ws = $pkg | Add-Worksheet @params if ($ws.Name -ne $WorksheetName) { Write-Warning -Message "The Worksheet name has been changed from $WorksheetName to $($ws.Name), this may cause errors later." $WorksheetName = $ws.Name @@ -609,27 +609,27 @@ ForeGroundColor = $c.ConditionalTextColor} if ($c.Range) {$cfParams.Range = $c.Range} else {$cfParams.Range = $ws.Dimension.Address } - Add-ConditionalFormatting -WorkSheet $ws @cfParams + Add-ConditionalFormatting -Worksheet $ws @cfParams Write-Verbose -Message "Added conditional formatting to range $($c.range)" } elseif ($c.formatter) { switch ($c.formatter) { - "ThreeIconSet" {Add-ConditionalFormatting -WorkSheet $ws -ThreeIconsSet $c.IconType -range $c.range -reverse:$c.reverse } - "FourIconSet" {Add-ConditionalFormatting -WorkSheet $ws -FourIconsSet $c.IconType -range $c.range -reverse:$c.reverse } - "FiveIconSet" {Add-ConditionalFormatting -WorkSheet $ws -FiveIconsSet $c.IconType -range $c.range -reverse:$c.reverse } + "ThreeIconSet" {Add-ConditionalFormatting -Worksheet $ws -ThreeIconsSet $c.IconType -range $c.range -reverse:$c.reverse } + "FourIconSet" {Add-ConditionalFormatting -Worksheet $ws -FourIconsSet $c.IconType -range $c.range -reverse:$c.reverse } + "FiveIconSet" {Add-ConditionalFormatting -Worksheet $ws -FiveIconsSet $c.IconType -range $c.range -reverse:$c.reverse } } Write-Verbose -Message "Added conditional formatting to range $($c.range)" } elseif ($c -is [hashtable] -or $c -is[System.Collections.Specialized.OrderedDictionary]) { if (-not $c.Range -or $c.Address) {$c.Address = $ws.Dimension.Address } - Add-ConditionalFormatting -WorkSheet $ws @c + Add-ConditionalFormatting -Worksheet $ws @c } } catch {throw "Error applying conditional formatting to worksheet $_"} } foreach ($s in $Style) { if (-not $s.Range) {$s["Range"] = $ws.Dimension.Address } - Set-ExcelRange -WorkSheet $ws @s + Set-ExcelRange -Worksheet $ws @s } if ($CellStyleSB) { try { diff --git a/ExportedCommands/Import-UPS.ps1 b/ExportedCommands/Import-UPS.ps1 index d71601f..f1ad15f 100644 --- a/ExportedCommands/Import-UPS.ps1 +++ b/ExportedCommands/Import-UPS.ps1 @@ -1,14 +1,4 @@ -function Import-USPS { - param( - $TrackingNumber, - [Switch]$UseDefaultCredentials - - ) - - Import-Html "https://tools.usps.com/go/TrackConfirmAction?qtc_tLabels1=$($TrackingNumber)" 0 -UseDefaultCredentials: $UseDefaultCredentials -} - -function Import-UPS { +function Import-UPS { param( $TrackingNumber, [Switch]$UseDefaultCredentials diff --git a/ExportedCommands/Import-USPS.ps1 b/ExportedCommands/Import-USPS.ps1 index 921fa71..e45ed38 100644 --- a/ExportedCommands/Import-USPS.ps1 +++ b/ExportedCommands/Import-USPS.ps1 @@ -1,9 +1,10 @@ function Import-USPS { + param( $TrackingNumber, [Switch]$UseDefaultCredentials ) - Import-Html "https://tools.usps.com/go/TrackConfirmAction?qtc_tLabels1=$($TrackingNumber)" 0 -UseDefaultCredentials: $UseDefaultCredentials + Import-Html "https://tools.usps.com/go/TrackConfirmAction?qtc_tLabels1=$($TrackingNumber)" 0 -UseDefaultCredentials:$UseDefaultCredentials } diff --git a/ExportedCommands/Join-Worksheet.ps1 b/ExportedCommands/Join-Worksheet.ps1 index cb24d4e..1d54004 100644 --- a/ExportedCommands/Join-Worksheet.ps1 +++ b/ExportedCommands/Join-Worksheet.ps1 @@ -55,7 +55,7 @@ ) #region get target worksheet, select it and move it to the end. if ($Path -and -not $ExcelPackage) {$ExcelPackage = Open-ExcelPackage -path $Path } - $destinationSheet = Add-WorkSheet -ExcelPackage $ExcelPackage -WorkSheetname $WorkSheetName -ClearSheet:$Clearsheet + $destinationSheet = Add-Worksheet -ExcelPackage $ExcelPackage -WorkSheetname $WorkSheetName -ClearSheet:$Clearsheet foreach ($w in $ExcelPackage.Workbook.Worksheets) {$w.view.TabSelected = $false} $destinationSheet.View.TabSelected = $true $ExcelPackage.Workbook.Worksheets.MoveToEnd($WorkSheetName) @@ -117,7 +117,7 @@ if ($HideSource) {$sourceWorksheet.Hidden = [OfficeOpenXml.eWorkSheetHidden]::Hidden} } - #We accept a bunch of parameters work to pass on to Export-excel ( Autosize, Autofilter, boldtopRow Freeze ); if we have any of those call export-excel otherwise close the package here. + #We accept a bunch of parameters work to pass on to Export-excel ( Autosize, Autofilter, boldtopRow Freeze ); if we have any of those call Export-excel otherwise close the package here. $params = @{} + $PSBoundParameters 'Path', 'Clearsheet', 'NoHeader', 'FromLabel', 'LabelBlocks', 'HideSource', 'Title', 'TitleFillPattern', 'TitleBackgroundColor', 'TitleBold', 'TitleSize' | ForEach-Object {$null = $params.Remove($_)} diff --git a/ExportedCommands/Merge-Worksheet.ps1 b/ExportedCommands/Merge-Worksheet.ps1 index 0674f65..36c0e88 100644 --- a/ExportedCommands/Merge-Worksheet.ps1 +++ b/ExportedCommands/Merge-Worksheet.ps1 @@ -115,7 +115,7 @@ #Make a list of properties/headings using the Property (default "*") and ExcludeProperty parameters $propList = @() $DifferenceObject = $DifferenceObject | Update-FirstObjectProperties - $headings = $DifferenceObject[0].psobject.Properties.Name # This preserves the sequence - using get-member would sort them alphabetically! There may be extra properties in + $headings = $DifferenceObject[0].psobject.Properties.Name # This preserves the sequence - using Get-member would sort them alphabetically! There may be extra properties in if ($NoHeader -and "Name" -eq $Key) {$Key = "p1"} if ($headings -notcontains $Key -and ('*' -ne $Key)) {Write-Warning -Message "You need to specify one of the headings in the sheet '$Worksheet1' as a key." ; return } diff --git a/ExportedCommands/Remove-WorkSheet.ps1 b/ExportedCommands/Remove-Worksheet.ps1 similarity index 87% rename from ExportedCommands/Remove-WorkSheet.ps1 rename to ExportedCommands/Remove-Worksheet.ps1 index 2d465e1..a2bbb93 100644 --- a/ExportedCommands/Remove-WorkSheet.ps1 +++ b/ExportedCommands/Remove-Worksheet.ps1 @@ -1,4 +1,4 @@ -Function Remove-WorkSheet { +Function Remove-Worksheet { [cmdletbinding(SupportsShouldProcess=$true)] param( # [Parameter(ValueFromPipelineByPropertyName)] @@ -11,7 +11,7 @@ Process { if (!$FullName) { - throw "Remove-WorkSheet requires the and Excel file" + throw "Remove-Worksheet requires the and Excel file" } $pkg = Open-ExcelPackage -Path $FullName diff --git a/ExportedCommands/Set-CellStyle.ps1 b/ExportedCommands/Set-CellStyle.ps1 index 0968512..96ca249 100644 --- a/ExportedCommands/Set-CellStyle.ps1 +++ b/ExportedCommands/Set-CellStyle.ps1 @@ -3,14 +3,14 @@ param() function Set-CellStyle { param( - $WorkSheet, + $Worksheet, $Row, $LastColumn, [OfficeOpenXml.Style.ExcelFillStyle]$Pattern, $Color ) if ($Color -is [string]) {$Color = [System.Drawing.Color]::$Color } - $t=$WorkSheet.Cells["A$($Row):$($LastColumn)$($Row)"] + $t=$Worksheet.Cells["A$($Row):$($LastColumn)$($Row)"] $t.Style.Fill.PatternType=$Pattern $t.Style.Fill.BackgroundColor.SetColor($Color) } \ No newline at end of file diff --git a/ExportedCommands/Set-ExcelColumn.ps1 b/ExportedCommands/Set-ExcelColumn.ps1 index 2d080a1..6cc51e5 100644 --- a/ExportedCommands/Set-ExcelColumn.ps1 +++ b/ExportedCommands/Set-ExcelColumn.ps1 @@ -116,7 +116,7 @@ } if ($params.Count) { $theRange = "$columnName$StartRow`:$columnName$endRow" - Set-ExcelRange -WorkSheet $Worksheet -Range $theRange @params + Set-ExcelRange -Worksheet $Worksheet -Range $theRange @params } #endregion if ($PSBoundParameters.ContainsKey('Hide')) {$workSheet.Column($Column).Hidden = [bool]$Hide} diff --git a/ExportedCommands/Set-ExcelRange.ps1 b/ExportedCommands/Set-ExcelRange.ps1 index 49ca0d0..48d759e 100644 --- a/ExportedCommands/Set-ExcelRange.ps1 +++ b/ExportedCommands/Set-ExcelRange.ps1 @@ -6,7 +6,7 @@ [Parameter(ValueFromPipeline = $true,Position=0)] [Alias("Address")] $Range , - [OfficeOpenXml.ExcelWorksheet]$WorkSheet , + [OfficeOpenXml.ExcelWorksheet]$Worksheet , [Alias("NFormat")] $NumberFormat, [OfficeOpenXml.Style.ExcelBorderStyle]$BorderAround, @@ -54,8 +54,8 @@ else { #We should accept, a worksheet and a name of a range or a cell address; a table; the address of a table; a named range; a row, a column or .Cells[ ] if ($Range -is [OfficeOpenXml.Table.ExcelTable]) {$Range = $Range.Address} - elseif ($WorkSheet -and ($Range -is [string] -or $Range -is [OfficeOpenXml.ExcelAddress])) { - $Range = $WorkSheet.Cells[$Range] + elseif ($Worksheet -and ($Range -is [string] -or $Range -is [OfficeOpenXml.ExcelAddress])) { + $Range = $Worksheet.Cells[$Range] } elseif ($Range -is [string]) {Write-Warning -Message "The range pararameter you have specified also needs a worksheet parameter." ;return} #else we assume $Range is a range. @@ -159,7 +159,7 @@ if ($Range -is [OfficeOpenXml.ExcelRow] ) {$Range.Height = $Height } elseif ($Range -is [OfficeOpenXml.ExcelRange] ) { ($Range.Start.Row)..($Range.Start.Row + $Range.Rows) | - ForEach-Object {$Range.WorkSheet.Row($_).Height = $Height } + ForEach-Object {$Range.Worksheet.Row($_).Height = $Height } } else {Write-Warning -Message ("Can set the height of a row or a range but not a {0} object" -f ($Range.GetType().name)) } } diff --git a/ExportedCommands/Set-ExcelRow.ps1 b/ExportedCommands/Set-ExcelRow.ps1 index 67ef805..72aa62e 100644 --- a/ExportedCommands/Set-ExcelRow.ps1 +++ b/ExportedCommands/Set-ExcelRow.ps1 @@ -113,7 +113,7 @@ } if ($params.Count) { $theRange = New-Object -TypeName OfficeOpenXml.ExcelAddress @($Row, $StartColumn, $Row, $endColumn) - Set-ExcelRange -WorkSheet $Worksheet -Range $theRange @params + Set-ExcelRange -Worksheet $Worksheet -Range $theRange @params } #endregion if ($PSBoundParameters.ContainsKey('Hide')) {$workSheet.Row($Row).Hidden = [bool]$Hide} diff --git a/ExportedCommands/Set-WorkSheetProtection.md b/ExportedCommands/Set-WorksheetProtection.md similarity index 100% rename from ExportedCommands/Set-WorkSheetProtection.md rename to ExportedCommands/Set-WorksheetProtection.md diff --git a/ExportedCommands/Set-WorkSheetProtection.ps1 b/ExportedCommands/Set-WorksheetProtection.ps1 similarity index 89% rename from ExportedCommands/Set-WorkSheetProtection.ps1 rename to ExportedCommands/Set-WorksheetProtection.ps1 index e17f3c7..b7258e3 100644 --- a/ExportedCommands/Set-WorkSheetProtection.ps1 +++ b/ExportedCommands/Set-WorksheetProtection.ps1 @@ -1,9 +1,9 @@ -Function Set-WorkSheetProtection { +Function Set-WorksheetProtection { [Cmdletbinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system state')] param ( [Parameter(Mandatory=$true)] - [OfficeOpenXml.ExcelWorksheet]$WorkSheet , + [OfficeOpenXml.ExcelWorksheet]$Worksheet , [switch]$IsProtected, [switch]$AllowAll, [switch]$BlockSelectLockedCells, @@ -44,12 +44,12 @@ Else {Write-Warning -Message "You haven't said if you want to turn protection off, or on." } if ($LockAddress) { - Set-ExcelRange -Range $WorkSheet.cells[$LockAddress] -Locked + Set-ExcelRange -Range $Worksheet.cells[$LockAddress] -Locked } elseif ($IsProtected) { - Set-ExcelRange -Range $WorkSheet.Cells -Locked + Set-ExcelRange -Range $Worksheet.Cells -Locked } if ($UnlockAddress) { - Set-ExcelRange -Range $WorkSheet.cells[$UnlockAddress] -Locked:$false + Set-ExcelRange -Range $Worksheet.cells[$UnlockAddress] -Locked:$false } } \ No newline at end of file diff --git a/ImportExcel.psd1 b/ImportExcel.psd1 index 6288b3d..bda2946 100644 --- a/ImportExcel.psd1 +++ b/ImportExcel.psd1 @@ -68,17 +68,17 @@ Check out the How To Videos https://www.youtube.com/watch?v=U3Ne_yX4tYo&list=PL5 'Add-ExcelName', 'Add-ExcelTable', 'Add-PivotTable', - 'Add-WorkSheet', + 'Add-Worksheet', 'BarChart', 'Close-ExcelPackage', 'ColumnChart', - 'Compare-WorkSheet', + 'Compare-Worksheet', 'Convert-ExcelRangeToImage', 'ConvertFrom-ExcelData', 'ConvertFrom-ExcelSheet', 'ConvertFrom-ExcelToSQLInsert', 'ConvertTo-ExcelXlsx', - 'Copy-ExcelWorkSheet', + 'Copy-ExcelWorksheet', 'DoChart', 'Expand-NumberFormat', 'Export-Excel', @@ -110,14 +110,14 @@ Check out the How To Videos https://www.youtube.com/watch?v=U3Ne_yX4tYo&list=PL5 'Open-ExcelPackage', 'PieChart', 'Pivot', - 'Remove-WorkSheet' + 'Remove-Worksheet' 'Select-Worksheet', 'Send-SQLDataToExcel', 'Set-CellStyle', 'Set-ExcelColumn', 'Set-ExcelRange', 'Set-ExcelRow', - 'Set-WorkSheetProtection', + 'Set-WorksheetProtection', 'Test-Boolean', 'Test-Date', 'Test-Integer', diff --git a/ImportExcel.psm1 b/ImportExcel.psm1 index 359fd89..02dc71c 100644 --- a/ImportExcel.psm1 +++ b/ImportExcel.psm1 @@ -32,7 +32,7 @@ else { if (($IsLinux -or $IsMacOS) -or $env:NoAutoSize) { $ExcelPackage = [OfficeOpenXml.ExcelPackage]::new() - $Cells = ($ExcelPackage | Add-WorkSheet).Cells['A1'] + $Cells = ($ExcelPackage | Add-Worksheet).Cells['A1'] $Cells.Value = 'Test' try { $Cells.AutoFitColumns() diff --git a/Install.ps1 b/Install.ps1 index ae5e08a..c7589d3 100644 --- a/Install.ps1 +++ b/Install.ps1 @@ -29,12 +29,12 @@ $IncludeFiles = @( 'AddDataValidation.ps1', 'Charting.ps1', 'ColorCompletion.ps1', - 'Compare-WorkSheet.ps1', + 'Compare-Worksheet.ps1', 'ConvertExcelToImageFile.ps1', 'ConvertFromExcelData.ps1', 'ConvertFromExcelToSQLInsert.ps1', 'ConvertToExcelXlsx.ps1', - 'Copy-ExcelWorkSheet.ps1', + 'Copy-ExcelWorksheet.ps1', 'Export-Excel.ps1', 'Export-ExcelSheet.ps1', 'Export-StocksToExcel.ps1', @@ -62,7 +62,7 @@ $IncludeFiles = @( 'Set-CellStyle.ps1', 'Set-Column.ps1', 'Set-Row.ps1', - 'Set-WorkSheetProtection.ps1', + 'Set-WorksheetProtection.ps1', 'SetFormat.ps1', 'TrackingUtils.ps1', 'Update-FirstObjectProperties.ps1' diff --git a/__tests__/AddTrendlinesToAChart.tests.ps1 b/__tests__/AddTrendlinesToAChart.tests.ps1 index 9eaf518..16c98de 100644 --- a/__tests__/AddTrendlinesToAChart.tests.ps1 +++ b/__tests__/AddTrendlinesToAChart.tests.ps1 @@ -1,4 +1,4 @@ -if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { +if (-not (Get-command Import-Excel -ErrorAction SilentlyContinue)) { Import-Module $PSScriptRoot\..\ImportExcel.psd1 } Describe "Test adding trendlines to charts" { diff --git a/__tests__/Compare-WorkSheet.tests.ps1 b/__tests__/Compare-WorkSheet.tests.ps1 index e14e609..e119576 100644 --- a/__tests__/Compare-WorkSheet.tests.ps1 +++ b/__tests__/Compare-WorkSheet.tests.ps1 @@ -1,7 +1,7 @@ #Requires -Modules Pester [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')] param() -if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { +if (-not (Get-command Import-Excel -ErrorAction SilentlyContinue)) { Import-Module $PSScriptRoot\..\ImportExcel.psd1 } Describe "Compare Worksheet" { @@ -27,7 +27,7 @@ Describe "Compare Worksheet" { $s.RemoveAt(5) $s | Export-Excel -Path TestDrive:\server2.xlsx #Assume default worksheet name, (sheet1) and column header for key ("name") - $comp = compare-WorkSheet "TestDrive:\server1.xlsx" "TestDrive:\server2.xlsx" | Sort-Object -Property _row, _file + $comp = Compare-Worksheet "TestDrive:\server1.xlsx" "TestDrive:\server2.xlsx" | Sort-Object -Property _row, _file } Context "Simple comparison output" { it "Found the right number of differences " { @@ -59,7 +59,7 @@ Describe "Compare Worksheet" { Context "Setting the background to highlight different rows" { BeforeAll { - $null = Compare-WorkSheet "TestDrive:\server1.xlsx" "TestDrive:\server2.xlsx" -BackgroundColor ([System.Drawing.Color]::LightGreen) + $null = Compare-Worksheet "TestDrive:\server1.xlsx" "TestDrive:\server2.xlsx" -BackgroundColor ([System.Drawing.Color]::LightGreen) $xl1 = Open-ExcelPackage -Path "TestDrive:\server1.xlsx" $xl2 = Open-ExcelPackage -Path "TestDrive:\server2.xlsx" $s1Sheet = $xl1.Workbook.Worksheets[1] @@ -85,7 +85,7 @@ Describe "Compare Worksheet" { Context "Setting the forgound to highlight changed properties" { BeforeAll { - $null = compare-WorkSheet "TestDrive:\server1.xlsx" "TestDrive:\server2.xlsx" -AllDataBackgroundColor([System.Drawing.Color]::white) -BackgroundColor ([System.Drawing.Color]::LightGreen) -FontColor ([System.Drawing.Color]::DarkRed) + $null = Compare-Worksheet "TestDrive:\server1.xlsx" "TestDrive:\server2.xlsx" -AllDataBackgroundColor([System.Drawing.Color]::white) -BackgroundColor ([System.Drawing.Color]::LightGreen) -FontColor ([System.Drawing.Color]::DarkRed) $xl1 = Open-ExcelPackage -Path "TestDrive:\server1.xlsx" $xl2 = Open-ExcelPackage -Path "TestDrive:\server2.xlsx" $s1Sheet = $xl1.Workbook.Worksheets[1] @@ -114,7 +114,7 @@ Describe "Compare Worksheet" { Context "More complex comparison: output check and different worksheet names " { BeforeAll { - [System.Collections.ArrayList]$s = get-service | Select-Object -first 25 -Property RequiredServices, CanPauseAndContinue, CanShutdown, CanStop, + [System.Collections.ArrayList]$s = Get-service | Select-Object -first 25 -Property RequiredServices, CanPauseAndContinue, CanShutdown, CanStop, DisplayName, DependentServices, MachineName, ServiceName, ServicesDependedOn, ServiceHandle, Status, ServiceType, StartType -ExcludeProperty Name $s | Export-Excel -Path TestDrive:\server1.xlsx -WorkSheetname server1 #$s is a zero based array, excel rows are 1 based and excel has a header row so Excel rows will be 2 + index in $s @@ -130,7 +130,7 @@ Describe "Compare Worksheet" { $s | Select-Object -Property ServiceName, DisplayName, StartType, ServiceType | Export-Excel -Path TestDrive:\server2.xlsx -WorkSheetname server2 #Assume default worksheet name, (sheet1) and column header for key ("name") - $comp = compare-WorkSheet "TestDrive:\server1.xlsx" "TestDrive:\server2.xlsx" -WorkSheetName server1,server2 -Key ServiceName -Property DisplayName,StartType -AllDataBackgroundColor ([System.Drawing.Color]::AliceBlue) -BackgroundColor ([System.Drawing.Color]::White) -FontColor ([System.Drawing.Color]::Red) | Sort-Object _row,_file + $comp = Compare-Worksheet "TestDrive:\server1.xlsx" "TestDrive:\server2.xlsx" -WorkSheetName server1,server2 -Key ServiceName -Property DisplayName,StartType -AllDataBackgroundColor ([System.Drawing.Color]::AliceBlue) -BackgroundColor ([System.Drawing.Color]::White) -FontColor ([System.Drawing.Color]::Red) | Sort-Object _row,_file $xl1 = Open-ExcelPackage -Path "TestDrive:\server1.xlsx" $xl2 = Open-ExcelPackage -Path "TestDrive:\server2.xlsx" $s1Sheet = $xl1.Workbook.Worksheets["server1"] @@ -188,7 +188,7 @@ Describe "Compare Worksheet" { Describe "Merge Worksheet" { BeforeAll { Remove-Item -Path "TestDrive:\server*.xlsx" , "TestDrive:\combined*.xlsx" -ErrorAction SilentlyContinue - [System.Collections.ArrayList]$s = get-service | Select-Object -first 25 -Property * + [System.Collections.ArrayList]$s = Get-service | Select-Object -first 25 -Property * $s | Export-Excel -Path TestDrive:\server1.xlsx @@ -255,7 +255,7 @@ Describe "Merge Multiple sheets" { Context "Merge 3 sheets with 3 properties" { BeforeAll { Remove-Item -Path "TestDrive:\server*.xlsx" , "TestDrive:\combined*.xlsx" -ErrorAction SilentlyContinue - [System.Collections.ArrayList]$s = get-service | Select-Object -first 25 -Property Name,DisplayName,StartType + [System.Collections.ArrayList]$s = Get-service | Select-Object -first 25 -Property Name,DisplayName,StartType $s | Export-Excel -Path TestDrive:\server1.xlsx #$s is a zero based array, excel rows are 1 based and excel has a header row so Excel rows will be 2 + index in $s diff --git a/__tests__/ConvertFromExcelToSQLInsert.tests.ps1 b/__tests__/ConvertFromExcelToSQLInsert.tests.ps1 index cd1fb90..7729f53 100644 --- a/__tests__/ConvertFromExcelToSQLInsert.tests.ps1 +++ b/__tests__/ConvertFromExcelToSQLInsert.tests.ps1 @@ -1,4 +1,4 @@ -if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { +if (-not (Get-command Import-Excel -ErrorAction SilentlyContinue)) { Import-Module $PSScriptRoot\..\ImportExcel.psd1 } $xlFile = "TestDrive:\testSQL.xlsx" diff --git a/__tests__/Copy-ExcelWorksheet.Tests.ps1 b/__tests__/Copy-ExcelWorksheet.Tests.ps1 index 4e2b9c1..3ebcf4c 100644 --- a/__tests__/Copy-ExcelWorksheet.Tests.ps1 +++ b/__tests__/Copy-ExcelWorksheet.Tests.ps1 @@ -36,7 +36,7 @@ Describe "Copy-Worksheet" { } | Export-Excel -NoNumberConversion IPAddress, StrLeadZero, StrAltPhone2 -WorkSheetname MixedTypes -Path $path2 Context "Simplest copy" { BeforeAll { - Copy-ExcelWorkSheet -SourceWorkbook $path1 -DestinationWorkbook $path2 + Copy-ExcelWorksheet -SourceWorkbook $path1 -DestinationWorkbook $path2 $excel = Open-ExcelPackage -Path $path2 $ws = $excel.Workbook.Worksheets["Processes"] } @@ -48,7 +48,7 @@ Describe "Copy-Worksheet" { } Context "Mixed types using a package object" { BeforeAll { - Copy-ExcelWorkSheet -SourceWorkbook $excel -DestinationWorkbook $excel -DestinationWorkSheet "CopyOfMixedTypes" + Copy-ExcelWorksheet -SourceWorkbook $excel -DestinationWorkbook $excel -DestinationWorkSheet "CopyOfMixedTypes" Close-ExcelPackage -ExcelPackage $excel $excel = Open-ExcelPackage -Path $path2 $ws = $Excel.Workbook.Worksheets[3] @@ -108,10 +108,10 @@ Describe "Copy-Worksheet" { $targetSheets = "1.1.2019", "1.4.2019" $targetSheets | ForEach-Object { - Copy-ExcelWorkSheet -SourceWorkbook $xlfile -DestinationWorkbook $xlfileArchive -SourceWorkSheet $_ -DestinationWorkSheet $_ + Copy-ExcelWorksheet -SourceWorkbook $xlfile -DestinationWorkbook $xlfileArchive -SourceWorkSheet $_ -DestinationWorkSheet $_ } - $targetSheets | ForEach-Object { Remove-WorkSheet -FullName $xlfile -WorksheetName $_ } + $targetSheets | ForEach-Object { Remove-Worksheet -FullName $xlfile -WorksheetName $_ } (Get-ExcelSheetInfo -Path $xlfile ).Count | Should Be 3 } @@ -131,7 +131,7 @@ Describe "Copy-Worksheet" { "Hello World" | Export-Excel $xlfile -WorksheetName $_ } $e = Open-ExcelPackage $xlfile - $e.Workbook.Worksheets | Copy-ExcelWorkSheet -DestinationWorkbook $xlfileArchive + $e.Workbook.Worksheets | Copy-ExcelWorksheet -DestinationWorkbook $xlfileArchive Close-ExcelPackage -NoSave $e } it "Should copy sheets piped into the command " { diff --git a/__tests__/Export-Excel.Tests.ps1 b/__tests__/Export-Excel.Tests.ps1 index ad34a80..aaeae93 100644 --- a/__tests__/Export-Excel.Tests.ps1 +++ b/__tests__/Export-Excel.Tests.ps1 @@ -2,7 +2,7 @@ [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidAssignmentToAutomaticVariable", "", Justification='Sets IsWindows on pre-6.0 only')] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')] param() -if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { +if (-not (Get-command Import-Excel -ErrorAction SilentlyContinue)) { Import-Module $PSScriptRoot\..\ImportExcel.psd1 } if ($null -eq $IsWindows) {$IsWindows = [environment]::OSVersion.Platform -like "win*"} @@ -397,7 +397,7 @@ Describe ExportExcel { } } - #Test adding mutliple conditional blocks and using the minimal syntax for new-ConditionalText + #Test adding mutliple conditional blocks and using the minimal syntax for New-ConditionalText $path = "TestDrive:\test.xlsx" Remove-item -Path $path -ErrorAction SilentlyContinue @@ -523,15 +523,15 @@ Describe ExportExcel { Context " # Add-Worksheet inserted sheets, moved them correctly, and copied a sheet" { $path = "TestDrive:\test.xlsx" - #Test the -CopySource and -Movexxxx parameters for Add-WorkSheet + #Test the -CopySource and -Movexxxx parameters for Add-Worksheet $Excel = Open-ExcelPackage $path #At this point Sheets Should be in the order Sheet1, Processes, ProcessesPivotTable - $null = Add-WorkSheet -ExcelPackage $Excel -WorkSheetname "Processes" -MoveToEnd # order now Sheet1, ProcessesPivotTable, Processes - $null = Add-WorkSheet -ExcelPackage $Excel -WorkSheetname "NewSheet" -MoveAfter "*" -CopySource ($excel.Workbook.Worksheets["Sheet1"]) # Now its NewSheet, Sheet1, ProcessesPivotTable, Processes - $null = Add-WorkSheet -ExcelPackage $Excel -WorkSheetname "Sheet1" -MoveAfter "Processes" # Now its NewSheet, ProcessesPivotTable, Processes, Sheet1 - $null = Add-WorkSheet -ExcelPackage $Excel -WorkSheetname "Another" -MoveToStart # Now its Another, NewSheet, ProcessesPivotTable, Processes, Sheet1 - $null = Add-WorkSheet -ExcelPackage $Excel -WorkSheetname "NearDone" -MoveBefore 5 # Now its Another, NewSheet, ProcessesPivotTable, Processes, NearDone ,Sheet1 - $null = Add-WorkSheet -ExcelPackage $Excel -WorkSheetname "OneLast" -MoveBefore "ProcessesPivotTable" # Now its Another, NewSheet, Onelast, ProcessesPivotTable, Processes,NearDone ,Sheet1 + $null = Add-Worksheet -ExcelPackage $Excel -WorkSheetname "Processes" -MoveToEnd # order now Sheet1, ProcessesPivotTable, Processes + $null = Add-Worksheet -ExcelPackage $Excel -WorkSheetname "NewSheet" -MoveAfter "*" -CopySource ($excel.Workbook.Worksheets["Sheet1"]) # Now its NewSheet, Sheet1, ProcessesPivotTable, Processes + $null = Add-Worksheet -ExcelPackage $Excel -WorkSheetname "Sheet1" -MoveAfter "Processes" # Now its NewSheet, ProcessesPivotTable, Processes, Sheet1 + $null = Add-Worksheet -ExcelPackage $Excel -WorkSheetname "Another" -MoveToStart # Now its Another, NewSheet, ProcessesPivotTable, Processes, Sheet1 + $null = Add-Worksheet -ExcelPackage $Excel -WorkSheetname "NearDone" -MoveBefore 5 # Now its Another, NewSheet, ProcessesPivotTable, Processes, NearDone ,Sheet1 + $null = Add-Worksheet -ExcelPackage $Excel -WorkSheetname "OneLast" -MoveBefore "ProcessesPivotTable" # Now its Another, NewSheet, Onelast, ProcessesPivotTable, Processes,NearDone ,Sheet1 Close-ExcelPackage $Excel $Excel = Open-ExcelPackage $path @@ -735,10 +735,10 @@ Describe ExportExcel { Set-ExcelRange -Address $sheet.Cells["E1:H1048576"] -HorizontalAlignment Right -NFormat "#,###" Set-ExcelRange -Address $sheet.Column(4) -HorizontalAlignment Right -NFormat "#,##0.0" -Bold Set-ExcelRange -Address $sheet.Row(1) -Bold -HorizontalAlignment Center - Add-ConditionalFormatting -WorkSheet $sheet -Range "D2:D1048576" -DataBarColor ([System.Drawing.Color]::Red) + Add-ConditionalFormatting -Worksheet $sheet -Range "D2:D1048576" -DataBarColor ([System.Drawing.Color]::Red) #test Add-ConditionalFormatting -passthru and using a range (and no worksheet) $rule = Add-ConditionalFormatting -passthru -Address $sheet.cells["C:C"] -RuleType TopPercent -ConditionValue 20 -Bold -StrikeThru - Add-ConditionalFormatting -WorkSheet $sheet -Range "G2:G1048576" -RuleType GreaterThan -ConditionValue "104857600" -ForeGroundColor ([System.Drawing.Color]::Red) -Bold -Italic -Underline -BackgroundColor ([System.Drawing.Color]::Beige) -BackgroundPattern LightUp -PatternColor ([System.Drawing.Color]::Gray) + Add-ConditionalFormatting -Worksheet $sheet -Range "G2:G1048576" -RuleType GreaterThan -ConditionValue "104857600" -ForeGroundColor ([System.Drawing.Color]::Red) -Bold -Italic -Underline -BackgroundColor ([System.Drawing.Color]::Beige) -BackgroundPattern LightUp -PatternColor ([System.Drawing.Color]::Gray) #Test Set-ExcelRange with a column if ($isWindows) { foreach ($c in 5..9) {Set-ExcelRange $sheet.Column($c) -AutoFit } } Add-PivotTable -PivotTableName "PT_Procs" -ExcelPackage $excel -SourceWorkSheet 1 -PivotRows Company -PivotData @{'Name' = 'Count'} -IncludePivotChart -ChartType ColumnClustered -NoLegend @@ -810,8 +810,8 @@ Describe ExportExcel { Remove-Item -Path $path -ErrorAction SilentlyContinue #Test we haven't missed any parameters on New-ChartDefinition which are on add chart or vice versa. - $ParamChk1 = (get-command Add-ExcelChart ).Parameters.Keys.where({-not (get-command New-ExcelChartDefinition).Parameters.ContainsKey($_) }) | Sort-Object - $ParamChk2 = (get-command New-ExcelChartDefinition).Parameters.Keys.where({-not (get-command Add-ExcelChart ).Parameters.ContainsKey($_) }) + $ParamChk1 = (Get-command Add-ExcelChart ).Parameters.Keys.where({-not (Get-command New-ExcelChartDefinition).Parameters.ContainsKey($_) }) | Sort-Object + $ParamChk2 = (Get-command New-ExcelChartDefinition).Parameters.Keys.where({-not (Get-command Add-ExcelChart ).Parameters.ContainsKey($_) }) it "Found the same parameters for Add-ExcelChart and New-ExcelChartDefinintion " { $ParamChk1.count | Should be 3 $ParamChk1[0] | Should be "PassThru" @@ -872,7 +872,7 @@ Describe ExportExcel { -Column 2 -ColumnOffSetPixels 35 -Width 800 -XAxisTitleText "Degrees" -XAxisTitleBold -XAxisTitleSize 12 -XMajorUnit 30 -XMinorUnit 10 -XMinValue 0 -XMaxValue 361 -XAxisNumberformat "000" ` -YMinValue -1.25 -YMaxValue 1.25 -YMajorUnit 0.25 -YAxisNumberformat "0.00" -YAxisTitleText "Sine" -YAxisTitleBold -YAxisTitleSize 12 ` -LegendSize 8 -legendBold -LegendPosition Bottom - Add-ConditionalFormatting -WorkSheet $excel.Workbook.Worksheets["Sinx"] -Range "B2:B362" -RuleType LessThan -ConditionValue "=B1" -ForeGroundColor ([System.Drawing.Color]::Red) + Add-ConditionalFormatting -Worksheet $excel.Workbook.Worksheets["Sinx"] -Range "B2:B362" -RuleType LessThan -ConditionValue "=B1" -ForeGroundColor ([System.Drawing.Color]::Red) $ws = $Excel.Workbook.Worksheets["Sinx"] $d = $ws.Drawings[0] It "Controled the axes and title and legend of the chart " { diff --git a/__tests__/First10Races.tests.ps1 b/__tests__/First10Races.tests.ps1 index 4d913b5..995fe41 100644 --- a/__tests__/First10Races.tests.ps1 +++ b/__tests__/First10Races.tests.ps1 @@ -32,7 +32,7 @@ Describe "Creating small named ranges with hyperlinks" { #create a table which covers all the data. And define a pivot table which uses the same address range. $table = Add-ExcelTable -PassThru -Range $worksheet.cells[$topRow, 1, $lastDataRow, $columns] -TableName "AllResults" -TableStyle Light4 ` - -ShowHeader -ShowFilter -ShowColumnStripes -ShowRowStripes:$false -ShowFirstColumn:$false -ShowLastColumn:$false -ShowTotal:$false #Test Add-ExcelTable outside export-Excel with as many options as possible. + -ShowHeader -ShowFilter -ShowColumnStripes -ShowRowStripes:$false -ShowFirstColumn:$false -ShowLastColumn:$false -ShowTotal:$false #Test Add-ExcelTable outside Export-Excel with as many options as possible. $pt = New-PivotTableDefinition -PivotTableName Analysis -SourceWorkSheet $worksheet -SourceRange $table.address.address -PivotRows Driver -PivotData @{Points = "SUM"} -PivotTotals None $cf = Add-ConditionalFormatting -Address $worksheet.cells[$topRow, $columns, $lastDataRow, $columns] -ThreeIconsSet Arrows -Passthru #Test using cells[r1,c1,r2,c2] @@ -42,15 +42,15 @@ Describe "Creating small named ranges with hyperlinks" { Add-ConditionalFormatting -Address $worksheet.cells["FinishPosition"] -RuleType Equal -ConditionValue 1 -ForeGroundColor ([System.Drawing.Color]::Purple) -Bold -Priority 1 -StopIfTrue #Test Priority and stopIfTrue and using range name Add-ConditionalFormatting -Address $worksheet.Cells["GridPosition"] -RuleType ThreeColorScale -Reverse #Test Reverse $ct = New-ConditionalText -Text "Ferrari" - $ct2 = New-ConditionalText -Range $worksheet.Names["FinishPosition"].Address -ConditionalType LessThanOrEqual -Text 3 -ConditionalText ([System.Drawing.Color]::Red) -Background ([System.Drawing.Color]::White) #Test new-conditionalText in shortest and longest forms. + $ct2 = New-ConditionalText -Range $worksheet.Names["FinishPosition"].Address -ConditionalType LessThanOrEqual -Text 3 -ConditionalText ([System.Drawing.Color]::Red) -Background ([System.Drawing.Color]::White) #Test New-ConditionalText in shortest and longest forms. #Create links for each group name (race) and Export them so they start at Cell A1; create a pivot table with definition just created, save the file and open in Excel $excel = $results | ForEach-Object {(New-Object -TypeName OfficeOpenXml.ExcelHyperLink -ArgumentList "Sheet1!$($_.Name)" , "$($_.name) GP")} | #Test Exporting Hyperlinks with display property. Export-Excel -ExcelPackage $excel -AutoSize -PivotTableDefinition $pt -Calculate -ConditionalFormat $ct, $ct2 -PassThru #Test conditional text rules in conditional format (orignally icon sets only ) - $null = Add-WorkSheet -ExcelPackage $excel -WorksheetName "Points1" + $null = Add-Worksheet -ExcelPackage $excel -WorksheetName "Points1" Add-PivotTable -PivotTableName "Points1" -Address $excel.Points1.Cells["A1"] -ExcelPackage $excel -SourceWorkSheet sheet1 -SourceRange $excel.Sheet1.Tables[0].Address.Address -PivotRows Driver, Date -PivotData @{Points = "SUM"} -GroupDateRow Date -GroupDatePart Years, Months - $null = Add-WorkSheet -ExcelPackage $excel -WorksheetName "Places1" + $null = Add-Worksheet -ExcelPackage $excel -WorksheetName "Places1" $newpt = Add-PivotTable -PivotTableName "Places1" -Address $excel.Places1.Cells["A1"] -ExcelPackage $excel -SourceWorkSheet sheet1 -SourceRange $excel.Sheet1.Tables[0].Address.Address -PivotRows Driver, FinishPosition -PivotData @{Date = "Count"} -GroupNumericRow FinishPosition -GroupNumericMin 1 -GroupNumericMax 25 -GroupNumericInterval 3 -PassThru $newpt.RowFields[0].SubTotalFunctions = [OfficeOpenXml.Table.PivotTable.eSubTotalFunctions]::None Close-ExcelPackage -ExcelPackage $excel diff --git a/__tests__/FunctionAlias.tests.ps1 b/__tests__/FunctionAlias.tests.ps1 index 8468109..2a813a4 100644 --- a/__tests__/FunctionAlias.tests.ps1 +++ b/__tests__/FunctionAlias.tests.ps1 @@ -1,5 +1,5 @@ #Requires -Modules Pester -if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { +if (-not (Get-command Import-Excel -ErrorAction SilentlyContinue)) { Import-Module $PSScriptRoot\..\ImportExcel.psd1 } diff --git a/__tests__/ImportExcelHeaderName.tests.ps1 b/__tests__/ImportExcelHeaderName.tests.ps1 index dfc2f72..cff85bc 100644 --- a/__tests__/ImportExcelHeaderName.tests.ps1 +++ b/__tests__/ImportExcelHeaderName.tests.ps1 @@ -3,19 +3,19 @@ $xlfile = "TestDrive:\testImportExcel.xlsx" Describe "Import-Excel on a sheet with no headings" { BeforeAll { - $xl = "" | export-excel $xlfile -PassThru + $xl = "" | Export-excel $xlfile -PassThru - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range A1 -Value 'A' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range B1 -Value 'B' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range C1 -Value 'C' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range A1 -Value 'A' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range B1 -Value 'B' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range C1 -Value 'C' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range A2 -Value 'D' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range B2 -Value 'E' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range C2 -Value 'F' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range A2 -Value 'D' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range B2 -Value 'E' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range C2 -Value 'F' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range A3 -Value 'G' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range B3 -Value 'H' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range C3 -Value 'I' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range A3 -Value 'G' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range B3 -Value 'H' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range C3 -Value 'I' Close-ExcelPackage $xl } @@ -158,22 +158,22 @@ Describe "Import-Excel on a sheet with no headings" { It "Should" { $xlfile = "TestDrive:\testImportExcelSparse.xlsx" - $xl = "" | export-excel $xlfile -PassThru + $xl = "" | Export-excel $xlfile -PassThru - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range A1 -Value 'Chuck' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range B1 -Value '' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range C1 -Value 'Norris' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range D1 -Value 'California' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range A1 -Value 'Chuck' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range B1 -Value '' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range C1 -Value 'Norris' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range D1 -Value 'California' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range A2 -Value '' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range B2 -Value '' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range C2 -Value '' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range D2 -Value '' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range A2 -Value '' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range B2 -Value '' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range C2 -Value '' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range D2 -Value '' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range A3 -Value 'Jean-Claude' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range B3 -Value '' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range C3 -Value 'Vandamme' - Set-ExcelRange -WorkSheet $xl.Sheet1 -Range D3 -Value 'Brussels' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range A3 -Value 'Jean-Claude' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range B3 -Value '' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range C3 -Value 'Vandamme' + Set-ExcelRange -Worksheet $xl.Sheet1 -Range D3 -Value 'Brussels' Close-ExcelPackage $xl diff --git a/__tests__/ImportExcelTests/Simple.tests.ps1 b/__tests__/ImportExcelTests/Simple.tests.ps1 index a8a48fe..ce6df75 100644 --- a/__tests__/ImportExcelTests/Simple.tests.ps1 +++ b/__tests__/ImportExcelTests/Simple.tests.ps1 @@ -1,6 +1,6 @@ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')] Param() -if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { +if (-not (Get-command Import-Excel -ErrorAction SilentlyContinue)) { Import-Module $PSScriptRoot\..\..\ImportExcel.psd1 } Describe "Tests" { diff --git a/__tests__/InputItemParameter.tests.ps1 b/__tests__/InputItemParameter.tests.ps1 index 6eb6f9e..53939b3 100644 --- a/__tests__/InputItemParameter.tests.ps1 +++ b/__tests__/InputItemParameter.tests.ps1 @@ -181,7 +181,7 @@ Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking I Close-ExcelPackage $excel Context "Import As Text returns text values" { - $x = import-excel $path -WorksheetName sheet3 -AsText StartTime,hand* | Select-Object -last 1 + $x = Import-excel $path -WorksheetName sheet3 -AsText StartTime,hand* | Select-Object -last 1 it "Had fields of type string, not date or int, where specified as ASText " { $x.Handles.GetType().Name | should be "String" $x.StartTime.GetType().Name | should be "String" diff --git a/__tests__/PasswordProtection.tests.ps1 b/__tests__/PasswordProtection.tests.ps1 index eea9fc7..c2bc679 100644 --- a/__tests__/PasswordProtection.tests.ps1 +++ b/__tests__/PasswordProtection.tests.ps1 @@ -25,7 +25,7 @@ Describe "Password Support" { {Import-Excel $Path } | should throw } it "Could read the file when the password was included " { - (import-excel $path -Password $password).count | should be 20 + (Import-excel $path -Password $password).count | should be 20 } } } diff --git a/__tests__/ProtectWorksheet.tests.ps1 b/__tests__/ProtectWorksheet.tests.ps1 index 28c65b7..6d7fab0 100644 --- a/__tests__/ProtectWorksheet.tests.ps1 +++ b/__tests__/ProtectWorksheet.tests.ps1 @@ -15,7 +15,7 @@ Apple, New York, 1200,700 $ws = $excel.sheet1 - Set-WorkSheetProtection -WorkSheet $ws -IsProtected -BlockEditObject -AllowFormatRows -UnLockAddress "1:1" + Set-WorksheetProtection -Worksheet $ws -IsProtected -BlockEditObject -AllowFormatRows -UnLockAddress "1:1" Close-ExcelPackage -ExcelPackage $excel $excel = Open-ExcelPackage -Path $path diff --git a/__tests__/RangePassing.ps1 b/__tests__/RangePassing.ps1 index 25de3b7..c7f4300 100644 --- a/__tests__/RangePassing.ps1 +++ b/__tests__/RangePassing.ps1 @@ -16,11 +16,11 @@ describe "Consistent passing of ranges." { $warnvar | should not beNullOrEmpty $excel.Services.ConditionalFormatting.Count | Should be 2 $warnvar = $null - Add-ConditionalFormatting $excel.Services.Column(3) -WorkSheet $excel.Services` + Add-ConditionalFormatting $excel.Services.Column(3) -Worksheet $excel.Services` -underline -RuleType ContainsText -ConditionValue "Windows" -WarningVariable warnvar -WarningAction SilentlyContinue $warnvar | should beNullOrEmpty $excel.Services.ConditionalFormatting.Count | Should be 3 - {Add-ConditionalFormatting "Status" -WorkSheet $excel.Services ` + {Add-ConditionalFormatting "Status" -Worksheet $excel.Services ` -ForeGroundColor ([System.Drawing.Color]::Green) -RuleType ContainsText -ConditionValue "Running"} | Should not throw $excel.Services.ConditionalFormatting.Count | Should be 4 } @@ -33,36 +33,36 @@ describe "Consistent passing of ranges." { {Add-ConditionalFormatting $excel.Services.Tables["ServiceTable"].Address ` -Bold -RuleType ContainsText -ConditionValue "windows" } | Should not throw $excel.Services.ConditionalFormatting.Count | Should be 2 - {Add-ConditionalFormatting -WorkSheet $excel.Services -Address "a:a" ` + {Add-ConditionalFormatting -Worksheet $excel.Services -Address "a:a" ` -RuleType ContainsText -ConditionValue "stopped" -ForeGroundColor ([System.Drawing.Color]::Red) } | Should not throw $excel.Services.ConditionalFormatting.Count | Should be 3 } Close-ExcelPackage -NoSave $excel } - Context "Formating (Set-ExcelRange or its alias set-Format) " { + Context "Formating (Set-ExcelRange or its alias Set-Format) " { it "accepts Named Range, cells['Name'], cells['A1:Z9'], row, Worksheet + 'A1:Z9'" { $excel = Get-Service | Export-Excel -Path test2.xlsx -WorksheetName Services -PassThru -AutoSize -DisplayPropertySet -RangeName servicerange -Title "Services on $Env:COMPUTERNAME" - {set-format $excel.Services.Names["serviceRange"] -Bold } | Should Not Throw + {Set-format $excel.Services.Names["serviceRange"] -Bold } | Should Not Throw $excel.Services.cells["B2"].Style.Font.Bold | Should be $true {Set-ExcelRange -Range $excel.Services.Cells["serviceRange"] -italic:$true } | Should not throw $excel.Services.cells["C3"].Style.Font.Italic | Should be $true - {set-format $excel.Services.Row(4) -underline -Bold:$false } | Should not throw + {Set-format $excel.Services.Row(4) -underline -Bold:$false } | Should not throw $excel.Services.cells["A4"].Style.Font.UnderLine | Should be $true $excel.Services.cells["A4"].Style.Font.Bold | Should not be $true {Set-ExcelRange $excel.Services.Cells["A3:B3"] -StrikeThru } | Should not throw $excel.Services.cells["B3"].Style.Font.Strike | Should be $true - {Set-ExcelRange -WorkSheet $excel.Services -Range "A5:B6" -FontSize 8 } | Should not throw + {Set-ExcelRange -Worksheet $excel.Services -Range "A5:B6" -FontSize 8 } | Should not throw $excel.Services.cells["A5"].Style.Font.Size | Should be 8 } Close-ExcelPackage -NoSave $excel it "Accepts Table, Table.Address , worksheet + Name, Column," { $excel = Get-Service | Export-Excel -Path test2.xlsx -WorksheetName Services -PassThru -AutoNameRange -AutoSize -DisplayPropertySet -TableName servicetable -Title "Services on $Env:COMPUTERNAME" - {set-ExcelRange $excel.Services.Tables[0] -Italic } | Should not throw + {Set-ExcelRange $excel.Services.Tables[0] -Italic } | Should not throw $excel.Services.cells["C3"].Style.Font.Italic | Should be $true - {set-format $excel.Services.Tables["ServiceTable"].Address -Underline } | Should not throw + {Set-format $excel.Services.Tables["ServiceTable"].Address -Underline } | Should not throw $excel.Services.cells["C3"].Style.Font.UnderLine | Should be $true - {Set-ExcelRange -WorkSheet $excel.Services -Range "Name" -Bold } | Should not throw + {Set-ExcelRange -Worksheet $excel.Services -Range "Name" -Bold } | Should not throw $excel.Services.cells["B4"].Style.Font.Bold | Should be $true {$excel.Services.Column(3) | Set-ExcelRange -FontColor ([System.Drawing.Color]::Red) } | Should not throw $excel.Services.cells["C4"].Style.Font.Color.Rgb | Should be "FFFF0000" diff --git a/__tests__/Remove-WorkSheet.tests.ps1 b/__tests__/Remove-WorkSheet.tests.ps1 index 427281d..45a9ae3 100644 --- a/__tests__/Remove-WorkSheet.tests.ps1 +++ b/__tests__/Remove-WorkSheet.tests.ps1 @@ -1,5 +1,5 @@ #Requires -Modules Pester -if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { +if (-not (Get-command Import-Excel -ErrorAction SilentlyContinue)) { Import-Module $PSScriptRoot\..\ImportExcel.psd1 } Describe "Remove Worksheet" { @@ -29,11 +29,11 @@ John,20 } it "Should throw about the Path".PadRight(87) { - {Remove-WorkSheet} | Should throw 'Remove-WorkSheet requires the and Excel file' + {Remove-Worksheet} | Should throw 'Remove-Worksheet requires the and Excel file' } it "Should delete Target2".PadRight(87) { - Remove-WorkSheet -Path $xlFile1 -WorksheetName Target2 + Remove-Worksheet -Path $xlFile1 -WorksheetName Target2 $actual = Get-ExcelSheetInfo -Path $xlFile1 @@ -44,7 +44,7 @@ John,20 } it "Should delete Sheet1".PadRight(87) { - Remove-WorkSheet -Path $xlFile1 + Remove-Worksheet -Path $xlFile1 $actual = Get-ExcelSheetInfo -Path $xlFile1 @@ -55,7 +55,7 @@ John,20 } it "Should delete multiple sheets".PadRight(87) { - Remove-WorkSheet -Path $xlFile1 -WorksheetName Target1, Sheet1 + Remove-Worksheet -Path $xlFile1 -WorksheetName Target1, Sheet1 $actual = Get-ExcelSheetInfo -Path $xlFile1 @@ -66,7 +66,7 @@ John,20 it "Should delete sheet from multiple workbooks".PadRight(87) { - Get-ChildItem "TestDrive:\RemoveWorsheet*.xlsx" | Remove-WorkSheet + Get-ChildItem "TestDrive:\RemoveWorsheet*.xlsx" | Remove-Worksheet $actual = Get-ExcelSheetInfo -Path $xlFile1 diff --git a/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 b/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 index 96442e4..0ecf7d6 100644 --- a/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 +++ b/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 @@ -48,27 +48,27 @@ Describe "Number format expansion and setting" { $excel = 1..32 | ForEach-Object {$n} | Export-Excel -Path $path -show -WorksheetName s2 -PassThru $ws = $excel.Workbook.Worksheets[1] - Set-ExcelRange -WorkSheet $ws -Range "A1" -numberFormat 'General' - Set-ExcelRange -WorkSheet $ws -Range "A2" -numberFormat 'Number' - Set-ExcelRange -WorkSheet $ws -Range "A3" -numberFormat 'Percentage' - Set-ExcelRange -WorkSheet $ws -Range "A4" -numberFormat 'Scientific' - Set-ExcelRange -WorkSheet $ws -Range "A5" -numberFormat 'Fraction' - Set-ExcelRange -WorkSheet $ws -Range "A6" -numberFormat 'Short Date' - Set-ExcelRange -WorkSheet $ws -Range "A7" -numberFormat 'Short Time' - Set-ExcelRange -WorkSheet $ws -Range "A8" -numberFormat 'Long Time' - Set-ExcelRange -WorkSheet $ws -Range "A9" -numberFormat 'Date-Time' - Set-ExcelRange -WorkSheet $ws -Range "A10" -numberFormat 'Currency' - Set-ExcelRange -WorkSheet $ws -Range "A11" -numberFormat 'Text' - Set-ExcelRange -WorkSheet $ws -Range "A12" -numberFormat 'h:mm AM/PM' - Set-ExcelRange -WorkSheet $ws -Range "A13" -numberFormat 'h:mm:ss AM/PM' - Set-ExcelRange -WorkSheet $ws -Range "A14" -numberFormat 'mm:ss' - Set-ExcelRange -WorkSheet $ws -Range "A15" -numberFormat '[h]:mm:ss' - Set-ExcelRange -WorkSheet $ws -Range "A16" -numberFormat 'mmss.0' - Set-ExcelRange -WorkSheet $ws -Range "A17" -numberFormat 'd-mmm-yy' - Set-ExcelRange -WorkSheet $ws -Range "A18" -numberFormat 'd-mmm' - Set-ExcelRange -WorkSheet $ws -Range "A19" -numberFormat 'mmm-yy' - Set-ExcelRange -WorkSheet $ws -Range "A20" -numberFormat '0' - Set-ExcelRange -WorkSheet $ws -Range "A21" -numberFormat '0.00' + Set-ExcelRange -Worksheet $ws -Range "A1" -numberFormat 'General' + Set-ExcelRange -Worksheet $ws -Range "A2" -numberFormat 'Number' + Set-ExcelRange -Worksheet $ws -Range "A3" -numberFormat 'Percentage' + Set-ExcelRange -Worksheet $ws -Range "A4" -numberFormat 'Scientific' + Set-ExcelRange -Worksheet $ws -Range "A5" -numberFormat 'Fraction' + Set-ExcelRange -Worksheet $ws -Range "A6" -numberFormat 'Short Date' + Set-ExcelRange -Worksheet $ws -Range "A7" -numberFormat 'Short Time' + Set-ExcelRange -Worksheet $ws -Range "A8" -numberFormat 'Long Time' + Set-ExcelRange -Worksheet $ws -Range "A9" -numberFormat 'Date-Time' + Set-ExcelRange -Worksheet $ws -Range "A10" -numberFormat 'Currency' + Set-ExcelRange -Worksheet $ws -Range "A11" -numberFormat 'Text' + Set-ExcelRange -Worksheet $ws -Range "A12" -numberFormat 'h:mm AM/PM' + Set-ExcelRange -Worksheet $ws -Range "A13" -numberFormat 'h:mm:ss AM/PM' + Set-ExcelRange -Worksheet $ws -Range "A14" -numberFormat 'mm:ss' + Set-ExcelRange -Worksheet $ws -Range "A15" -numberFormat '[h]:mm:ss' + Set-ExcelRange -Worksheet $ws -Range "A16" -numberFormat 'mmss.0' + Set-ExcelRange -Worksheet $ws -Range "A17" -numberFormat 'd-mmm-yy' + Set-ExcelRange -Worksheet $ws -Range "A18" -numberFormat 'd-mmm' + Set-ExcelRange -Worksheet $ws -Range "A19" -numberFormat 'mmm-yy' + Set-ExcelRange -Worksheet $ws -Range "A20" -numberFormat '0' + Set-ExcelRange -Worksheet $ws -Range "A21" -numberFormat '0.00' Set-ExcelRange -Address $ws.Cells[ "A22"] -NumberFormat '#,##0' Set-ExcelRange -Address $ws.Cells[ "A23"] -NumberFormat '#,##0.00' Set-ExcelRange -Address $ws.Cells[ "A24"] -NumberFormat '#,' @@ -131,8 +131,8 @@ Describe "Set-ExcelColumn, Set-ExcelRow and Set-ExcelRange" { $r = Set-ExcelRow -PassThru -Worksheet $ws -StartColumn 3 -BorderAround Thin -Italic -Underline -FontSize 14 -Value {"=sum($columnName`2:$columnName$endrow)" } -VerticalAlignment Bottom Set-ExcelRange -Address $excel.Workbook.Worksheets["Sheet1"].Cells["b3"] -HorizontalAlignment Right -VerticalAlignment Center -BorderAround Thick -BorderColor ([System.Drawing.Color]::Red) -StrikeThru Set-ExcelRange -Address $excel.Workbook.Worksheets["Sheet1"].Cells["c3"] -BorderColor ([System.Drawing.Color]::Red) -BorderTop DashDot -BorderLeft DashDotDot -BorderBottom Dashed -BorderRight Dotted - Set-ExcelRange -WorkSheet $ws -Range "E3" -Bold:$false -FontShift Superscript -HorizontalAlignment Left - Set-ExcelRange -WorkSheet $ws -Range "E1" -ResetFont -HorizontalAlignment General -FontName "Courier New" -fontSize 9 + Set-ExcelRange -Worksheet $ws -Range "E3" -Bold:$false -FontShift Superscript -HorizontalAlignment Left + Set-ExcelRange -Worksheet $ws -Range "E1" -ResetFont -HorizontalAlignment General -FontName "Courier New" -fontSize 9 Set-ExcelRange -Address $ws.Cells["E7"] -ResetFont -WrapText -BackgroundColor ([System.Drawing.Color]::AliceBlue) -BackgroundPattern DarkTrellis -PatternColor ([System.Drawing.Color]::Red) -NumberFormat "£#,###.00" Set-ExcelRange -Address $ws.Column(1) -Width 0 if (-not $env:NoAutoSize) { @@ -142,11 +142,11 @@ Describe "Set-ExcelColumn, Set-ExcelRow and Set-ExcelRange" { #Test alias Set-Format -Address $ws.row(5) -Height 0 $rr = $r.row - Set-ExcelRange -WorkSheet $ws -Range "B$rr" -Value "Total" + Set-ExcelRange -Worksheet $ws -Range "B$rr" -Value "Total" $BadHideWarnvar = $null - Set-ExcelRange -WorkSheet $ws -Range "D$rr" -Formula "=E$rr/C$rr" -Hidden -WarningVariable "BadHideWarnvar" -WarningAction SilentlyContinue + Set-ExcelRange -Worksheet $ws -Range "D$rr" -Formula "=E$rr/C$rr" -Hidden -WarningVariable "BadHideWarnvar" -WarningAction SilentlyContinue $rr ++ - Set-ExcelRange -WorkSheet $ws -Range "B$rr" -Value ([datetime]::Now) + Set-ExcelRange -Worksheet $ws -Range "B$rr" -Value ([datetime]::Now) Close-ExcelPackage $excel -Calculate diff --git a/__tests__/Validation.tests.ps1 b/__tests__/Validation.tests.ps1 index 49c7e21..c2651fe 100644 --- a/__tests__/Validation.tests.ps1 +++ b/__tests__/Validation.tests.ps1 @@ -15,11 +15,11 @@ Describe "Data validation and protection" { Context "Data Validation rules" { BeforeAll { Remove-Item $path -ErrorAction SilentlyContinue - $excelPackage = $Data | export-excel -WorksheetName "Sales" -path $path -PassThru + $excelPackage = $Data | Export-excel -WorksheetName "Sales" -path $path -PassThru $excelPackage = @('Chisel','Crowbar','Drill','Hammer','Nails','Saw','Screwdriver','Wrench') | Export-excel -ExcelPackage $excelPackage -WorksheetName Values -PassThru - $VParams = @{WorkSheet = $excelPackage.sales; ShowErrorMessage=$true; ErrorStyle='stop'; ErrorTitle='Invalid Data' } + $VParams = @{Worksheet = $excelPackage.sales; ShowErrorMessage=$true; ErrorStyle='stop'; ErrorTitle='Invalid Data' } Add-ExcelDataValidationRule @VParams -Range 'B2:B1001' -ValidationType List -Formula 'values!$a$1:$a$10' -ErrorBody "You must select an item from the list.`r`nYou can add to the list on the values page" #Bucket Add-ExcelDataValidationRule @VParams -Range 'E2:E1001' -ValidationType Integer -Operator between -Value 0 -Value2 10000 -ErrorBody 'Quantity must be a whole number between 0 and 10000' Close-ExcelPackage -ExcelPackage $excelPackage From 5e87c3f6a776d1a43b528ac21d0bc918b9bfc861 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Mon, 25 Nov 2019 23:40:51 +0000 Subject: [PATCH 16/25] fixes to casing, and some basic functions changed to advanced --- ArgumentCompletion.ps1 | 4 +- CI/Test-SingleFunctions.ps1 | 48 +++++++++++-------- Examples/CustomizeExportExcel/Out-Excel.ps1 | 2 +- Examples/Index - Music.ps1 | 2 +- Export-charts.ps1 | 2 +- .../Add-ConditionalFormatting.ps1 | 6 +-- ExportedCommands/Add-ExcelChart.ps1 | 2 +- .../Add-ExcelDataValidationRule.ps1 | 4 +- ExportedCommands/Add-PivotTable.ps1 | 2 +- ExportedCommands/Close-ExcelPackage.ps1 | 7 ++- ExportedCommands/Compare-Worksheet.ps1 | 10 ++-- .../Convert-ExcelRangeToImage.ps1 | 4 +- ExportedCommands/ConvertTo-ExcelXlsx.ps1 | 6 +-- ExportedCommands/Expand-NumberFormat.ps1 | 33 +------------ ExportedCommands/Export-Excel.ps1 | 2 +- ExportedCommands/Export-ExcelSheet.ps1 | 1 - .../Export-MultipleExcelSheets.ps1 | 1 - ExportedCommands/Get-ExcelSheetInfo.ps1 | 2 +- ExportedCommands/Get-ExcelWorkbookInfo.ps1 | 10 ++-- ExportedCommands/Get-Range.ps1 | 4 +- ExportedCommands/Get-XYRange.ps1 | 1 + ExportedCommands/Import-Excel.ps1 | 8 ++-- ExportedCommands/Import-UPS.ps1 | 1 + ExportedCommands/Import-USPS.ps1 | 2 +- ExportedCommands/Invoke-Sum.ps1 | 1 + ExportedCommands/Merge-MultipleSheets.ps1 | 2 +- ExportedCommands/Merge-Worksheet.ps1 | 10 ++-- ExportedCommands/New-ConditionalText.ps1 | 2 +- ExportedCommands/New-ExcelChartDefinition.ps1 | 2 +- ExportedCommands/New-ExcelStyle.ps1 | 2 +- ExportedCommands/New-PSItem.ps1 | 2 +- ExportedCommands/Open-ExcelPackage.ps1 | 4 +- ExportedCommands/Remove-Worksheet.ps1 | 4 +- ExportedCommands/Send-SQLDataToExcel.ps1 | 2 +- ExportedCommands/Set-CellStyle.ps1 | 1 + ExportedCommands/Set-ExcelColumn.ps1 | 8 ++-- ExportedCommands/Set-ExcelRange.ps1 | 4 +- ExportedCommands/Set-ExcelRow.ps1 | 8 ++-- ExportedCommands/Set-WorksheetProtection.ps1 | 6 +-- .../Update-FirstObjectProperties.ps1 | 9 ++-- GetExcelTable.ps1 | 8 ++-- ImportExcel.psm1 | 6 +-- Install.ps1 | 6 +-- 43 files changed, 118 insertions(+), 133 deletions(-) diff --git a/ArgumentCompletion.ps1 b/ArgumentCompletion.ps1 index b0268da..f7ced45 100644 --- a/ArgumentCompletion.ps1 +++ b/ArgumentCompletion.ps1 @@ -6,7 +6,7 @@ } function ListFonts { - [cmdletbinding()] + [CmdletBinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingEmptyCatchBlock", "")] param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) if (-not $script:FontFamilies) { @@ -77,7 +77,7 @@ function WorksheetArgumentCompleter { } } -If (Get-Command -ErrorAction SilentlyContinue -name Register-ArgumentCompleter) { +if (Get-Command -ErrorAction SilentlyContinue -name Register-ArgumentCompleter) { Register-ArgumentCompleter -CommandName Export-Excel -ParameterName TitleBackgroundColor -ScriptBlock $Function:ColorCompletion Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName BackgroundColor -ScriptBlock $Function:ColorCompletion Register-ArgumentCompleter -CommandName Add-ConditionalFormatting -ParameterName DataBarColor -ScriptBlock $Function:ColorCompletion diff --git a/CI/Test-SingleFunctions.ps1 b/CI/Test-SingleFunctions.ps1 index c8622cd..6c2350b 100644 --- a/CI/Test-SingleFunctions.ps1 +++ b/CI/Test-SingleFunctions.ps1 @@ -1,15 +1,14 @@  -Function Test-SingleFunction { +function Test-SingleFunction { param ( [parameter(ValueFromPipeline=$true)] - $path ) + $path ) begin { - Push-Location "C:\Users\mcp\Documents\GitHub\ImportExcel" - $exportedFunctions = (Import-LocalizedData -FileName "ImportExcel.psd1").functionsToExport - Pop-Location + $psd = Get-Content -Raw "$PSScriptRoot\..\ImportExcel.psd1" + $exportedFunctions = (Invoke-Command ([scriptblock]::Create($psd))).functionsToExport $reg = [Regex]::new(@" - function\s*[-\w]+\s*{ # The function name and opening '{' - (?: + function\s*[-\w]+\s*{ # The function name and opening '{' + (?: [^{}]+ # Match all non-braces | (? { ) # Match '{', and capture into 'open' @@ -18,27 +17,38 @@ Function Test-SingleFunction { )* (?(open)(?!)) # Fails if 'open' stack isn't empty } # Functions closing '}' -"@, 33) # 33 = ignore case and white space. - - - }# +"@, 57) # 41 = compile ignore case and white space. +$reg2 = [Regex]::new(@" + ^function\s*[-\w]+\s*{ # The function name and opening '{' + ( + \#.*?[\r\n]+ # single line comment + | # or + \s*<\#.*?\#> # <#comment block#> + | # or + \s*\[.*?\] # [attribute tags] + )* +"@, 57) +# 43 = compile, multi-line, ignore case and white space. + } process { $item = Get-item $Path $name = $item.Name -replace "\.\w+$","" Write-Verbose $name $file = Get-Content $item -Raw - $m = $reg.Matches($file) - - - #based on https://stackoverflow.com/questions/7898310/using-regex-to-balance-match-parenthesis + $m = $reg.Matches($file) + + #based on https://stackoverflow.com/questions/7898310/using-regex-to-balance-match-parenthesis if ($m.Count -eq 0) {return "Could not find $name function in $($item.name)"} elseif ($m.Count -ge 2) {return "Multiple functions in $($item.name)"} elseif ($exportedFunctions -cnotcontains $name) {return "$name not exported (or in the wrong case)"} - elseif ($m[0] -cnotmatch "^\w+\s+$name") {return "function $name in wrong case"} - elseif ($m[0] -inotmatch "^function\s*$name\s*{(\s*<\#.*?\#>|\s*\[.*?\])*\s*param") {return "No param block in $name"} - elseif ($m[0] -inotmatch "\[cmdletbinding\(" -and + elseif ($m[0] -cnotmatch "^\w+\s+$name") {return "function $name in wrong case"} + $m2 = [regex]::Match($m[0],"param",[System.Text.RegularExpressions.RegexOptions]::IgnoreCase) + if (-not $m2.Success) {return "No param block in $name"} + # elseif ($m[0] -inotmatch "(?s)^function\s*$name\s*{(\s*<\#.*?\#>|\s*\[.*?\])*\s*param") + # elseif ($reg2.IsMatch($m[0].Value)) {return "function $name has comment-based help"} + elseif ($m[0] -inotmatch "\[CmdletBinding\(" -and $m[0] -inotmatch "\[parameter\(" ) {return "$name has is not an advanced function"} elseif (-not (& $Name -?).synopsis) {return "$name has no help"} - else {return "$name OK"} + else {Write-Verbose "$name OK"} } } \ No newline at end of file diff --git a/Examples/CustomizeExportExcel/Out-Excel.ps1 b/Examples/CustomizeExportExcel/Out-Excel.ps1 index b320241..0845d24 100644 --- a/Examples/CustomizeExportExcel/Out-Excel.ps1 +++ b/Examples/CustomizeExportExcel/Out-Excel.ps1 @@ -10,7 +10,7 @@ Preset2 will set AutoFilter and add the Title "Daily Report". (see comments and code below). #> -Function Out-Excel { +function Out-Excel { [CmdletBinding(DefaultParameterSetName = 'Default')] param( [switch] diff --git a/Examples/Index - Music.ps1 b/Examples/Index - Music.ps1 index d518495..f895505 100644 --- a/Examples/Index - Music.ps1 +++ b/Examples/Index - Music.ps1 @@ -1,5 +1,5 @@ #requires -modules "Get-IndexedItem" -[cmdletbinding()] +[CmdletBinding()] Param() Remove-Item ~\documents\music.xlsx -ErrorAction SilentlyContinue [System.Diagnostics.Stopwatch]$stopwatch = [System.Diagnostics.Stopwatch]::StartNew() diff --git a/Export-charts.ps1 b/Export-charts.ps1 index d78a9a6..96c6496 100644 --- a/Export-charts.ps1 +++ b/Export-charts.ps1 @@ -10,7 +10,7 @@ Exports the charts to PNG files in MyDocuments , and returns file objects representing the newly created files #> -Param ( +param( #Path to the Excel file whose chars we will export. $Path = "C:\Users\public\Documents\stats.xlsx", #If specified, output file objects representing the image files diff --git a/ExportedCommands/Add-ConditionalFormatting.ps1 b/ExportedCommands/Add-ConditionalFormatting.ps1 index 92ce94b..dffa8d1 100644 --- a/ExportedCommands/Add-ConditionalFormatting.ps1 +++ b/ExportedCommands/Add-ConditionalFormatting.ps1 @@ -1,5 +1,5 @@ -Function Add-ConditionalFormatting { - Param ( +function Add-ConditionalFormatting { + param ( [Parameter(Mandatory = $true, Position = 0)] [Alias("Range")] $Address , @@ -50,7 +50,7 @@ ) #Allow conditional formatting to work like Set-ExcelRange (with single ADDRESS parameter), split it to get worksheet and range of cells. - If ($Address -is [OfficeOpenXml.Table.ExcelTable]) { + if ($Address -is [OfficeOpenXml.Table.ExcelTable]) { $Worksheet = $Address.Address.Worksheet $Address = $Address.Address.Address } diff --git a/ExportedCommands/Add-ExcelChart.ps1 b/ExportedCommands/Add-ExcelChart.ps1 index 1fbaf62..88a0d46 100644 --- a/ExportedCommands/Add-ExcelChart.ps1 +++ b/ExportedCommands/Add-ExcelChart.ps1 @@ -1,6 +1,6 @@ function Add-ExcelChart { - [cmdletbinding(DefaultParameterSetName = 'Worksheet')] + [CmdletBinding(DefaultParameterSetName = 'Worksheet')] [OutputType([OfficeOpenXml.Drawing.Chart.ExcelChart])] param( [Parameter(ParameterSetName = 'Worksheet', Mandatory = $true)] diff --git a/ExportedCommands/Add-ExcelDataValidationRule.ps1 b/ExportedCommands/Add-ExcelDataValidationRule.ps1 index 6658ca3..cd3f732 100644 --- a/ExportedCommands/Add-ExcelDataValidationRule.ps1 +++ b/ExportedCommands/Add-ExcelDataValidationRule.ps1 @@ -1,6 +1,6 @@ -Function Add-ExcelDataValidationRule { +function Add-ExcelDataValidationRule { [CmdletBinding()] - Param( + param( [Parameter(ValueFromPipeline = $true,Position=0)] [Alias("Address")] $Range , diff --git a/ExportedCommands/Add-PivotTable.ps1 b/ExportedCommands/Add-PivotTable.ps1 index 589870a..5a7fadb 100644 --- a/ExportedCommands/Add-PivotTable.ps1 +++ b/ExportedCommands/Add-PivotTable.ps1 @@ -1,5 +1,5 @@ function Add-PivotTable { - [cmdletbinding(defaultParameterSetName = 'ChartbyParams')] + [CmdletBinding(defaultParameterSetName = 'ChartbyParams')] [OutputType([OfficeOpenXml.Table.PivotTable.ExcelPivotTable])] param ( [Parameter(Mandatory = $true)] diff --git a/ExportedCommands/Close-ExcelPackage.ps1 b/ExportedCommands/Close-ExcelPackage.ps1 index d49425e..c2d9ad4 100644 --- a/ExportedCommands/Close-ExcelPackage.ps1 +++ b/ExportedCommands/Close-ExcelPackage.ps1 @@ -1,8 +1,7 @@ - -Function Close-ExcelPackage { +function Close-ExcelPackage { [CmdLetBinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")] - Param ( + param ( [parameter(Mandatory=$true, ValueFromPipeline=$true)] [OfficeOpenXml.ExcelPackage]$ExcelPackage, [switch]$Show, @@ -16,7 +15,7 @@ Function Close-ExcelPackage { else { if ($Calculate) { try { [OfficeOpenXml.CalculationExtension]::Calculate($ExcelPackage.Workbook) } - Catch { Write-Warning "One or more errors occured while calculating, save will continue, but there may be errors in the workbook."} + catch { Write-Warning "One or more errors occured while calculating, save will continue, but there may be errors in the workbook."} } if ($SaveAs) { $SaveAs = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($SaveAs) diff --git a/ExportedCommands/Compare-Worksheet.ps1 b/ExportedCommands/Compare-Worksheet.ps1 index 2f23ffb..05aa23a 100644 --- a/ExportedCommands/Compare-Worksheet.ps1 +++ b/ExportedCommands/Compare-Worksheet.ps1 @@ -1,8 +1,8 @@ -Function Compare-Worksheet { - [cmdletbinding(DefaultParameterSetName)] +function Compare-Worksheet { + [CmdletBinding(DefaultParameterSetName)] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification="Write host used for sub-warning level message to operator which does not form output")] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification="False positives when initializing variable in begin block")] - Param( + param( [parameter(Mandatory=$true,Position=0)] $Referencefile , [parameter(Mandatory=$true,Position=1)] @@ -29,7 +29,7 @@ #if the filenames don't resolve, give up now. try { $oneFile = ((Resolve-Path -Path $Referencefile -ErrorAction Stop).path -eq (Resolve-Path -Path $Differencefile -ErrorAction Stop).path)} - Catch { Write-Warning -Message "Could not Resolve the filenames." ; return } + catch { Write-Warning -Message "Could not Resolve the filenames." ; return } #If we have one file , we must have two different worksheet names. If we have two files we can have a single string or two strings. if ($onefile -and ( ($WorkSheetName.count -ne 2) -or $WorkSheetName[0] -eq $WorkSheetName[1] ) ) { @@ -46,7 +46,7 @@ $sheet1 = Import-Excel -Path $Referencefile -WorksheetName $WorkSheet1 @params $sheet2 = Import-Excel -Path $Differencefile -WorksheetName $WorkSheet2 @Params } - Catch {Write-Warning -Message "Could not read the worksheet from $Referencefile and/or $Differencefile." ; return } + catch {Write-Warning -Message "Could not read the worksheet from $Referencefile and/or $Differencefile." ; return } #Get Column headings and create a hash table of Name to column letter. $headings = $Sheet1[-1].psobject.Properties.name # This preserves the sequence - using Get-member would sort them alphabetically! diff --git a/ExportedCommands/Convert-ExcelRangeToImage.ps1 b/ExportedCommands/Convert-ExcelRangeToImage.ps1 index 1569201..69a4c85 100644 --- a/ExportedCommands/Convert-ExcelRangeToImage.ps1 +++ b/ExportedCommands/Convert-ExcelRangeToImage.ps1 @@ -1,6 +1,6 @@ -Function Convert-ExcelRangeToImage { +function Convert-ExcelRangeToImage { [alias("Convert-XlRangeToImage")] - Param ( + param ( [parameter(Mandatory=$true)] $Path, $workSheetname = "Sheet1" , diff --git a/ExportedCommands/ConvertTo-ExcelXlsx.ps1 b/ExportedCommands/ConvertTo-ExcelXlsx.ps1 index 21ef2f3..36c67c4 100644 --- a/ExportedCommands/ConvertTo-ExcelXlsx.ps1 +++ b/ExportedCommands/ConvertTo-ExcelXlsx.ps1 @@ -1,13 +1,13 @@ -Function ConvertTo-ExcelXlsx { +function ConvertTo-ExcelXlsx { [CmdletBinding()] - Param + param ( [parameter(Mandatory = $true, ValueFromPipeline)] [string]$Path, [parameter(Mandatory = $false)] [switch]$Force ) - Process { + process { if (-Not ($Path | Test-Path) ) { throw "File not found" } diff --git a/ExportedCommands/Expand-NumberFormat.ps1 b/ExportedCommands/Expand-NumberFormat.ps1 index cbefdbb..650a1b6 100644 --- a/ExportedCommands/Expand-NumberFormat.ps1 +++ b/ExportedCommands/Expand-NumberFormat.ps1 @@ -1,34 +1,5 @@ - -function Expand-NumberFormat { - <# - .SYNOPSIS - Converts short names for number formats to the formatting strings used in Excel - .DESCRIPTION - Where you can type a number format you can write, for example, 'Short-Date' - and the module will translate it into the format string used by Excel. - Some formats, like Short-Date change how they are presented when Excel - loads (so date will use the local ordering of year, month and Day). Other - formats change how they appear when loaded with different cultures - (depending on the country "," or "." or " " may be the thousand seperator - although Excel always stores it as ",") - .EXAMPLE - Expand-NumberFormat percentage - - Returns "0.00%" - .EXAMPLE - Expand-NumberFormat Currency - - Returns the currency format specified in the local regional settings. This - may not be the same as Excel uses. The regional settings set the currency - symbol and then whether it is before or after the number and separated with - a space or not; for negative numbers the number may be wrapped in parentheses - or a - sign might appear before or after the number and symbol. - So this returns $#,##0.00;($#,##0.00) for English US, #,##0.00 €;€#,##0.00- - for French. (Note some Eurozone countries write €1,23 and others 1,23€ ) - In French the decimal point will be rendered as a "," and the thousand - separator as a space. - #> - [cmdletbinding()] +function Expand-NumberFormat { + [CmdletBinding()] [OutputType([String])] param ( #the format string to Expand diff --git a/ExportedCommands/Export-Excel.ps1 b/ExportedCommands/Export-Excel.ps1 index 1024d41..09fc486 100644 --- a/ExportedCommands/Export-Excel.ps1 +++ b/ExportedCommands/Export-Excel.ps1 @@ -403,7 +403,7 @@ Write-Warning -Message "AutoNameRange: Property name '$targetRangeName' is also a valid Excel address and may cause issues. Consider renaming the property." } } - Catch { + catch { Write-Warning -Message "AutoNameRange: Testing '$targetRangeName' caused an error. This should be harmless, but a change of property name may be needed.." } } diff --git a/ExportedCommands/Export-ExcelSheet.ps1 b/ExportedCommands/Export-ExcelSheet.ps1 index b703d0f..27e8de5 100644 --- a/ExportedCommands/Export-ExcelSheet.ps1 +++ b/ExportedCommands/Export-ExcelSheet.ps1 @@ -1,5 +1,4 @@ function Export-ExcelSheet { - [CmdletBinding()] param ( diff --git a/ExportedCommands/Export-MultipleExcelSheets.ps1 b/ExportedCommands/Export-MultipleExcelSheets.ps1 index d8012e2..80ce9f9 100644 --- a/ExportedCommands/Export-MultipleExcelSheets.ps1 +++ b/ExportedCommands/Export-MultipleExcelSheets.ps1 @@ -1,7 +1,6 @@ function Export-MultipleExcelSheets { [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification="No suitable singular")] - param( [Parameter(Mandatory = $true)] $Path, diff --git a/ExportedCommands/Get-ExcelSheetInfo.ps1 b/ExportedCommands/Get-ExcelSheetInfo.ps1 index f4fb88a..f5c6cf3 100644 --- a/ExportedCommands/Get-ExcelSheetInfo.ps1 +++ b/ExportedCommands/Get-ExcelSheetInfo.ps1 @@ -1,4 +1,4 @@ -Function Get-ExcelSheetInfo { +function Get-ExcelSheetInfo { [CmdletBinding()] param( [Alias('FullName')] diff --git a/ExportedCommands/Get-ExcelWorkbookInfo.ps1 b/ExportedCommands/Get-ExcelWorkbookInfo.ps1 index a064314..515cce4 100644 --- a/ExportedCommands/Get-ExcelWorkbookInfo.ps1 +++ b/ExportedCommands/Get-ExcelWorkbookInfo.ps1 @@ -1,13 +1,13 @@ -Function Get-ExcelWorkbookInfo { +function Get-ExcelWorkbookInfo { [CmdletBinding()] - Param ( + param ( [Alias('FullName')] [Parameter(ValueFromPipelineByPropertyName=$true, ValueFromPipeline=$true, Mandatory=$true)] [String]$Path ) - Process { - Try { + process { + try { $Path = (Resolve-Path $Path).ProviderPath $stream = New-Object -TypeName System.IO.FileStream -ArgumentList $Path,'Open','Read','ReadWrite' @@ -20,7 +20,7 @@ $xl.Dispose() $xl = $null } - Catch { + catch { throw "Failed retrieving Excel workbook information for '$Path': $_" } } diff --git a/ExportedCommands/Get-Range.ps1 b/ExportedCommands/Get-Range.ps1 index e25db9c..d127afb 100644 --- a/ExportedCommands/Get-Range.ps1 +++ b/ExportedCommands/Get-Range.ps1 @@ -1,3 +1,5 @@ -function Get-Range ($start=0,$stop,$step=1) { +function Get-Range { + [CmdletBinding()] + param($start=0,$stop,$step=1) for ($idx = $start; $idx -lt $stop; $idx+=$step) {$idx} } \ No newline at end of file diff --git a/ExportedCommands/Get-XYRange.ps1 b/ExportedCommands/Get-XYRange.ps1 index f28c8c8..734d263 100644 --- a/ExportedCommands/Get-XYRange.ps1 +++ b/ExportedCommands/Get-XYRange.ps1 @@ -1,4 +1,5 @@ function Get-XYRange { + [CmdletBinding()] param($targetData) $record = $targetData | Select-Object -First 1 diff --git a/ExportedCommands/Import-Excel.ps1 b/ExportedCommands/Import-Excel.ps1 index 94ec48f..5bd4389 100644 --- a/ExportedCommands/Import-Excel.ps1 +++ b/ExportedCommands/Import-Excel.ps1 @@ -47,20 +47,20 @@ else { $Paths = '' } - Function Get-PropertyNames { + function Get-PropertyNames { <# .SYNOPSIS Create objects containing the column number and the column name for each of the different header types. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = "Name would be incorrect, and command is not exported")] - Param ( + param( [Parameter(Mandatory)] [Int[]]$Columns, [Parameter(Mandatory)] [Int]$StartRow ) - Try { + try { if ($HeaderName) { $i = 0 foreach ($H in $HeaderName) { @@ -86,7 +86,7 @@ } } } - Catch { + catch { throw "Failed creating property names: $_" ; return } } diff --git a/ExportedCommands/Import-UPS.ps1 b/ExportedCommands/Import-UPS.ps1 index f1ad15f..16d2636 100644 --- a/ExportedCommands/Import-UPS.ps1 +++ b/ExportedCommands/Import-UPS.ps1 @@ -1,4 +1,5 @@ function Import-UPS { + [CmdletBinding()] param( $TrackingNumber, [Switch]$UseDefaultCredentials diff --git a/ExportedCommands/Import-USPS.ps1 b/ExportedCommands/Import-USPS.ps1 index e45ed38..fcb8ad1 100644 --- a/ExportedCommands/Import-USPS.ps1 +++ b/ExportedCommands/Import-USPS.ps1 @@ -1,5 +1,5 @@ function Import-USPS { - + [CmdletBinding()] param( $TrackingNumber, [Switch]$UseDefaultCredentials diff --git a/ExportedCommands/Invoke-Sum.ps1 b/ExportedCommands/Invoke-Sum.ps1 index 7343098..8f6a3f3 100644 --- a/ExportedCommands/Invoke-Sum.ps1 +++ b/ExportedCommands/Invoke-Sum.ps1 @@ -1,4 +1,5 @@ function Invoke-Sum { + [CmdletBinding()] param( $data, $dimension, diff --git a/ExportedCommands/Merge-MultipleSheets.ps1 b/ExportedCommands/Merge-MultipleSheets.ps1 index 14017dc..996bdf4 100644 --- a/ExportedCommands/Merge-MultipleSheets.ps1 +++ b/ExportedCommands/Merge-MultipleSheets.ps1 @@ -1,5 +1,5 @@ function Merge-MultipleSheets { - [cmdletbinding()] + [CmdletBinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification="False positives when initializing variable in begin block")] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification="MultipleSheet would be incorrect")] #[Alias("Merge-MulipleSheets")] #There was a spelling error in the first release. This was there to ensure things didn't break but intelisense gave the alias first. diff --git a/ExportedCommands/Merge-Worksheet.ps1 b/ExportedCommands/Merge-Worksheet.ps1 index 36c0e88..8a561a1 100644 --- a/ExportedCommands/Merge-Worksheet.ps1 +++ b/ExportedCommands/Merge-Worksheet.ps1 @@ -1,6 +1,6 @@ function Merge-Worksheet { - [cmdletbinding(SupportsShouldProcess=$true)] - Param( + [CmdletBinding(SupportsShouldProcess=$true)] + param( [parameter(ParameterSetName='A',Mandatory=$true,Position=0)] #A = Compare two files default headers [parameter(ParameterSetName='B',Mandatory=$true,Position=0)] #B = Compare two files user supplied headers [parameter(ParameterSetName='C',Mandatory=$true,Position=0)] #C = Compare two files headers P1, P2, P3 etc @@ -76,7 +76,7 @@ if ($Referencefile -and $Differencefile) { #if the filenames don't resolve, give up now. try { $oneFile = ((Resolve-Path -Path $Referencefile -ErrorAction Stop).path -eq (Resolve-Path -Path $Differencefile -ErrorAction Stop).path)} - Catch { Write-Warning -Message "Could not Resolve the filenames." ; return } + catch { Write-Warning -Message "Could not Resolve the filenames." ; return } #If we have one file , we must have two different Worksheet names. If we have two files $WorksheetName can be a single string or two strings. if ($onefile -and ( ($WorksheetName.count -ne 2) -or $WorksheetName[0] -eq $WorksheetName[1] ) ) { @@ -94,7 +94,7 @@ $ReferenceObject = Import-Excel -Path $Referencefile -WorksheetName $Worksheet1 @params $DifferenceObject = Import-Excel -Path $Differencefile -WorksheetName $Worksheet2 @Params } - Catch {Write-Warning -Message "Could not read the Worksheet from $Referencefile::$Worksheet1 and/or $Differencefile::$Worksheet2." ; return } + catch {Write-Warning -Message "Could not read the Worksheet from $Referencefile::$Worksheet1 and/or $Differencefile::$Worksheet2." ; return } if ($NoHeader) {$firstDataRow = $Startrow } else {$firstDataRow = $Startrow + 1} } elseif ( $Differencefile) { @@ -102,7 +102,7 @@ $params = @{WorksheetName=$WorksheetName; Path=$Differencefile; ErrorAction=[System.Management.Automation.ActionPreference]::Stop } foreach ($p in @("HeaderName","NoHeader","StartRow")) {if ($PSBoundParameters[$p]) {$params[$p] = $PSBoundParameters[$p]}} try {$DifferenceObject = Import-Excel @Params } - Catch {Write-Warning -Message "Could not read the Worksheet '$WorksheetName' from $Differencefile::$WorksheetName." ; return } + catch {Write-Warning -Message "Could not read the Worksheet '$WorksheetName' from $Differencefile::$WorksheetName." ; return } if ($DiffPrefix -eq "=>" ) { $DiffPrefix = (Split-Path -Path $Differencefile -Leaf) -replace "\.xlsx$","" } diff --git a/ExportedCommands/New-ConditionalText.ps1 b/ExportedCommands/New-ConditionalText.ps1 index a5b6743..e7e990c 100644 --- a/ExportedCommands/New-ConditionalText.ps1 +++ b/ExportedCommands/New-ConditionalText.ps1 @@ -1,5 +1,5 @@ function New-ConditionalText { - [cmdletbinding()] + [CmdletBinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system State')] param( #[Parameter(Mandatory=$true)] diff --git a/ExportedCommands/New-ExcelChartDefinition.ps1 b/ExportedCommands/New-ExcelChartDefinition.ps1 index e657d84..f024b9b 100644 --- a/ExportedCommands/New-ExcelChartDefinition.ps1 +++ b/ExportedCommands/New-ExcelChartDefinition.ps1 @@ -1,6 +1,6 @@ function New-ExcelChartDefinition { [Alias("New-ExcelChart")] #This was the former name. The new name reflects that we are defining a chart, not making one in the workbook. - [cmdletbinding()] + [CmdletBinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Does not change system State')] param( $Title = "Chart Title", diff --git a/ExportedCommands/New-ExcelStyle.ps1 b/ExportedCommands/New-ExcelStyle.ps1 index a88d122..2bb2cde 100644 --- a/ExportedCommands/New-ExcelStyle.ps1 +++ b/ExportedCommands/New-ExcelStyle.ps1 @@ -1,5 +1,5 @@ function New-ExcelStyle { - [cmdletbinding()] + [CmdletBinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Does not change system State')] param ( [Alias("Address")] diff --git a/ExportedCommands/New-PSItem.ps1 b/ExportedCommands/New-PSItem.ps1 index 4e10276..7dd2653 100644 --- a/ExportedCommands/New-PSItem.ps1 +++ b/ExportedCommands/New-PSItem.ps1 @@ -1,7 +1,7 @@ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Scope='Function', Target='New*', Justification='Does not change system State')] param() function New-PSItem { - + param() $totalArgs = $args.Count if($args[-1] -is [array]) { diff --git a/ExportedCommands/Open-ExcelPackage.ps1 b/ExportedCommands/Open-ExcelPackage.ps1 index 4277ba5..a645e07 100644 --- a/ExportedCommands/Open-ExcelPackage.ps1 +++ b/ExportedCommands/Open-ExcelPackage.ps1 @@ -1,8 +1,8 @@ -Function Open-ExcelPackage { +function Open-ExcelPackage { [CmdLetBinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")] [OutputType([OfficeOpenXml.ExcelPackage])] - Param ( + param( #The path to the file to open. [Parameter(Mandatory=$true)]$Path, #If specified, any running instances of Excel will be terminated before opening the file. diff --git a/ExportedCommands/Remove-Worksheet.ps1 b/ExportedCommands/Remove-Worksheet.ps1 index a2bbb93..e8d0d8f 100644 --- a/ExportedCommands/Remove-Worksheet.ps1 +++ b/ExportedCommands/Remove-Worksheet.ps1 @@ -1,5 +1,5 @@ -Function Remove-Worksheet { - [cmdletbinding(SupportsShouldProcess=$true)] +function Remove-Worksheet { + [CmdletBinding(SupportsShouldProcess=$true)] param( # [Parameter(ValueFromPipelineByPropertyName)] [Parameter(ValueFromPipelineByPropertyName)] diff --git a/ExportedCommands/Send-SQLDataToExcel.ps1 b/ExportedCommands/Send-SQLDataToExcel.ps1 index 0ba3169..bdf6d3c 100644 --- a/ExportedCommands/Send-SQLDataToExcel.ps1 +++ b/ExportedCommands/Send-SQLDataToExcel.ps1 @@ -1,4 +1,4 @@ -Function Send-SQLDataToExcel { +function Send-SQLDataToExcel { [CmdletBinding(DefaultParameterSetName="none")] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '', Justification="Allowed to use DBSessions Global variable from GETSQL Module")] diff --git a/ExportedCommands/Set-CellStyle.ps1 b/ExportedCommands/Set-CellStyle.ps1 index 96ca249..02a48b0 100644 --- a/ExportedCommands/Set-CellStyle.ps1 +++ b/ExportedCommands/Set-CellStyle.ps1 @@ -2,6 +2,7 @@ param() function Set-CellStyle { + [CmdletBinding()] param( $Worksheet, $Row, diff --git a/ExportedCommands/Set-ExcelColumn.ps1 b/ExportedCommands/Set-ExcelColumn.ps1 index 6cc51e5..feb9d4e 100644 --- a/ExportedCommands/Set-ExcelColumn.ps1 +++ b/ExportedCommands/Set-ExcelColumn.ps1 @@ -1,10 +1,10 @@ -Function Set-ExcelColumn { - [cmdletbinding()] +function Set-ExcelColumn { + [CmdletBinding()] [Alias("Set-Column")] [OutputType([OfficeOpenXml.ExcelColumn],[String])] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system state')] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingfunctions', '',Justification='Does not change system state')] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification="Variables created for script block which may be passed as a parameter, but not used in the script")] - Param ( + param( [Parameter(ParameterSetName="Package",Mandatory=$true)] [OfficeOpenXml.ExcelPackage]$ExcelPackage, [Parameter(ParameterSetName="Package")] diff --git a/ExportedCommands/Set-ExcelRange.ps1 b/ExportedCommands/Set-ExcelRange.ps1 index 48d759e..ae80b3e 100644 --- a/ExportedCommands/Set-ExcelRange.ps1 +++ b/ExportedCommands/Set-ExcelRange.ps1 @@ -1,8 +1,8 @@ function Set-ExcelRange { - [cmdletbinding()] + [CmdletBinding()] [Alias("Set-Format")] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system state')] - Param ( + param( [Parameter(ValueFromPipeline = $true,Position=0)] [Alias("Address")] $Range , diff --git a/ExportedCommands/Set-ExcelRow.ps1 b/ExportedCommands/Set-ExcelRow.ps1 index 72aa62e..c2c454b 100644 --- a/ExportedCommands/Set-ExcelRow.ps1 +++ b/ExportedCommands/Set-ExcelRow.ps1 @@ -1,10 +1,10 @@ -Function Set-ExcelRow { - [cmdletbinding()] +function Set-ExcelRow { + [CmdletBinding()] [Alias("Set-Row")] [OutputType([OfficeOpenXml.ExcelRow],[String])] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system state')] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingfunctions', '',Justification='Does not change system state')] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification="Variables created for script block which may be passed as a parameter, but not used in the script")] - Param ( + param( [Parameter(ParameterSetName="Package",Mandatory=$true)] [OfficeOpenXml.ExcelPackage]$ExcelPackage, [Parameter(ParameterSetName="Package")] diff --git a/ExportedCommands/Set-WorksheetProtection.ps1 b/ExportedCommands/Set-WorksheetProtection.ps1 index b7258e3..7cb7db5 100644 --- a/ExportedCommands/Set-WorksheetProtection.ps1 +++ b/ExportedCommands/Set-WorksheetProtection.ps1 @@ -1,6 +1,6 @@ -Function Set-WorksheetProtection { - [Cmdletbinding()] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system state')] +function Set-WorksheetProtection { + [CmdletBinding()] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingfunctions', '',Justification='Does not change system state')] param ( [Parameter(Mandatory=$true)] [OfficeOpenXml.ExcelWorksheet]$Worksheet , diff --git a/ExportedCommands/Update-FirstObjectProperties.ps1 b/ExportedCommands/Update-FirstObjectProperties.ps1 index c859576..d4386d9 100644 --- a/ExportedCommands/Update-FirstObjectProperties.ps1 +++ b/ExportedCommands/Update-FirstObjectProperties.ps1 @@ -3,9 +3,10 @@ param() -Function Update-FirstObjectProperties { - - Try { +function Update-FirstObjectProperties { + [CmdletBinding()] + param() + try { $Union = @() $Input | ForEach-Object { If ($Union.Count) { @@ -17,7 +18,7 @@ Function Update-FirstObjectProperties { } $Union } - Catch { + catch { throw "Failed updating the properties of the first object: $_" } } \ No newline at end of file diff --git a/GetExcelTable.ps1 b/GetExcelTable.ps1 index 4fa2742..109f2d6 100644 --- a/GetExcelTable.ps1 +++ b/GetExcelTable.ps1 @@ -1,5 +1,5 @@ -Function Get-ExcelTableName { - Param ( +function Get-ExcelTableName { + param( $Path, $WorksheetName ) @@ -28,8 +28,8 @@ Function Get-ExcelTableName { $Excel = $null } -Function Get-ExcelTable { - Param ( +function Get-ExcelTable { + param( $Path, $TableName, $WorksheetName diff --git a/ImportExcel.psm1 b/ImportExcel.psm1 index 02dc71c..c121aa0 100644 --- a/ImportExcel.psm1 +++ b/ImportExcel.psm1 @@ -11,9 +11,9 @@ foreach ($directory in @('ExportedCommands','Charting','InferData','Pivot')) { if ($PSVersionTable.PSVersion.Major -ge 5) { . $PSScriptRoot\Plot.ps1 - Function New-Plot { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'New-Plot does not change system state')] - Param() + function New-Plot { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingfunctions', '', Justification = 'New-Plot does not change system state')] + param() [PSPlot]::new() } diff --git a/Install.ps1 b/Install.ps1 index c7589d3..ad4284a 100644 --- a/Install.ps1 +++ b/Install.ps1 @@ -4,7 +4,7 @@ File must not have BOM for GitHub deploy to work. #> [CmdletBinding(DefaultParameterSetName = 'Default')] -Param ( +param( # Path to install the module to, if not provided -Scope used. [Parameter(Mandatory, ParameterSetName = 'ModulePath')] [ValidateNotNullOrEmpty()] @@ -106,7 +106,7 @@ function Invoke-MultiLike { } } -Try { +try { Write-Verbose -Message 'Module installation started' if (!$ModulePath) { @@ -202,7 +202,7 @@ Try { Import-Module -Name $ModuleName -Force Write-Verbose -Message "Module installed" } -Catch { +catch { throw ('Failed installing module "{0}". Error: "{1}" in Line {2}' -f $ModuleName, $_, $_.InvocationInfo.ScriptLineNumber) } finally { From 6508043bc0707f06aa28a0b73d6b616fb6d03141 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sat, 30 Nov 2019 15:28:05 +0000 Subject: [PATCH 17/25] Make Update-1st object props an advanced cmdlet & faster --- .../Update-FirstObjectProperties.ps1 | 34 ++++++++++++------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/ExportedCommands/Update-FirstObjectProperties.ps1 b/ExportedCommands/Update-FirstObjectProperties.ps1 index d4386d9..d24758c 100644 --- a/ExportedCommands/Update-FirstObjectProperties.ps1 +++ b/ExportedCommands/Update-FirstObjectProperties.ps1 @@ -5,20 +5,28 @@ param() function Update-FirstObjectProperties { [CmdletBinding()] - param() - try { - $Union = @() - $Input | ForEach-Object { - If ($Union.Count) { - $_ | Get-Member | Where-Object {-not ($Union[0] | Get-Member $_.Name)} | ForEach-Object { - $Union[0] | Add-Member -MemberType NoteProperty -Name $_.Name -Value $Null - } + param ( + [Parameter(ValueFromPipeline=$true)] + $InputObject + ) + begin { $union = New-Object -TypeName System.Collections.ArrayList } + process { + try { + If ($union.Count -eq 0) { + [void]$union.Add($InputObject) + $memberNames = (Get-Member -InputObject $InputObject -MemberType Properties).Name + } + else { + foreach ($propName in (Get-Member -InputObject $InputObject -MemberType Properties).Name) { + if ($propName -notin $memberNames) { + Add-Member -InputObject $Union[0] -MemberType NoteProperty -Name $propName -Value $Null + $memberNames += $propName + } + } + [void]$Union.Add($InputObject) } - $Union += $_ } - $Union - } - catch { - throw "Failed updating the properties of the first object: $_" + catch {throw "Failed updating the properties of the first object: $_"} } + end { $Union } } \ No newline at end of file From d1c347285f939d31b13c1df4b24daca320da3722 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sat, 30 Nov 2019 15:28:31 +0000 Subject: [PATCH 18/25] Move DLL load into PSD1 --- ImportExcel.psd1 | 6 +++--- ImportExcel.psm1 | 2 -- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/ImportExcel.psd1 b/ImportExcel.psd1 index bda2946..c811a85 100644 --- a/ImportExcel.psd1 +++ b/ImportExcel.psd1 @@ -1,4 +1,7 @@ @{ + # Assemblies that must be loaded prior to importing this module + RequiredAssemblies = @('.\EPPlus.dll') + # Script module or binary module file associated with this manifest. RootModule = 'ImportExcel.psm1' @@ -45,9 +48,6 @@ Check out the How To Videos https://www.youtube.com/watch?v=U3Ne_yX4tYo&list=PL5 # Modules that must be imported into the global environment prior to importing this module # RequiredModules = @() - # Assemblies that must be loaded prior to importing this module - # RequiredAssemblies = @() - # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() diff --git a/ImportExcel.psm1 b/ImportExcel.psm1 index c121aa0..084adee 100644 --- a/ImportExcel.psm1 +++ b/ImportExcel.psm1 @@ -1,6 +1,4 @@ #region import everything we need -Add-Type -Path "$($PSScriptRoot)\EPPlus.dll" - try {[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")} catch {Write-Warning -Message "System.Drawing could not be loaded. Color and font look-ups may not be available."} From 6b033d745196f6cb9b056bb05fad534ecc4b98d3 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sun, 1 Dec 2019 00:15:05 +0000 Subject: [PATCH 19/25] Fix for CI --- ImportExcel.psd1 | 1 - Install.ps1 | 62 ++++++++++++++---------------------------------- 2 files changed, 18 insertions(+), 45 deletions(-) diff --git a/ImportExcel.psd1 b/ImportExcel.psd1 index c811a85..009087f 100644 --- a/ImportExcel.psd1 +++ b/ImportExcel.psd1 @@ -2,7 +2,6 @@ # Assemblies that must be loaded prior to importing this module RequiredAssemblies = @('.\EPPlus.dll') - # Script module or binary module file associated with this manifest. RootModule = 'ImportExcel.psm1' diff --git a/Install.ps1 b/Install.ps1 index ad4284a..a733000 100644 --- a/Install.ps1 +++ b/Install.ps1 @@ -22,53 +22,27 @@ param( ) # Set Files and Folders patterns to Include/Exclude. $IncludeFiles = @( - '*.dll', + 'EPPlus.dll', '*.psd1', '*.psm1', - 'AddConditionalFormatting.ps1', - 'AddDataValidation.ps1', - 'Charting.ps1', - 'ColorCompletion.ps1', - 'Compare-Worksheet.ps1', - 'ConvertExcelToImageFile.ps1', - 'ConvertFromExcelData.ps1', - 'ConvertFromExcelToSQLInsert.ps1', - 'ConvertToExcelXlsx.ps1', - 'Copy-ExcelWorksheet.ps1', - 'Export-Excel.ps1', - 'Export-ExcelSheet.ps1', - 'Export-StocksToExcel.ps1', - 'Get-ExcelColumnName.ps1', - 'Get-ExcelSheetInfo.ps1', - 'Get-ExcelWorkbookInfo.ps1', - 'Get-HtmlTable.ps1', - 'Get-Range.ps1', - 'Get-XYRange.ps1', - 'Import-Html.ps1', - 'InferData.ps1', - 'Invoke-Sum.ps1', - 'Join-Worksheet.ps1', - 'Merge-Worksheet.ps1', - 'New-ConditionalFormattingIconSet.ps1', - 'New-ConditionalText.ps1', - 'New-ExcelChart.ps1', - 'New-PSItem.ps1', - 'Open-ExcelPackage.ps1', - 'Pivot.ps1', - 'PivotTable.ps1', - 'Plot.ps1', - 'RemoveWorksheet.ps1', - 'Send-SQLDataToExcel.ps1', - 'Set-CellStyle.ps1', - 'Set-Column.ps1', - 'Set-Row.ps1', - 'Set-WorksheetProtection.ps1', - 'SetFormat.ps1', - 'TrackingUtils.ps1', - 'Update-FirstObjectProperties.ps1' -) + '*.ps1' + 'Charting', + 'en-US', + 'Examples', + 'ExportedCommands', + 'images', + 'InferData', + 'InternalFunctions', + 'Pivot', + 'spikes', + 'Testimonials', + 'README.md', + 'LICENSE.txt' + ) $ExcludeFiles = @( - 'Install.ps1' + 'Install.ps1', + 'InstallModule.ps1', + 'PublishToGallery.PS1' ) From 88e2a23e1b2dac5d6ecea05058f6f42efc44b2f4 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sun, 1 Dec 2019 17:01:50 +0000 Subject: [PATCH 20/25] directory renames --- ImportExcel.psd1 | 20 ++++++++++++++++++- ImportExcel.psm1 | 19 ++++++++++-------- .../Add-ConditionalFormatting.ps1 | 0 .../Add-ExcelChart.ps1 | 0 .../Add-ExcelDataValidationRule.ps1 | 0 .../Add-ExcelName.ps1 | 0 .../Add-ExcelTable.ps1 | 0 .../Add-PivotTable.ps1 | 0 .../Add-Worksheet.ps1 | 0 .../ArgumentCompletion.ps1 | 0 .../Close-ExcelPackage.ps1 | 0 .../Compare-Worksheet.ps1 | 0 .../Convert-ExcelRangeToImage.ps1 | 0 .../ConvertFrom-ExcelData.md | 0 .../ConvertFrom-ExcelData.ps1 | 0 .../ConvertFrom-ExcelSheet.md | 0 .../ConvertFrom-ExcelSheet.ps1 | 0 .../ConvertFrom-ExcelToSQLInsert.ps1 | 0 .../ConvertTo-ExcelXlsx.md | 0 .../ConvertTo-ExcelXlsx.ps1 | 0 .../Copy-ExcelWorksheet.ps1 | 0 .../Expand-NumberFormat.ps1 | 0 {ExportedCommands => Public}/Export-Excel.ps1 | 0 .../Export-ExcelSheet.md | 0 .../Export-ExcelSheet.ps1 | 0 .../Export-MultipleExcelSheets.md | 0 .../Export-MultipleExcelSheets.ps1 | 0 .../Export-StocksToExcel.ps1 | 0 .../Get-ExcelColumnName.md | 0 .../Get-ExcelColumnName.ps1 | 0 .../Get-ExcelSheetInfo.ps1 | 0 .../Get-ExcelWorkbookInfo.ps1 | 0 {ExportedCommands => Public}/Get-HtmlTable.md | 0 .../Get-HtmlTable.ps1 | 0 {ExportedCommands => Public}/Get-Range.md | 0 {ExportedCommands => Public}/Get-Range.ps1 | 0 {ExportedCommands => Public}/Get-XYRange.md | 0 {ExportedCommands => Public}/Get-XYRange.ps1 | 0 {ExportedCommands => Public}/Import-Excel.ps1 | 0 {ExportedCommands => Public}/Import-Html.md | 0 {ExportedCommands => Public}/Import-Html.ps1 | 0 {ExportedCommands => Public}/Import-UPS.md | 0 {ExportedCommands => Public}/Import-UPS.ps1 | 0 {ExportedCommands => Public}/Import-USPS.md | 0 {ExportedCommands => Public}/Import-USPS.ps1 | 0 Install.ps1 => Public/Install.ps1 | 0 InstallModule.ps1 => Public/InstallModule.ps1 | 0 {ExportedCommands => Public}/Invoke-Sum.md | 0 {ExportedCommands => Public}/Invoke-Sum.ps1 | 0 .../Join-Worksheet.ps1 | 0 .../Merge-MultipleSheets.ps1 | 0 .../Merge-Worksheet.ps1 | 0 .../New-ConditionalFormattingIconSet.ps1 | 0 .../New-ConditionalText.ps1 | 0 .../New-ExcelChartDefinition.ps1 | 0 .../New-ExcelStyle.md | 0 .../New-ExcelStyle.ps1 | 0 {ExportedCommands => Public}/New-PSItem.md | 0 {ExportedCommands => Public}/New-PSItem.ps1 | 0 .../New-PivotTableDefinition.ps1 | 0 New-Plot.md => Public/New-Plot.md | 0 .../Open-ExcelPackage.ps1 | 0 .../PublishToGallery.ps1 | 0 .../Remove-Worksheet.ps1 | 0 .../Select-Worksheet.ps1 | 0 .../Send-SQLDataToExcel.ps1 | 0 {ExportedCommands => Public}/Set-CellStyle.md | 0 .../Set-CellStyle.ps1 | 0 .../Set-ExcelColumn.ps1 | 0 .../Set-ExcelRange.ps1 | 0 {ExportedCommands => Public}/Set-ExcelRow.ps1 | 0 .../Set-WorksheetProtection.md | 0 .../Set-WorksheetProtection.ps1 | 0 .../Update-FirstObjectProperties.ps1 | 0 {en-US => en}/ImportExcel-help.xml | 0 en/Strings.psd1 | 5 +++++ mdHelp/{ => en}/Add-ConditionalFormatting.md | 0 mdHelp/{ => en}/Add-ExcelChart.md | 0 .../{ => en}/Add-ExcelDataValidationRule.md | 0 mdHelp/{ => en}/Add-ExcelName.md | 0 mdHelp/{ => en}/Add-ExcelTable.md | 0 mdHelp/{ => en}/Add-PivotTable.md | 0 mdHelp/{ => en}/Add-WorkSheet.md | 0 mdHelp/{ => en}/Close-ExcelPackage.md | 0 mdHelp/{ => en}/Compare-WorkSheet.md | 0 mdHelp/{ => en}/Convert-ExcelRangeToImage.md | 0 .../{ => en}/ConvertFrom-ExcelToSQLInsert.md | 0 mdHelp/{ => en}/Copy-ExcelWorkSheet.md | 0 mdHelp/{ => en}/Expand-NumberFormat.md | 0 mdHelp/{ => en}/Export-Excel.md | 0 mdHelp/{ => en}/Get-ExcelSheetInfo.md | 0 mdHelp/{ => en}/Get-ExcelWorkbookInfo.md | 0 mdHelp/{ => en}/Import-Excel.md | 0 mdHelp/{ => en}/Join-Worksheet.md | 0 mdHelp/{ => en}/Merge-MultipleSheets.md | 0 mdHelp/{ => en}/Merge-Worksheet.md | 0 .../New-ConditionalFormattingIconSet.md | 0 mdHelp/{ => en}/New-ConditionalText.md | 0 mdHelp/{ => en}/New-ExcelChartDefinition.md | 0 mdHelp/{ => en}/New-PivotTableDefinition.md | 0 mdHelp/{ => en}/Open-ExcelPackage.md | 0 mdHelp/{ => en}/Remove-WorkSheet.md | 0 mdHelp/{ => en}/Select-Worksheet.md | 0 mdHelp/{ => en}/Send-SQLDataToExcel.md | 0 mdHelp/{ => en}/Set-ExcelColumn.md | 0 mdHelp/{ => en}/Set-ExcelRange.md | 0 mdHelp/{ => en}/Set-ExcelRow.md | 0 .../{ => en}/Update-FirstObjectProperties.md | 0 108 files changed, 35 insertions(+), 9 deletions(-) rename {ExportedCommands => Public}/Add-ConditionalFormatting.ps1 (100%) rename {ExportedCommands => Public}/Add-ExcelChart.ps1 (100%) rename {ExportedCommands => Public}/Add-ExcelDataValidationRule.ps1 (100%) rename {ExportedCommands => Public}/Add-ExcelName.ps1 (100%) rename {ExportedCommands => Public}/Add-ExcelTable.ps1 (100%) rename {ExportedCommands => Public}/Add-PivotTable.ps1 (100%) rename {ExportedCommands => Public}/Add-Worksheet.ps1 (100%) rename ArgumentCompletion.ps1 => Public/ArgumentCompletion.ps1 (100%) rename {ExportedCommands => Public}/Close-ExcelPackage.ps1 (100%) rename {ExportedCommands => Public}/Compare-Worksheet.ps1 (100%) rename {ExportedCommands => Public}/Convert-ExcelRangeToImage.ps1 (100%) rename {ExportedCommands => Public}/ConvertFrom-ExcelData.md (100%) rename {ExportedCommands => Public}/ConvertFrom-ExcelData.ps1 (100%) rename {ExportedCommands => Public}/ConvertFrom-ExcelSheet.md (100%) rename {ExportedCommands => Public}/ConvertFrom-ExcelSheet.ps1 (100%) rename {ExportedCommands => Public}/ConvertFrom-ExcelToSQLInsert.ps1 (100%) rename {ExportedCommands => Public}/ConvertTo-ExcelXlsx.md (100%) rename {ExportedCommands => Public}/ConvertTo-ExcelXlsx.ps1 (100%) rename {ExportedCommands => Public}/Copy-ExcelWorksheet.ps1 (100%) rename {ExportedCommands => Public}/Expand-NumberFormat.ps1 (100%) rename {ExportedCommands => Public}/Export-Excel.ps1 (100%) rename {ExportedCommands => Public}/Export-ExcelSheet.md (100%) rename {ExportedCommands => Public}/Export-ExcelSheet.ps1 (100%) rename {ExportedCommands => Public}/Export-MultipleExcelSheets.md (100%) rename {ExportedCommands => Public}/Export-MultipleExcelSheets.ps1 (100%) rename {ExportedCommands => Public}/Export-StocksToExcel.ps1 (100%) rename {ExportedCommands => Public}/Get-ExcelColumnName.md (100%) rename {ExportedCommands => Public}/Get-ExcelColumnName.ps1 (100%) rename {ExportedCommands => Public}/Get-ExcelSheetInfo.ps1 (100%) rename {ExportedCommands => Public}/Get-ExcelWorkbookInfo.ps1 (100%) rename {ExportedCommands => Public}/Get-HtmlTable.md (100%) rename {ExportedCommands => Public}/Get-HtmlTable.ps1 (100%) rename {ExportedCommands => Public}/Get-Range.md (100%) rename {ExportedCommands => Public}/Get-Range.ps1 (100%) rename {ExportedCommands => Public}/Get-XYRange.md (100%) rename {ExportedCommands => Public}/Get-XYRange.ps1 (100%) rename {ExportedCommands => Public}/Import-Excel.ps1 (100%) rename {ExportedCommands => Public}/Import-Html.md (100%) rename {ExportedCommands => Public}/Import-Html.ps1 (100%) rename {ExportedCommands => Public}/Import-UPS.md (100%) rename {ExportedCommands => Public}/Import-UPS.ps1 (100%) rename {ExportedCommands => Public}/Import-USPS.md (100%) rename {ExportedCommands => Public}/Import-USPS.ps1 (100%) rename Install.ps1 => Public/Install.ps1 (100%) rename InstallModule.ps1 => Public/InstallModule.ps1 (100%) rename {ExportedCommands => Public}/Invoke-Sum.md (100%) rename {ExportedCommands => Public}/Invoke-Sum.ps1 (100%) rename {ExportedCommands => Public}/Join-Worksheet.ps1 (100%) rename {ExportedCommands => Public}/Merge-MultipleSheets.ps1 (100%) rename {ExportedCommands => Public}/Merge-Worksheet.ps1 (100%) rename {ExportedCommands => Public}/New-ConditionalFormattingIconSet.ps1 (100%) rename {ExportedCommands => Public}/New-ConditionalText.ps1 (100%) rename {ExportedCommands => Public}/New-ExcelChartDefinition.ps1 (100%) rename {ExportedCommands => Public}/New-ExcelStyle.md (100%) rename {ExportedCommands => Public}/New-ExcelStyle.ps1 (100%) rename {ExportedCommands => Public}/New-PSItem.md (100%) rename {ExportedCommands => Public}/New-PSItem.ps1 (100%) rename {ExportedCommands => Public}/New-PivotTableDefinition.ps1 (100%) rename New-Plot.md => Public/New-Plot.md (100%) rename {ExportedCommands => Public}/Open-ExcelPackage.ps1 (100%) rename PublishToGallery.ps1 => Public/PublishToGallery.ps1 (100%) rename {ExportedCommands => Public}/Remove-Worksheet.ps1 (100%) rename {ExportedCommands => Public}/Select-Worksheet.ps1 (100%) rename {ExportedCommands => Public}/Send-SQLDataToExcel.ps1 (100%) rename {ExportedCommands => Public}/Set-CellStyle.md (100%) rename {ExportedCommands => Public}/Set-CellStyle.ps1 (100%) rename {ExportedCommands => Public}/Set-ExcelColumn.ps1 (100%) rename {ExportedCommands => Public}/Set-ExcelRange.ps1 (100%) rename {ExportedCommands => Public}/Set-ExcelRow.ps1 (100%) rename {ExportedCommands => Public}/Set-WorksheetProtection.md (100%) rename {ExportedCommands => Public}/Set-WorksheetProtection.ps1 (100%) rename {ExportedCommands => Public}/Update-FirstObjectProperties.ps1 (100%) rename {en-US => en}/ImportExcel-help.xml (100%) create mode 100644 en/Strings.psd1 rename mdHelp/{ => en}/Add-ConditionalFormatting.md (100%) rename mdHelp/{ => en}/Add-ExcelChart.md (100%) rename mdHelp/{ => en}/Add-ExcelDataValidationRule.md (100%) rename mdHelp/{ => en}/Add-ExcelName.md (100%) rename mdHelp/{ => en}/Add-ExcelTable.md (100%) rename mdHelp/{ => en}/Add-PivotTable.md (100%) rename mdHelp/{ => en}/Add-WorkSheet.md (100%) rename mdHelp/{ => en}/Close-ExcelPackage.md (100%) rename mdHelp/{ => en}/Compare-WorkSheet.md (100%) rename mdHelp/{ => en}/Convert-ExcelRangeToImage.md (100%) rename mdHelp/{ => en}/ConvertFrom-ExcelToSQLInsert.md (100%) rename mdHelp/{ => en}/Copy-ExcelWorkSheet.md (100%) rename mdHelp/{ => en}/Expand-NumberFormat.md (100%) rename mdHelp/{ => en}/Export-Excel.md (100%) rename mdHelp/{ => en}/Get-ExcelSheetInfo.md (100%) rename mdHelp/{ => en}/Get-ExcelWorkbookInfo.md (100%) rename mdHelp/{ => en}/Import-Excel.md (100%) rename mdHelp/{ => en}/Join-Worksheet.md (100%) rename mdHelp/{ => en}/Merge-MultipleSheets.md (100%) rename mdHelp/{ => en}/Merge-Worksheet.md (100%) rename mdHelp/{ => en}/New-ConditionalFormattingIconSet.md (100%) rename mdHelp/{ => en}/New-ConditionalText.md (100%) rename mdHelp/{ => en}/New-ExcelChartDefinition.md (100%) rename mdHelp/{ => en}/New-PivotTableDefinition.md (100%) rename mdHelp/{ => en}/Open-ExcelPackage.md (100%) rename mdHelp/{ => en}/Remove-WorkSheet.md (100%) rename mdHelp/{ => en}/Select-Worksheet.md (100%) rename mdHelp/{ => en}/Send-SQLDataToExcel.md (100%) rename mdHelp/{ => en}/Set-ExcelColumn.md (100%) rename mdHelp/{ => en}/Set-ExcelRange.md (100%) rename mdHelp/{ => en}/Set-ExcelRow.md (100%) rename mdHelp/{ => en}/Update-FirstObjectProperties.md (100%) diff --git a/ImportExcel.psd1 b/ImportExcel.psd1 index 009087f..6914d70 100644 --- a/ImportExcel.psd1 +++ b/ImportExcel.psd1 @@ -145,7 +145,25 @@ Check out the How To Videos https://www.youtube.com/watch?v=U3Ne_yX4tYo&list=PL5 # ModuleList = @() # List of all files packaged with this module - # FileList = @() + FileList = @( + '.\EPPlus.dll', + '.\Export-charts.ps1', + '.\GetExcelTable.ps1', + '.\ImportExcel.psd1', + '.\ImportExcel.psm1', + '.\LICENSE.txt', + '.\README.md', + '.\en\ImportExcel-help.xml', + '.\en\Strings.psd1', + '.\Charting\Charting.ps1', + '.\InferData\InferData.ps1', + '.\Pivot\Pivot.ps1', + '.\spikes\ConvertFrom-ExcelColumnName.ps1', + '.\Testimonials\t1.png', + '.\images\*.gif', + '.\images\*.png', + '.\Examples\*.*' + ) # Private data to pass to the module specified in RootModule/ModuleToProcess PrivateData = @{ diff --git a/ImportExcel.psm1 b/ImportExcel.psm1 index 084adee..d472f10 100644 --- a/ImportExcel.psm1 +++ b/ImportExcel.psm1 @@ -1,11 +1,18 @@ #region import everything we need +$culture= $host.CurrentCulture.Name -replace '-\w*$','' +Import-LocalizedData -UICulture $culture -BindingVariable Strings -FileName Strings -ErrorAction Ignore +if (-not $Strings) { + Import-LocalizedData -UICulture "en" -BindingVariable Strings -FileName Strings -ErrorAction Ignore +} try {[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")} -catch {Write-Warning -Message "System.Drawing could not be loaded. Color and font look-ups may not be available."} +catch {Write-Warning -Message $Strings.SystemDrawingAvaialable} -foreach ($directory in @('ExportedCommands','Charting','InferData','Pivot')) { +foreach ($directory in @('Public','Private', 'Charting','InferData','Pivot')) { Get-ChildItem -Path "$PSScriptRoot\$directory\*.ps1" | ForEach-Object {. $_.FullName} } +. $PSScriptRoot\ArgumentCompletion.ps1 + if ($PSVersionTable.PSVersion.Major -ge 5) { . $PSScriptRoot\Plot.ps1 @@ -18,16 +25,12 @@ if ($PSVersionTable.PSVersion.Major -ge 5) { } else { - Write-Warning 'PowerShell 5 is required for plot.ps1' - Write-Warning 'PowerShell Excel is ready, except for that functionality' + Write-Warning $Strings.PS5NeededForPlot + Write-Warning $Strings.ModuleReadyExceptPlot } - -. $PSScriptRoot\ArgumentCompletion.ps1 - #endregion - if (($IsLinux -or $IsMacOS) -or $env:NoAutoSize) { $ExcelPackage = [OfficeOpenXml.ExcelPackage]::new() $Cells = ($ExcelPackage | Add-Worksheet).Cells['A1'] diff --git a/ExportedCommands/Add-ConditionalFormatting.ps1 b/Public/Add-ConditionalFormatting.ps1 similarity index 100% rename from ExportedCommands/Add-ConditionalFormatting.ps1 rename to Public/Add-ConditionalFormatting.ps1 diff --git a/ExportedCommands/Add-ExcelChart.ps1 b/Public/Add-ExcelChart.ps1 similarity index 100% rename from ExportedCommands/Add-ExcelChart.ps1 rename to Public/Add-ExcelChart.ps1 diff --git a/ExportedCommands/Add-ExcelDataValidationRule.ps1 b/Public/Add-ExcelDataValidationRule.ps1 similarity index 100% rename from ExportedCommands/Add-ExcelDataValidationRule.ps1 rename to Public/Add-ExcelDataValidationRule.ps1 diff --git a/ExportedCommands/Add-ExcelName.ps1 b/Public/Add-ExcelName.ps1 similarity index 100% rename from ExportedCommands/Add-ExcelName.ps1 rename to Public/Add-ExcelName.ps1 diff --git a/ExportedCommands/Add-ExcelTable.ps1 b/Public/Add-ExcelTable.ps1 similarity index 100% rename from ExportedCommands/Add-ExcelTable.ps1 rename to Public/Add-ExcelTable.ps1 diff --git a/ExportedCommands/Add-PivotTable.ps1 b/Public/Add-PivotTable.ps1 similarity index 100% rename from ExportedCommands/Add-PivotTable.ps1 rename to Public/Add-PivotTable.ps1 diff --git a/ExportedCommands/Add-Worksheet.ps1 b/Public/Add-Worksheet.ps1 similarity index 100% rename from ExportedCommands/Add-Worksheet.ps1 rename to Public/Add-Worksheet.ps1 diff --git a/ArgumentCompletion.ps1 b/Public/ArgumentCompletion.ps1 similarity index 100% rename from ArgumentCompletion.ps1 rename to Public/ArgumentCompletion.ps1 diff --git a/ExportedCommands/Close-ExcelPackage.ps1 b/Public/Close-ExcelPackage.ps1 similarity index 100% rename from ExportedCommands/Close-ExcelPackage.ps1 rename to Public/Close-ExcelPackage.ps1 diff --git a/ExportedCommands/Compare-Worksheet.ps1 b/Public/Compare-Worksheet.ps1 similarity index 100% rename from ExportedCommands/Compare-Worksheet.ps1 rename to Public/Compare-Worksheet.ps1 diff --git a/ExportedCommands/Convert-ExcelRangeToImage.ps1 b/Public/Convert-ExcelRangeToImage.ps1 similarity index 100% rename from ExportedCommands/Convert-ExcelRangeToImage.ps1 rename to Public/Convert-ExcelRangeToImage.ps1 diff --git a/ExportedCommands/ConvertFrom-ExcelData.md b/Public/ConvertFrom-ExcelData.md similarity index 100% rename from ExportedCommands/ConvertFrom-ExcelData.md rename to Public/ConvertFrom-ExcelData.md diff --git a/ExportedCommands/ConvertFrom-ExcelData.ps1 b/Public/ConvertFrom-ExcelData.ps1 similarity index 100% rename from ExportedCommands/ConvertFrom-ExcelData.ps1 rename to Public/ConvertFrom-ExcelData.ps1 diff --git a/ExportedCommands/ConvertFrom-ExcelSheet.md b/Public/ConvertFrom-ExcelSheet.md similarity index 100% rename from ExportedCommands/ConvertFrom-ExcelSheet.md rename to Public/ConvertFrom-ExcelSheet.md diff --git a/ExportedCommands/ConvertFrom-ExcelSheet.ps1 b/Public/ConvertFrom-ExcelSheet.ps1 similarity index 100% rename from ExportedCommands/ConvertFrom-ExcelSheet.ps1 rename to Public/ConvertFrom-ExcelSheet.ps1 diff --git a/ExportedCommands/ConvertFrom-ExcelToSQLInsert.ps1 b/Public/ConvertFrom-ExcelToSQLInsert.ps1 similarity index 100% rename from ExportedCommands/ConvertFrom-ExcelToSQLInsert.ps1 rename to Public/ConvertFrom-ExcelToSQLInsert.ps1 diff --git a/ExportedCommands/ConvertTo-ExcelXlsx.md b/Public/ConvertTo-ExcelXlsx.md similarity index 100% rename from ExportedCommands/ConvertTo-ExcelXlsx.md rename to Public/ConvertTo-ExcelXlsx.md diff --git a/ExportedCommands/ConvertTo-ExcelXlsx.ps1 b/Public/ConvertTo-ExcelXlsx.ps1 similarity index 100% rename from ExportedCommands/ConvertTo-ExcelXlsx.ps1 rename to Public/ConvertTo-ExcelXlsx.ps1 diff --git a/ExportedCommands/Copy-ExcelWorksheet.ps1 b/Public/Copy-ExcelWorksheet.ps1 similarity index 100% rename from ExportedCommands/Copy-ExcelWorksheet.ps1 rename to Public/Copy-ExcelWorksheet.ps1 diff --git a/ExportedCommands/Expand-NumberFormat.ps1 b/Public/Expand-NumberFormat.ps1 similarity index 100% rename from ExportedCommands/Expand-NumberFormat.ps1 rename to Public/Expand-NumberFormat.ps1 diff --git a/ExportedCommands/Export-Excel.ps1 b/Public/Export-Excel.ps1 similarity index 100% rename from ExportedCommands/Export-Excel.ps1 rename to Public/Export-Excel.ps1 diff --git a/ExportedCommands/Export-ExcelSheet.md b/Public/Export-ExcelSheet.md similarity index 100% rename from ExportedCommands/Export-ExcelSheet.md rename to Public/Export-ExcelSheet.md diff --git a/ExportedCommands/Export-ExcelSheet.ps1 b/Public/Export-ExcelSheet.ps1 similarity index 100% rename from ExportedCommands/Export-ExcelSheet.ps1 rename to Public/Export-ExcelSheet.ps1 diff --git a/ExportedCommands/Export-MultipleExcelSheets.md b/Public/Export-MultipleExcelSheets.md similarity index 100% rename from ExportedCommands/Export-MultipleExcelSheets.md rename to Public/Export-MultipleExcelSheets.md diff --git a/ExportedCommands/Export-MultipleExcelSheets.ps1 b/Public/Export-MultipleExcelSheets.ps1 similarity index 100% rename from ExportedCommands/Export-MultipleExcelSheets.ps1 rename to Public/Export-MultipleExcelSheets.ps1 diff --git a/ExportedCommands/Export-StocksToExcel.ps1 b/Public/Export-StocksToExcel.ps1 similarity index 100% rename from ExportedCommands/Export-StocksToExcel.ps1 rename to Public/Export-StocksToExcel.ps1 diff --git a/ExportedCommands/Get-ExcelColumnName.md b/Public/Get-ExcelColumnName.md similarity index 100% rename from ExportedCommands/Get-ExcelColumnName.md rename to Public/Get-ExcelColumnName.md diff --git a/ExportedCommands/Get-ExcelColumnName.ps1 b/Public/Get-ExcelColumnName.ps1 similarity index 100% rename from ExportedCommands/Get-ExcelColumnName.ps1 rename to Public/Get-ExcelColumnName.ps1 diff --git a/ExportedCommands/Get-ExcelSheetInfo.ps1 b/Public/Get-ExcelSheetInfo.ps1 similarity index 100% rename from ExportedCommands/Get-ExcelSheetInfo.ps1 rename to Public/Get-ExcelSheetInfo.ps1 diff --git a/ExportedCommands/Get-ExcelWorkbookInfo.ps1 b/Public/Get-ExcelWorkbookInfo.ps1 similarity index 100% rename from ExportedCommands/Get-ExcelWorkbookInfo.ps1 rename to Public/Get-ExcelWorkbookInfo.ps1 diff --git a/ExportedCommands/Get-HtmlTable.md b/Public/Get-HtmlTable.md similarity index 100% rename from ExportedCommands/Get-HtmlTable.md rename to Public/Get-HtmlTable.md diff --git a/ExportedCommands/Get-HtmlTable.ps1 b/Public/Get-HtmlTable.ps1 similarity index 100% rename from ExportedCommands/Get-HtmlTable.ps1 rename to Public/Get-HtmlTable.ps1 diff --git a/ExportedCommands/Get-Range.md b/Public/Get-Range.md similarity index 100% rename from ExportedCommands/Get-Range.md rename to Public/Get-Range.md diff --git a/ExportedCommands/Get-Range.ps1 b/Public/Get-Range.ps1 similarity index 100% rename from ExportedCommands/Get-Range.ps1 rename to Public/Get-Range.ps1 diff --git a/ExportedCommands/Get-XYRange.md b/Public/Get-XYRange.md similarity index 100% rename from ExportedCommands/Get-XYRange.md rename to Public/Get-XYRange.md diff --git a/ExportedCommands/Get-XYRange.ps1 b/Public/Get-XYRange.ps1 similarity index 100% rename from ExportedCommands/Get-XYRange.ps1 rename to Public/Get-XYRange.ps1 diff --git a/ExportedCommands/Import-Excel.ps1 b/Public/Import-Excel.ps1 similarity index 100% rename from ExportedCommands/Import-Excel.ps1 rename to Public/Import-Excel.ps1 diff --git a/ExportedCommands/Import-Html.md b/Public/Import-Html.md similarity index 100% rename from ExportedCommands/Import-Html.md rename to Public/Import-Html.md diff --git a/ExportedCommands/Import-Html.ps1 b/Public/Import-Html.ps1 similarity index 100% rename from ExportedCommands/Import-Html.ps1 rename to Public/Import-Html.ps1 diff --git a/ExportedCommands/Import-UPS.md b/Public/Import-UPS.md similarity index 100% rename from ExportedCommands/Import-UPS.md rename to Public/Import-UPS.md diff --git a/ExportedCommands/Import-UPS.ps1 b/Public/Import-UPS.ps1 similarity index 100% rename from ExportedCommands/Import-UPS.ps1 rename to Public/Import-UPS.ps1 diff --git a/ExportedCommands/Import-USPS.md b/Public/Import-USPS.md similarity index 100% rename from ExportedCommands/Import-USPS.md rename to Public/Import-USPS.md diff --git a/ExportedCommands/Import-USPS.ps1 b/Public/Import-USPS.ps1 similarity index 100% rename from ExportedCommands/Import-USPS.ps1 rename to Public/Import-USPS.ps1 diff --git a/Install.ps1 b/Public/Install.ps1 similarity index 100% rename from Install.ps1 rename to Public/Install.ps1 diff --git a/InstallModule.ps1 b/Public/InstallModule.ps1 similarity index 100% rename from InstallModule.ps1 rename to Public/InstallModule.ps1 diff --git a/ExportedCommands/Invoke-Sum.md b/Public/Invoke-Sum.md similarity index 100% rename from ExportedCommands/Invoke-Sum.md rename to Public/Invoke-Sum.md diff --git a/ExportedCommands/Invoke-Sum.ps1 b/Public/Invoke-Sum.ps1 similarity index 100% rename from ExportedCommands/Invoke-Sum.ps1 rename to Public/Invoke-Sum.ps1 diff --git a/ExportedCommands/Join-Worksheet.ps1 b/Public/Join-Worksheet.ps1 similarity index 100% rename from ExportedCommands/Join-Worksheet.ps1 rename to Public/Join-Worksheet.ps1 diff --git a/ExportedCommands/Merge-MultipleSheets.ps1 b/Public/Merge-MultipleSheets.ps1 similarity index 100% rename from ExportedCommands/Merge-MultipleSheets.ps1 rename to Public/Merge-MultipleSheets.ps1 diff --git a/ExportedCommands/Merge-Worksheet.ps1 b/Public/Merge-Worksheet.ps1 similarity index 100% rename from ExportedCommands/Merge-Worksheet.ps1 rename to Public/Merge-Worksheet.ps1 diff --git a/ExportedCommands/New-ConditionalFormattingIconSet.ps1 b/Public/New-ConditionalFormattingIconSet.ps1 similarity index 100% rename from ExportedCommands/New-ConditionalFormattingIconSet.ps1 rename to Public/New-ConditionalFormattingIconSet.ps1 diff --git a/ExportedCommands/New-ConditionalText.ps1 b/Public/New-ConditionalText.ps1 similarity index 100% rename from ExportedCommands/New-ConditionalText.ps1 rename to Public/New-ConditionalText.ps1 diff --git a/ExportedCommands/New-ExcelChartDefinition.ps1 b/Public/New-ExcelChartDefinition.ps1 similarity index 100% rename from ExportedCommands/New-ExcelChartDefinition.ps1 rename to Public/New-ExcelChartDefinition.ps1 diff --git a/ExportedCommands/New-ExcelStyle.md b/Public/New-ExcelStyle.md similarity index 100% rename from ExportedCommands/New-ExcelStyle.md rename to Public/New-ExcelStyle.md diff --git a/ExportedCommands/New-ExcelStyle.ps1 b/Public/New-ExcelStyle.ps1 similarity index 100% rename from ExportedCommands/New-ExcelStyle.ps1 rename to Public/New-ExcelStyle.ps1 diff --git a/ExportedCommands/New-PSItem.md b/Public/New-PSItem.md similarity index 100% rename from ExportedCommands/New-PSItem.md rename to Public/New-PSItem.md diff --git a/ExportedCommands/New-PSItem.ps1 b/Public/New-PSItem.ps1 similarity index 100% rename from ExportedCommands/New-PSItem.ps1 rename to Public/New-PSItem.ps1 diff --git a/ExportedCommands/New-PivotTableDefinition.ps1 b/Public/New-PivotTableDefinition.ps1 similarity index 100% rename from ExportedCommands/New-PivotTableDefinition.ps1 rename to Public/New-PivotTableDefinition.ps1 diff --git a/New-Plot.md b/Public/New-Plot.md similarity index 100% rename from New-Plot.md rename to Public/New-Plot.md diff --git a/ExportedCommands/Open-ExcelPackage.ps1 b/Public/Open-ExcelPackage.ps1 similarity index 100% rename from ExportedCommands/Open-ExcelPackage.ps1 rename to Public/Open-ExcelPackage.ps1 diff --git a/PublishToGallery.ps1 b/Public/PublishToGallery.ps1 similarity index 100% rename from PublishToGallery.ps1 rename to Public/PublishToGallery.ps1 diff --git a/ExportedCommands/Remove-Worksheet.ps1 b/Public/Remove-Worksheet.ps1 similarity index 100% rename from ExportedCommands/Remove-Worksheet.ps1 rename to Public/Remove-Worksheet.ps1 diff --git a/ExportedCommands/Select-Worksheet.ps1 b/Public/Select-Worksheet.ps1 similarity index 100% rename from ExportedCommands/Select-Worksheet.ps1 rename to Public/Select-Worksheet.ps1 diff --git a/ExportedCommands/Send-SQLDataToExcel.ps1 b/Public/Send-SQLDataToExcel.ps1 similarity index 100% rename from ExportedCommands/Send-SQLDataToExcel.ps1 rename to Public/Send-SQLDataToExcel.ps1 diff --git a/ExportedCommands/Set-CellStyle.md b/Public/Set-CellStyle.md similarity index 100% rename from ExportedCommands/Set-CellStyle.md rename to Public/Set-CellStyle.md diff --git a/ExportedCommands/Set-CellStyle.ps1 b/Public/Set-CellStyle.ps1 similarity index 100% rename from ExportedCommands/Set-CellStyle.ps1 rename to Public/Set-CellStyle.ps1 diff --git a/ExportedCommands/Set-ExcelColumn.ps1 b/Public/Set-ExcelColumn.ps1 similarity index 100% rename from ExportedCommands/Set-ExcelColumn.ps1 rename to Public/Set-ExcelColumn.ps1 diff --git a/ExportedCommands/Set-ExcelRange.ps1 b/Public/Set-ExcelRange.ps1 similarity index 100% rename from ExportedCommands/Set-ExcelRange.ps1 rename to Public/Set-ExcelRange.ps1 diff --git a/ExportedCommands/Set-ExcelRow.ps1 b/Public/Set-ExcelRow.ps1 similarity index 100% rename from ExportedCommands/Set-ExcelRow.ps1 rename to Public/Set-ExcelRow.ps1 diff --git a/ExportedCommands/Set-WorksheetProtection.md b/Public/Set-WorksheetProtection.md similarity index 100% rename from ExportedCommands/Set-WorksheetProtection.md rename to Public/Set-WorksheetProtection.md diff --git a/ExportedCommands/Set-WorksheetProtection.ps1 b/Public/Set-WorksheetProtection.ps1 similarity index 100% rename from ExportedCommands/Set-WorksheetProtection.ps1 rename to Public/Set-WorksheetProtection.ps1 diff --git a/ExportedCommands/Update-FirstObjectProperties.ps1 b/Public/Update-FirstObjectProperties.ps1 similarity index 100% rename from ExportedCommands/Update-FirstObjectProperties.ps1 rename to Public/Update-FirstObjectProperties.ps1 diff --git a/en-US/ImportExcel-help.xml b/en/ImportExcel-help.xml similarity index 100% rename from en-US/ImportExcel-help.xml rename to en/ImportExcel-help.xml diff --git a/en/Strings.psd1 b/en/Strings.psd1 new file mode 100644 index 0000000..ad64b6e --- /dev/null +++ b/en/Strings.psd1 @@ -0,0 +1,5 @@ +ConvertFrom-StringData @' +SystemDrawingAvaialable=System.Drawing could not be loaded. Color and font look-ups may not be available. +PS5NeededForPlot=PowerShell 5 is required for plot.ps1 +ModuleReadyExceptPlot=The ImportExcel moudle is ready, except for that functionality +'@ \ No newline at end of file diff --git a/mdHelp/Add-ConditionalFormatting.md b/mdHelp/en/Add-ConditionalFormatting.md similarity index 100% rename from mdHelp/Add-ConditionalFormatting.md rename to mdHelp/en/Add-ConditionalFormatting.md diff --git a/mdHelp/Add-ExcelChart.md b/mdHelp/en/Add-ExcelChart.md similarity index 100% rename from mdHelp/Add-ExcelChart.md rename to mdHelp/en/Add-ExcelChart.md diff --git a/mdHelp/Add-ExcelDataValidationRule.md b/mdHelp/en/Add-ExcelDataValidationRule.md similarity index 100% rename from mdHelp/Add-ExcelDataValidationRule.md rename to mdHelp/en/Add-ExcelDataValidationRule.md diff --git a/mdHelp/Add-ExcelName.md b/mdHelp/en/Add-ExcelName.md similarity index 100% rename from mdHelp/Add-ExcelName.md rename to mdHelp/en/Add-ExcelName.md diff --git a/mdHelp/Add-ExcelTable.md b/mdHelp/en/Add-ExcelTable.md similarity index 100% rename from mdHelp/Add-ExcelTable.md rename to mdHelp/en/Add-ExcelTable.md diff --git a/mdHelp/Add-PivotTable.md b/mdHelp/en/Add-PivotTable.md similarity index 100% rename from mdHelp/Add-PivotTable.md rename to mdHelp/en/Add-PivotTable.md diff --git a/mdHelp/Add-WorkSheet.md b/mdHelp/en/Add-WorkSheet.md similarity index 100% rename from mdHelp/Add-WorkSheet.md rename to mdHelp/en/Add-WorkSheet.md diff --git a/mdHelp/Close-ExcelPackage.md b/mdHelp/en/Close-ExcelPackage.md similarity index 100% rename from mdHelp/Close-ExcelPackage.md rename to mdHelp/en/Close-ExcelPackage.md diff --git a/mdHelp/Compare-WorkSheet.md b/mdHelp/en/Compare-WorkSheet.md similarity index 100% rename from mdHelp/Compare-WorkSheet.md rename to mdHelp/en/Compare-WorkSheet.md diff --git a/mdHelp/Convert-ExcelRangeToImage.md b/mdHelp/en/Convert-ExcelRangeToImage.md similarity index 100% rename from mdHelp/Convert-ExcelRangeToImage.md rename to mdHelp/en/Convert-ExcelRangeToImage.md diff --git a/mdHelp/ConvertFrom-ExcelToSQLInsert.md b/mdHelp/en/ConvertFrom-ExcelToSQLInsert.md similarity index 100% rename from mdHelp/ConvertFrom-ExcelToSQLInsert.md rename to mdHelp/en/ConvertFrom-ExcelToSQLInsert.md diff --git a/mdHelp/Copy-ExcelWorkSheet.md b/mdHelp/en/Copy-ExcelWorkSheet.md similarity index 100% rename from mdHelp/Copy-ExcelWorkSheet.md rename to mdHelp/en/Copy-ExcelWorkSheet.md diff --git a/mdHelp/Expand-NumberFormat.md b/mdHelp/en/Expand-NumberFormat.md similarity index 100% rename from mdHelp/Expand-NumberFormat.md rename to mdHelp/en/Expand-NumberFormat.md diff --git a/mdHelp/Export-Excel.md b/mdHelp/en/Export-Excel.md similarity index 100% rename from mdHelp/Export-Excel.md rename to mdHelp/en/Export-Excel.md diff --git a/mdHelp/Get-ExcelSheetInfo.md b/mdHelp/en/Get-ExcelSheetInfo.md similarity index 100% rename from mdHelp/Get-ExcelSheetInfo.md rename to mdHelp/en/Get-ExcelSheetInfo.md diff --git a/mdHelp/Get-ExcelWorkbookInfo.md b/mdHelp/en/Get-ExcelWorkbookInfo.md similarity index 100% rename from mdHelp/Get-ExcelWorkbookInfo.md rename to mdHelp/en/Get-ExcelWorkbookInfo.md diff --git a/mdHelp/Import-Excel.md b/mdHelp/en/Import-Excel.md similarity index 100% rename from mdHelp/Import-Excel.md rename to mdHelp/en/Import-Excel.md diff --git a/mdHelp/Join-Worksheet.md b/mdHelp/en/Join-Worksheet.md similarity index 100% rename from mdHelp/Join-Worksheet.md rename to mdHelp/en/Join-Worksheet.md diff --git a/mdHelp/Merge-MultipleSheets.md b/mdHelp/en/Merge-MultipleSheets.md similarity index 100% rename from mdHelp/Merge-MultipleSheets.md rename to mdHelp/en/Merge-MultipleSheets.md diff --git a/mdHelp/Merge-Worksheet.md b/mdHelp/en/Merge-Worksheet.md similarity index 100% rename from mdHelp/Merge-Worksheet.md rename to mdHelp/en/Merge-Worksheet.md diff --git a/mdHelp/New-ConditionalFormattingIconSet.md b/mdHelp/en/New-ConditionalFormattingIconSet.md similarity index 100% rename from mdHelp/New-ConditionalFormattingIconSet.md rename to mdHelp/en/New-ConditionalFormattingIconSet.md diff --git a/mdHelp/New-ConditionalText.md b/mdHelp/en/New-ConditionalText.md similarity index 100% rename from mdHelp/New-ConditionalText.md rename to mdHelp/en/New-ConditionalText.md diff --git a/mdHelp/New-ExcelChartDefinition.md b/mdHelp/en/New-ExcelChartDefinition.md similarity index 100% rename from mdHelp/New-ExcelChartDefinition.md rename to mdHelp/en/New-ExcelChartDefinition.md diff --git a/mdHelp/New-PivotTableDefinition.md b/mdHelp/en/New-PivotTableDefinition.md similarity index 100% rename from mdHelp/New-PivotTableDefinition.md rename to mdHelp/en/New-PivotTableDefinition.md diff --git a/mdHelp/Open-ExcelPackage.md b/mdHelp/en/Open-ExcelPackage.md similarity index 100% rename from mdHelp/Open-ExcelPackage.md rename to mdHelp/en/Open-ExcelPackage.md diff --git a/mdHelp/Remove-WorkSheet.md b/mdHelp/en/Remove-WorkSheet.md similarity index 100% rename from mdHelp/Remove-WorkSheet.md rename to mdHelp/en/Remove-WorkSheet.md diff --git a/mdHelp/Select-Worksheet.md b/mdHelp/en/Select-Worksheet.md similarity index 100% rename from mdHelp/Select-Worksheet.md rename to mdHelp/en/Select-Worksheet.md diff --git a/mdHelp/Send-SQLDataToExcel.md b/mdHelp/en/Send-SQLDataToExcel.md similarity index 100% rename from mdHelp/Send-SQLDataToExcel.md rename to mdHelp/en/Send-SQLDataToExcel.md diff --git a/mdHelp/Set-ExcelColumn.md b/mdHelp/en/Set-ExcelColumn.md similarity index 100% rename from mdHelp/Set-ExcelColumn.md rename to mdHelp/en/Set-ExcelColumn.md diff --git a/mdHelp/Set-ExcelRange.md b/mdHelp/en/Set-ExcelRange.md similarity index 100% rename from mdHelp/Set-ExcelRange.md rename to mdHelp/en/Set-ExcelRange.md diff --git a/mdHelp/Set-ExcelRow.md b/mdHelp/en/Set-ExcelRow.md similarity index 100% rename from mdHelp/Set-ExcelRow.md rename to mdHelp/en/Set-ExcelRow.md diff --git a/mdHelp/Update-FirstObjectProperties.md b/mdHelp/en/Update-FirstObjectProperties.md similarity index 100% rename from mdHelp/Update-FirstObjectProperties.md rename to mdHelp/en/Update-FirstObjectProperties.md From a37f6f375494e2c0a38a04696f4828e692a2b787 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sun, 1 Dec 2019 18:46:45 +0000 Subject: [PATCH 21/25] Relocate files (hopefully final!) --- Public/ArgumentCompletion.ps1 => ArgumentCompletion.ps1 | 0 ImportExcel.psd1 | 6 ++---- Public/Install.ps1 => Install.ps1 | 0 Public/InstallModule.ps1 => InstallModule.ps1 | 0 Public/PublishToGallery.ps1 => PublishToGallery.ps1 | 0 5 files changed, 2 insertions(+), 4 deletions(-) rename Public/ArgumentCompletion.ps1 => ArgumentCompletion.ps1 (100%) rename Public/Install.ps1 => Install.ps1 (100%) rename Public/InstallModule.ps1 => InstallModule.ps1 (100%) rename Public/PublishToGallery.ps1 => PublishToGallery.ps1 (100%) diff --git a/Public/ArgumentCompletion.ps1 b/ArgumentCompletion.ps1 similarity index 100% rename from Public/ArgumentCompletion.ps1 rename to ArgumentCompletion.ps1 diff --git a/ImportExcel.psd1 b/ImportExcel.psd1 index 6914d70..c553e85 100644 --- a/ImportExcel.psd1 +++ b/ImportExcel.psd1 @@ -159,10 +159,8 @@ Check out the How To Videos https://www.youtube.com/watch?v=U3Ne_yX4tYo&list=PL5 '.\InferData\InferData.ps1', '.\Pivot\Pivot.ps1', '.\spikes\ConvertFrom-ExcelColumnName.ps1', - '.\Testimonials\t1.png', - '.\images\*.gif', - '.\images\*.png', - '.\Examples\*.*' + '.\Examples', '.\images', '.\Testimonials' ,'.\Public' , ".\Private" + ) # Private data to pass to the module specified in RootModule/ModuleToProcess diff --git a/Public/Install.ps1 b/Install.ps1 similarity index 100% rename from Public/Install.ps1 rename to Install.ps1 diff --git a/Public/InstallModule.ps1 b/InstallModule.ps1 similarity index 100% rename from Public/InstallModule.ps1 rename to InstallModule.ps1 diff --git a/Public/PublishToGallery.ps1 b/PublishToGallery.ps1 similarity index 100% rename from Public/PublishToGallery.ps1 rename to PublishToGallery.ps1 From 229f69313b7936891086a01f7a3d6b6536f099c0 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sun, 1 Dec 2019 22:30:57 +0000 Subject: [PATCH 22/25] final tidy for PR --- CI/Test-SingleFunctions.ps1 | 2 +- CI/build.ps1 | 80 +++++++++++++++++++ ...cksToExcel.ps1 => Export-StocksToExcel.ps1 | 0 Public/Import-Excel.ps1 | 2 +- 4 files changed, 82 insertions(+), 2 deletions(-) create mode 100644 CI/build.ps1 rename Public/Export-StocksToExcel.ps1 => Export-StocksToExcel.ps1 (100%) diff --git a/CI/Test-SingleFunctions.ps1 b/CI/Test-SingleFunctions.ps1 index 6c2350b..ac83cbb 100644 --- a/CI/Test-SingleFunctions.ps1 +++ b/CI/Test-SingleFunctions.ps1 @@ -48,7 +48,7 @@ $reg2 = [Regex]::new(@" # elseif ($reg2.IsMatch($m[0].Value)) {return "function $name has comment-based help"} elseif ($m[0] -inotmatch "\[CmdletBinding\(" -and $m[0] -inotmatch "\[parameter\(" ) {return "$name has is not an advanced function"} - elseif (-not (& $Name -?).synopsis) {return "$name has no help"} + #elseif (-not (& $Name -?).synopsis) {return "$name has no help"} else {Write-Verbose "$name OK"} } } \ No newline at end of file diff --git a/CI/build.ps1 b/CI/build.ps1 new file mode 100644 index 0000000..bff69de --- /dev/null +++ b/CI/build.ps1 @@ -0,0 +1,80 @@ +[CmdletBinding(DefaultParameterSetName = 'Default')] +param( + # Path to install the module to, if not provided -Scope used. + [Parameter(Mandatory, ParameterSetName = 'ModulePath')] + [ValidateNotNullOrEmpty()] + [String]$ModulePath, + + # Path to install the module to, PSModulePath "CurrentUser" or "AllUsers", if not provided "CurrentUser" used. + [Parameter(Mandatory, ParameterSetName = 'Scope')] + [ValidateSet('CurrentUser', 'AllUsers')] + [string] + $Scope = 'CurrentUser', + [switch]$Passthru, + [switch]$Tests +) + +if ($PSScriptRoot) { Push-Location $PSScriptRoot } + +$psdpath = Get-Item "*.psd1" +if (-not $psdpath -or $psdpath.count -gt 1) { + throw "Did not find a unique PSD file " +} +else { + $ModuleName = $psdpath.Name -replace '\.psd1$' , '' + $Settings = $(& ([scriptblock]::Create(($psdpath | Get-Content -Raw)))) +} + +try { + Write-Verbose -Message 'Module installation started' + + if (!$ModulePath) { + if ($IsLinux -or $IsMacOS) {$ModulePathSeparator = ':' } + else {$ModulePathSeparator = ';' } + + if ($Scope -eq 'CurrentUser') { $dir = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::UserProfile) } + else { $dir = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::ProgramFiles) } + $ModulePath = ($env:PSModulePath -split $ModulePathSeparator).where({$_ -like "$dir*"},"First",1) + $ModulePath = Join-Path -Path $ModulePath -ChildPath $ModuleName + $ModulePath = Join-Path -Path $ModulePath -ChildPath $Settings.ModuleVersion + } + + # Create Directory + if (-not (Test-Path -Path $ModulePath)) { + $null = New-Item -Path $ModulePath -ItemType Directory -ErrorAction Stop + Write-Verbose -Message ('Created module folder: "{0}"' -f $ModulePath) + } + + Write-Verbose -Message ('Copying files to "{0}"' -f $ModulePath) + $outputFile = $psdpath | Copy-Item -Destination $ModulePath -PassThru + Foreach ($file in $Settings.FileList) { + if ($file -like '.\*') { + $dest = ($file -replace '\.\\',"$ModulePath\") + if (-not (Test-Path -PathType Container (Split-Path -Parent $dest))) { + $null = New-item -Type Directory -Path (Split-Path -Parent $dest) + } + } + else {$dest = $ModulePath } + Copy-Item $file -Destination $dest -Force -Recurse + } + + if (Test-Path -PathType Container "mdHelp") { + if (-not (Get-Module -ListAvailable platyPS)) { + Write-Verbose-Message ('Installing Platyps to build help files') + Install-Module -Name platyPS -Force -SkipPublisherCheck + } + Import-Module platyPS + Get-ChildItem .\mdHelp -Directory | ForEach-Object { + New-ExternalHelp -Path $_.FullName -OutputPath (Join-Path $ModulePath $_.Name) -Force -Verbose + } + } + $env:PSNewBuildModule = $ModulePath + + if ($Passthru) {$outputFile} +} +catch { + throw ('Failed installing module "{0}". Error: "{1}" in Line {2}' -f $ModuleName, $_, $_.InvocationInfo.ScriptLineNumber) +} +finally { + Write-Verbose -Message 'Module installation end' +} \ No newline at end of file diff --git a/Public/Export-StocksToExcel.ps1 b/Export-StocksToExcel.ps1 similarity index 100% rename from Public/Export-StocksToExcel.ps1 rename to Export-StocksToExcel.ps1 diff --git a/Public/Import-Excel.ps1 b/Public/Import-Excel.ps1 index 5bd4389..11a856b 100644 --- a/Public/Import-Excel.ps1 +++ b/Public/Import-Excel.ps1 @@ -162,7 +162,7 @@ #region Create one object per row if ($AsText) { <#join items in AsText together with ~~~ . Escape any regex special characters... - # which turns * into \* make it .*. Convert ~~~ to $|^ and top and tail with ^%; + # which turns "*" into "\*" make it ".*". Convert ~~~ to $|^ and top and tail with ^%; So if we get "Week", "[Time]" and "*date*" ; make the expression ^week$|^\[Time\]$|^.*Date.*$ $make a regex for this which is case insensitive (option 1) and compiled (option 8) #> From d89346c89c94ea9f88124a269c6c86ed8ffa0791 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sun, 1 Dec 2019 22:39:53 +0000 Subject: [PATCH 23/25] Fix CI getting out of sync with directory changes --- Install.ps1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Install.ps1 b/Install.ps1 index a733000..7f82e96 100644 --- a/Install.ps1 +++ b/Install.ps1 @@ -29,7 +29,8 @@ $IncludeFiles = @( 'Charting', 'en-US', 'Examples', - 'ExportedCommands', + 'Public', + 'Private' 'images', 'InferData', 'InternalFunctions', From b534bd974b9a982f74fd713e6cf4b9fc92ce123c Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sun, 1 Dec 2019 22:43:37 +0000 Subject: [PATCH 24/25] Repeat --- Install.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Install.ps1 b/Install.ps1 index 7f82e96..e7be649 100644 --- a/Install.ps1 +++ b/Install.ps1 @@ -30,7 +30,7 @@ $IncludeFiles = @( 'en-US', 'Examples', 'Public', - 'Private' + 'Private', 'images', 'InferData', 'InternalFunctions', From 1667ba33eb72bd06c82af2cfe318070cb15e6065 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sun, 1 Dec 2019 22:48:11 +0000 Subject: [PATCH 25/25] Fix error caused by empty private dir --- ImportExcel.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ImportExcel.psm1 b/ImportExcel.psm1 index d472f10..b070877 100644 --- a/ImportExcel.psm1 +++ b/ImportExcel.psm1 @@ -7,7 +7,7 @@ if (-not $Strings) { try {[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")} catch {Write-Warning -Message $Strings.SystemDrawingAvaialable} -foreach ($directory in @('Public','Private', 'Charting','InferData','Pivot')) { +foreach ($directory in @('Public','Charting','InferData','Pivot')) { Get-ChildItem -Path "$PSScriptRoot\$directory\*.ps1" | ForEach-Object {. $_.FullName} }