From e2c649534015f9713261c9f07d5003a64ad87295 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sun, 10 Nov 2019 13:29:17 +0000 Subject: [PATCH 01/11] Re-enabled compare worksheet test on V6. --- __tests__/Compare-WorkSheet.tests.ps1 | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/__tests__/Compare-WorkSheet.tests.ps1 b/__tests__/Compare-WorkSheet.tests.ps1 index 14d2b66..ce88404 100644 --- a/__tests__/Compare-WorkSheet.tests.ps1 +++ b/__tests__/Compare-WorkSheet.tests.ps1 @@ -4,15 +4,15 @@ if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { } Describe "Compare Worksheet" { BeforeAll { - if ($PSVersionTable.PSVersion.Major -gt 5) { + <# if ($PSVersionTable.PSVersion.Major -gt 5) { It "GridView Support" { Set-ItResult -Pending -Because "Can't test grid view on V6 and later" } } - else { Add-Type -AssemblyName System.Windows.Forms } + else { Add-Type -AssemblyName System.Windows.Forms } #> . "$PSScriptRoot\Samples\Samples.ps1" Remove-Item -Path "TestDrive:\server*.xlsx" - [System.Collections.ArrayList]$s = get-service | Select-Object -first 25 -Property Name, RequiredServices, CanPauseAndContinue, CanShutdown, CanStop, DisplayName, DependentServices, MachineName + [System.Collections.ArrayList]$s = Get-Service | Select-Object -first 25 -Property Name, RequiredServices, CanPauseAndContinue, CanShutdown, CanStop, DisplayName, DependentServices, MachineName $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 $row4Displayname = $s[2].DisplayName @@ -177,8 +177,8 @@ Describe "Compare Worksheet" { $s2Sheet.Cells["F4"].Style.Font.Color.Rgb | Should beNullOrEmpty } AfterAll { - # Close-ExcelPackage -ExcelPackage $xl1 -NoSave -Show - # Close-ExcelPackage -ExcelPackage $xl2 -NoSave -Show + Close-ExcelPackage -ExcelPackage $xl1 -NoSave # -Show + Close-ExcelPackage -ExcelPackage $xl2 -NoSave # -Show } } } From 16bc380b6550e9362461406ba1c6fc58b6b3ca9f Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sat, 16 Nov 2019 00:33:53 +0000 Subject: [PATCH 02/11] Fix datatable issues with duplicate names & empty tables --- Export-Excel.ps1 | 19 ++++++++++++------- __tests__/Export-Excel.Tests.ps1 | 14 +++++++------- __tests__/InputItemParameter.tests.ps1 | 9 ++++++--- 3 files changed, 25 insertions(+), 17 deletions(-) diff --git a/Export-Excel.ps1 b/Export-Excel.ps1 index 53d79f9..b07b055 100644 --- a/Export-Excel.ps1 +++ b/Export-Excel.ps1 @@ -478,7 +478,7 @@ $TableName, - [OfficeOpenXml.Table.TableStyles]$TableStyle, + [OfficeOpenXml.Table.TableStyles]$TableStyle = [OfficeOpenXml.Table.TableStyles]::Medium6, [Switch]$Barchart, [Switch]$PieChart, [Switch]$LineChart , @@ -534,7 +534,7 @@ if (-not $PSBoundParameters.ContainsKey("TableName") -and -not $PSBoundParameters.ContainsKey("TableStyle") -and -not $AutoFilter) { - $TableName = '' + $TableName = 'Table1' } } if ($ExcelPackage) { @@ -625,7 +625,15 @@ if it was passed 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]) { - $null = $ws.Cells[$row,$StartColumn].LoadFromDataTable($InputObject, (-not $noHeader) ) + if ($TableName) { + $InputObject.TableName = $TableName + $TableName = $null + } + while ($InputObject.TableName -in $pkg.Workbook.Worksheets.Tables.name) { + Write-Warning "Table name $($InputObject.TableName) is not unique, adding '_' to it " + $InputObject.TableName += "_" + } + $null = $ws.Cells[$row,$StartColumn].LoadFromDataTable($InputObject, (-not $noHeader),$TableStyle ) foreach ($c in $InputObject.Columns.where({$_.datatype -eq [datetime]})) { Set-ExcelColumn -Worksheet $ws -Column ($c.Ordinal + $StartColumn) -NumberFormat 'Date-Time' } @@ -808,10 +816,7 @@ #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) { - if ($PSBoundParameters.ContainsKey('TableStyle')) { - Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $TableName -TableStyle $TableStyle - } - else {Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $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 diff --git a/__tests__/Export-Excel.Tests.ps1 b/__tests__/Export-Excel.Tests.ps1 index 424284f..c7df4cc 100644 --- a/__tests__/Export-Excel.Tests.ps1 +++ b/__tests__/Export-Excel.Tests.ps1 @@ -614,7 +614,7 @@ Describe ExportExcel { $dataWs = $Excel.Workbook.Worksheets["NoOffset"] it "Created a new sheet and auto-extended a table and explicitly extended named ranges " { - $dataWs.Tables["ProcTab"].Address.Address | Should be "A1:E21" + $dataWs.Tables["ProcTab"].Address.Address | Should be "A1:E11" $dataWs.Names["CPU"].Rows | Should be 20 $dataWs.Names["CPU"].Columns | Should be 1 } @@ -657,7 +657,7 @@ Describe ExportExcel { #Catch warning $warnvar = $null #Test create two data pages; as part of adding the second give both their own pivot table, test -autosize switch - Get-Service | Select-Object -Property Status, Name, DisplayName, StartType, CanPauseAndContinue | Export-Excel -Path $path -AutoSize -TableName "All Services" -TableStyle Medium1 -WarningVariable warnvar + Get-Service | Select-Object -Property Status, Name, DisplayName, StartType, CanPauseAndContinue | Export-Excel -Path $path -AutoSize -TableName "All Services" -TableStyle Medium1 -WarningVariable warnvar -WarningAction SilentlyContinue Get-Process | Select-Object -Property Name, Company, Handles, CPU, VM | Export-Excel -Path $path -AutoSize -WorkSheetname 'sheet2' -TableName "Processes" -TableStyle Light1 -Title "Processes" -TitleFillPattern Solid -TitleBackgroundColor ([System.Drawing.Color]::AliceBlue) -TitleBold -TitleSize 22 -PivotTableDefinition $ptDef $Excel = Open-ExcelPackage $path $ws1 = $Excel.Workbook.Worksheets["Sheet1"] @@ -1004,7 +1004,7 @@ Describe ExportExcel { Remove-Item -Path $Path -ErrorAction SilentlyContinue $Processes = Get-Process | Select-Object -first 10 -Property Name, cpu, pm, handles, company - it "Default Set with Path".PadRight(87) { + it "Allows the default parameter set with Path".PadRight(87) { $ExcelPackage = $Processes | Export-Excel -Path $Path -PassThru $Worksheet = $ExcelPackage.Workbook.Worksheets[1] @@ -1013,7 +1013,7 @@ Describe ExportExcel { $Worksheet.Tables | Should BeNullOrEmpty $Worksheet.AutoFilterAddress | Should BeNullOrEmpty } - it "ExcelPackage Set. Path and (ExcelPackage or Now) should throw".PadRight(87) { + it "throws when the ExcelPackage is specified with either -path or -Now".PadRight(87) { $ExcelPackage = Export-Excel -Path $Path -PassThru {Export-Excel -ExcelPackage $ExcelPackage -Path $Path} | Should Throw 'Parameter set cannot be resolved using the specified named parameters' {Export-Excel -ExcelPackage $ExcelPackage -Now} | Should Throw 'Parameter set cannot be resolved using the specified named parameters' @@ -1039,9 +1039,9 @@ Describe ExportExcel { $ExcelPackage = $Processes | Export-Excel -Now -PassThru $Worksheet = $ExcelPackage.Workbook.Worksheets[1] - $ExcelPackage.File | Should BeLike ([IO.Path]::GetTempPath() + '*') - $Worksheet.Tables[0].Name | Should Be 'Table1' - $Worksheet.AutoFilterAddress | Should BeNullOrEmpty + $ExcelPackage.File.FullName | Should BeLike ([IO.Path]::GetTempPath() + '*') + $Worksheet.Tables[0].Name | Should Be 'Table1' + $Worksheet.AutoFilterAddress | Should BeNullOrEmpty if ($isWindows) { $Worksheet.Column(5).Width | Should BeGreaterThan 9.5 } diff --git a/__tests__/InputItemParameter.tests.ps1 b/__tests__/InputItemParameter.tests.ps1 index d1cee88..bb0c0cb 100644 --- a/__tests__/InputItemParameter.tests.ps1 +++ b/__tests__/InputItemParameter.tests.ps1 @@ -15,7 +15,7 @@ Describe "Exporting with -Inputobject; table handling, Send SQL Data and import } 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" + Send-SQLDataToExcel -path $path -DataTable $DataTable -WorkSheetname Sheet3 -TableName "Data" $DataTable.Rows.Clear() Send-SQLDataToExcel -path $path -DataTable $DataTable -WorkSheetname Sheet4 -force -WarningVariable WVOne -WarningAction SilentlyContinue Send-SQLDataToExcel -path $path -DataTable ([System.Data.DataTable]::new('Test2')) -WorkSheetname Sheet5 -force -WarningVariable wvTwo -WarningAction SilentlyContinue @@ -87,12 +87,15 @@ Describe "Exporting with -Inputobject; table handling, Send SQL Data and import $sheet.cells["A1"].Value | should be "Name" $sheet.cells["E1"].Value | should be "StartTime" $sheet.cells["A3"].Value | should beNullOrEmpty - $wvone | should not beNullOrEmpty + $wvone[0] | should match "Zero" + } + it "Handled two data tables with the same name " { + $wvone[1] | should match "is not unique" } } $Sheet = $excel.Sheet5 Context "Zero-column Data Table handled by Send-SQLDataToExcel -Force" { - it "Put Created a blank Sheet and raised a warning " { + it "Created a blank Sheet and raised a warning " { $sheet.Dimension | should beNullOrEmpty $wvTwo | should not beNullOrEmpty } From 07b36e5e56e7e3f01a06d8265bfeddd089d62781 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sat, 16 Nov 2019 11:01:57 +0000 Subject: [PATCH 03/11] improve table options on export --- Export-Excel.ps1 | 29 +++++++++++--------- __tests__/InputItemParameter.tests.ps1 | 37 ++++++++++++++++++++++---- 2 files changed, 48 insertions(+), 18 deletions(-) diff --git a/Export-Excel.ps1 b/Export-Excel.ps1 index b07b055..4459690 100644 --- a/Export-Excel.ps1 +++ b/Export-Excel.ps1 @@ -422,11 +422,9 @@ [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')] @@ -462,8 +460,6 @@ [Switch]$FreezeFirstColumn, [Switch]$FreezeTopRowFirstColumn, [Int[]]$FreezePane, - - [Switch]$AutoFilter, [Switch]$BoldTopRow, [Switch]$NoHeader, @@ -473,11 +469,8 @@ else { $true } })] [String]$RangeName, - - + [Alias('Table')] $TableName, - - [OfficeOpenXml.Table.TableStyles]$TableStyle = [OfficeOpenXml.Table.TableStyles]::Medium6, [Switch]$Barchart, [Switch]$PieChart, @@ -525,12 +518,14 @@ #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."} + 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 ($PSBoundParameters.Keys.Count -eq 0 -Or $Now -or (-not $Path -and -not $ExcelPackage) ) { + 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) { @@ -622,18 +617,26 @@ 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 was passed it is a data table don't do foreach on it (slow) put the whole table in and set dates on date columns, + 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 - $TableName = $null } while ($InputObject.TableName -in $pkg.Workbook.Worksheets.Tables.name) { Write-Warning "Table name $($InputObject.TableName) is not unique, adding '_' to it " $InputObject.TableName += "_" } - $null = $ws.Cells[$row,$StartColumn].LoadFromDataTable($InputObject, (-not $noHeader),$TableStyle ) + 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' } diff --git a/__tests__/InputItemParameter.tests.ps1 b/__tests__/InputItemParameter.tests.ps1 index bb0c0cb..28ddc45 100644 --- a/__tests__/InputItemParameter.tests.ps1 +++ b/__tests__/InputItemParameter.tests.ps1 @@ -1,8 +1,8 @@ -Describe "Exporting with -Inputobject; table handling, Send SQL Data and import as " { +Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking Import -asText" { BeforeAll { $path = "TestDrive:\Results.xlsx" Remove-Item -Path $path -ErrorAction SilentlyContinue - . "$PSScriptRoot\Samples\Samples.ps1" + 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') $null = $DataTable.Columns.Add('Name') @@ -13,11 +13,17 @@ Describe "Exporting with -Inputobject; table handling, Send SQL Data and import foreach ($r in $results) { $null = $DataTable.Rows.Add($r.name, $r.CPU, $R.PM, $r.Handles, $r.StartTime) } - export-excel -Path $path -InputObject $results -WorksheetName Sheet1 -RangeName "Whole" - export-excel -Path $path -InputObject $DataTable -WorksheetName Sheet2 -AutoNameRange + $NowPkg = Export-Excel -InputObject $DataTable -PassThru + $NowPath1 = $NowPkg.File.FullName + Close-ExcelPackage $NowPkg + $NowPkg = Export-Excel -InputObject $DataTable -PassThru -table:$false + $NowPath2 = $NowPkg.File.FullName + 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 -WarningVariable WVOne -WarningAction SilentlyContinue + 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 $excel = Open-ExcelPackage $path $sheet = $excel.Sheet1 @@ -61,6 +67,23 @@ Describe "Exporting with -Inputobject; table handling, Send SQL Data and import $sheet.Cells["E11"].Style.Numberformat.NumFmtID | should be 22 } } + + Context "'Now' Mode behavior" { + $NowPkg = Open-ExcelPackage $NowPath1 + $sheet = $NowPkg.Sheet1 + it "Formatted data as a table by default " { + $sheet.Tables.Count | should be 1 + } + Close-ExcelPackage -NoSave $NowPkg + Remove-Item $NowPath1 + $NowPkg = Open-ExcelPackage $NowPath2 + $sheet = $NowPkg.Sheet1 + it "Did not data as a table when table:`$false was used " { + $sheet.Tables.Count | should be 0 + } + Close-ExcelPackage -NoSave $NowPkg + Remove-Item $NowPath2 + } $sheet = $excel.Sheet3 Context "Table of processes via Send-SQLDataToExcel" { it "Put the correct data rows and columns into the sheet " { @@ -89,9 +112,13 @@ Describe "Exporting with -Inputobject; table handling, Send SQL Data and import $sheet.cells["A3"].Value | should beNullOrEmpty $wvone[0] | should match "Zero" } + it "Applied table formatting " { + $sheet.Tables.Count | should be 1 + } it "Handled two data tables with the same name " { $wvone[1] | should match "is not unique" } + } $Sheet = $excel.Sheet5 Context "Zero-column Data Table handled by Send-SQLDataToExcel -Force" { From 43927ca078a0d5a342ea8bbf7096cf6531d0ba4f Mon Sep 17 00:00:00 2001 From: ili101 Date: Sun, 17 Nov 2019 19:58:14 +0200 Subject: [PATCH 04/11] Export-Excel.ps1 532: Now mode TableName is auto generated if not specified (shouldn't matter just in case). 632: Fix -DataTable "" to use LoadFromDataTable with style (auto generated name) 820: DataTable + TableStyle without TableName corruption fix. Also simplified even more. 822: Change back to "-TableName $TableName" as cange broke test: Export-Excel.Tests.ps1 617: Undo change test was correct. --- Export-Excel.ps1 | 14 ++++++-------- __tests__/Export-Excel.Tests.ps1 | 2 +- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/Export-Excel.ps1 b/Export-Excel.ps1 index 4459690..c0a97f2 100644 --- a/Export-Excel.ps1 +++ b/Export-Excel.ps1 @@ -529,7 +529,7 @@ if (-not $PSBoundParameters.ContainsKey("TableName") -and -not $PSBoundParameters.ContainsKey("TableStyle") -and -not $AutoFilter) { - $TableName = 'Table1' + $TableName = '' } } if ($ExcelPackage) { @@ -629,8 +629,7 @@ Write-Warning "Table name $($InputObject.TableName) is not unique, adding '_' to it " $InputObject.TableName += "_" } - if ($TableName -or $PSBoundParameters.ContainsKey("TableStyle")) { - $TableName = $null + if ($null -ne $TableName -or $PSBoundParameters.ContainsKey("TableStyle")) { $null = $ws.Cells[$row,$StartColumn].LoadFromDataTable($InputObject, (-not $noHeader),$TableStyle ) } else { @@ -818,11 +817,10 @@ 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')) { + if ($InputObject -isnot [System.Data.DataTable]) { + Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $TableName -TableStyle $TableStyle + } } elseif ($AutoFilter) { try { diff --git a/__tests__/Export-Excel.Tests.ps1 b/__tests__/Export-Excel.Tests.ps1 index c7df4cc..89767fa 100644 --- a/__tests__/Export-Excel.Tests.ps1 +++ b/__tests__/Export-Excel.Tests.ps1 @@ -614,7 +614,7 @@ Describe ExportExcel { $dataWs = $Excel.Workbook.Worksheets["NoOffset"] 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 } From 36f27e3d400e33fb562d9e03f86270b77b408b49 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sun, 17 Nov 2019 22:43:42 +0000 Subject: [PATCH 05/11] commented pull request --- Export-Excel.ps1 | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Export-Excel.ps1 b/Export-Excel.ps1 index c0a97f2..189fdde 100644 --- a/Export-Excel.ps1 +++ b/Export-Excel.ps1 @@ -529,7 +529,7 @@ if (-not $PSBoundParameters.ContainsKey("TableName") -and -not $PSBoundParameters.ContainsKey("TableStyle") -and -not $AutoFilter) { - $TableName = '' + $TableName = '' # later rely on distinction between NULL and "" } } if ($ExcelPackage) { @@ -620,7 +620,7 @@ 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 + #Change TableName if $TableName is non-empty; don't leave caller with a renamed table! $orginalTableName = $InputObject.TableName if ($TableName) { $InputObject.TableName = $TableName @@ -629,6 +629,7 @@ 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 ) } @@ -818,6 +819,7 @@ #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 -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 } From 66bf3adf17f3fb87ea9e21104a78159877f53a5b Mon Sep 17 00:00:00 2001 From: jhoneill Date: Sun, 17 Nov 2019 22:45:29 +0000 Subject: [PATCH 06/11] remove LoadPSD calls & 72 empty catch blocks from examples --- 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 fdfe98a..dff53f2 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 cc7d18cc593cca06638c54ad06729214bc598278 Mon Sep 17 00:00:00 2001 From: ili101 Date: Mon, 18 Nov 2019 12:21:21 +0200 Subject: [PATCH 07/11] EPPlus empty row on an empty table --- Export-Excel.ps1 | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Export-Excel.ps1 b/Export-Excel.ps1 index c0a97f2..3735b5f 100644 --- a/Export-Excel.ps1 +++ b/Export-Excel.ps1 @@ -631,6 +631,10 @@ } 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) ) From 5aa841c2254bdbf769acf131ef408ca20fadf9d2 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Wed, 20 Nov 2019 19:14:19 +0000 Subject: [PATCH 08/11] aggressive linting --- 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 | 10 ++-- __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, 218 insertions(+), 189 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 89767fa..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,7 +614,7 @@ 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:E21" $dataWs.Names["CPU"].Rows | Should be 20 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 962a08e..bb8dd61 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 98b91ce19d0cf30ee8bea474a388bbff31f2cdb7 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Thu, 21 Nov 2019 07:40:21 +0000 Subject: [PATCH 09/11] Fix append behavior passing data tables to export --- Export-Excel.ps1 | 52 +++++++++++++++++++++++++++++------------------- 1 file changed, 32 insertions(+), 20 deletions(-) diff --git a/Export-Excel.ps1 b/Export-Excel.ps1 index 7436e99..de3f59d 100644 --- a/Export-Excel.ps1 +++ b/Export-Excel.ps1 @@ -555,6 +555,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} } @@ -571,8 +572,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 @@ -620,27 +623,36 @@ 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 - } - 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) + if ($Append) { + $row ++ + $null = $ws.Cells[$row,$StartColumn].LoadFromDataTable($InputObject, $false ) + if ($TableName) { + Add-ExcelTable -Range $ws.Cells[$ws.Dimension] -TableName $TableName -TableStyle $TableStyle } } - else { - $null = $ws.Cells[$row,$StartColumn].LoadFromDataTable($InputObject, (-not $noHeader) ) + 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 } - $InputObject.TableName = $orginalTableName foreach ($c in $InputObject.Columns.where({$_.datatype -eq [datetime]})) { Set-ExcelColumn -Worksheet $ws -Column ($c.Ordinal + $StartColumn) -NumberFormat 'Date-Time' } From 30e4515287e72a74987bae33ece4b75f49bf6db3 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Thu, 21 Nov 2019 20:20:56 +0000 Subject: [PATCH 10/11] improve DataTable passing to Export --- Export-Excel.ps1 | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Export-Excel.ps1 b/Export-Excel.ps1 index de3f59d..76f6766 100644 --- a/Export-Excel.ps1 +++ b/Export-Excel.ps1 @@ -575,7 +575,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 @@ -623,10 +623,10 @@ 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 ($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 } } From c38adba49d09daee4ab54979178206d18c0fb533 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Thu, 21 Nov 2019 20:22:06 +0000 Subject: [PATCH 11/11] Add tests for improved datatable handling 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