From f65e198986f1b564d4fe4136024d05e66a98594d Mon Sep 17 00:00:00 2001 From: jhoneill Date: Wed, 30 Oct 2019 10:58:59 +0000 Subject: [PATCH 01/11] Adaptation for V6 broke under V5. Fixed --- __tests__/Compare-WorkSheet.tests.ps1 | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/__tests__/Compare-WorkSheet.tests.ps1 b/__tests__/Compare-WorkSheet.tests.ps1 index d94d29d..f30bec2 100644 --- a/__tests__/Compare-WorkSheet.tests.ps1 +++ b/__tests__/Compare-WorkSheet.tests.ps1 @@ -54,18 +54,9 @@ Describe "Compare Worksheet" { } } - Context "Setting the background to highlight different rows, use of grid view." { + Context "Setting the background to highlight different rows" { BeforeAll { - $useGrid = ($PSVersionTable.PSVersion.Major -LE 5) - if ($useGrid) { - $ModulePath = (Get-Command -Name 'Compare-WorkSheet').Module.Path - $PowerShellExec = if ($PSEdition -eq 'Core') {'pwsh.exe'} else {'powershell.exe'} - $PowerShellPath = Join-Path -Path $PSHOME -ChildPath $PowerShellExec - . $PowerShellPath -Command ('Import-Module {0}; $null = Compare-WorkSheet "{1}server1.xlsx" "{1}server2.xlsx" -BackgroundColor ([System.Drawing.Color]::LightGreen) -GridView; Start-Sleep -sec 5' -f $ModulePath, (Resolve-Path 'TestDrive:').ProviderPath) - } - else { - $null = Compare-WorkSheet "TestDrive:\server1.xlsx" "TestDrive:\server2.xlsx" -BackgroundColor ([System.Drawing.Color]::LightGreen) -GridView:$useGrid - } + $null = Compare-WorkSheet "TestDrive:\server1.xlsx" "TestDrive:\server2.xlsx" -BackgroundColor ([System.Drawing.Color]::LightGreen) $xl1 = Open-ExcelPackage -Path "TestDrive:\server1.xlsx" $xl2 = Open-ExcelPackage -Path "TestDrive:\server2.xlsx" $s1Sheet = $xl1.Workbook.Worksheets[1] From 34fe2f429a820476c01a033bdd5a04478223d649 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Wed, 30 Oct 2019 10:59:23 +0000 Subject: [PATCH 02/11] Added support for Import-Excel -ASTEXT --- ImportExcel.psm1 | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/ImportExcel.psm1 b/ImportExcel.psm1 index fcb5081..2d6997d 100644 --- a/ImportExcel.psm1 +++ b/ImportExcel.psm1 @@ -127,6 +127,9 @@ function Import-Excel { .PARAMETER EndColumn By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number. + .PARAMETER AsText + Normally Import-Excel returns the Cell values. If AsText is specified the data is returned as the text displayed in the cells. + .PARAMETER Password Accepts a string that will be used to open a password protected Excel file. @@ -314,6 +317,7 @@ function Import-Excel { [Alias('RightColumn')] [Int]$EndColumn , [Switch]$DataOnly, + [switch]$AsText, [ValidateNotNullOrEmpty()] [String]$Password ) @@ -437,12 +441,17 @@ function Import-Excel { #Disabled write-verbose for speed # Write-Verbose "Import row '$R'" $NewRow = [Ordered]@{ } - - foreach ($P in $PropertyNames) { - $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Value - # Write-Verbose "Import cell '$($Worksheet.Cells[$R, $P.Column].Address)' with property name '$($p.Value)' and value '$($Worksheet.Cells[$R, $P.Column].Value)'." + if ($AsText) { + foreach ($P in $PropertyNames) { + $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Text + } + } + else { + foreach ($P in $PropertyNames) { + $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Value + # Write-Verbose "Import cell '$($Worksheet.Cells[$R, $P.Column].Address)' with property name '$($p.Value)' and value '$($Worksheet.Cells[$R, $P.Column].Value)'." + } } - [PSCustomObject]$NewRow } #endregion From 463944ae2d5040f2aebb35a180474889a84cb542 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Wed, 30 Oct 2019 10:59:45 +0000 Subject: [PATCH 03/11] Added support for Send-SQLData -force --- Send-SQLDataToExcel.ps1 | 65 ++++++++++++++++++++++++++--------------- 1 file changed, 41 insertions(+), 24 deletions(-) diff --git a/Send-SQLDataToExcel.ps1 b/Send-SQLDataToExcel.ps1 index 874ee87..280f82f 100644 --- a/Send-SQLDataToExcel.ps1 +++ b/Send-SQLDataToExcel.ps1 @@ -29,6 +29,8 @@ A System.Data.DataTable object containing the data to be inserted into the spreadsheet without running a query. This remains supported to avoid breaking older scripts, but if you have a DataTable object you can pass the it into Export-Excel using -InputObject. + .PARAMETER Force + If specified Export-Excel will be called with parameters specified, even if there is no data to send .EXAMPLE C:\> Send-SQLDataToExcel -MsSQLserver -Connection localhost -SQL "select name,type,type_desc from [master].[sys].[all_objects]" -Path .\temp.xlsx -WorkSheetname master -AutoSize -FreezeTopRow -AutoFilter -BoldTopRow @@ -108,7 +110,8 @@ [string]$SQL, [int]$QueryTimeout, [Parameter(ParameterSetName="Pre-FetchedData", Mandatory=$true)] - [System.Data.DataTable]$DataTable + [System.Data.DataTable]$DataTable, + [switch]$Force ) #Import the parameters from Export-Excel, we will pass InputObject, and we have the common parameters so exclude those, #and re-write the [Parmameter] attribute on each one to avoid parameterSetName here competing with the settings in Export excel. @@ -135,38 +138,52 @@ $null = $PSBoundParameters.Remove('AutoFilter') } #We were either given a session object or a connection string (with, optionally a MSSQLServer parameter) - #If we got -MSSQLServer, create a SQL connection, if we didn't but we got -Connection create an ODBC connection - if ($MsSQLserver -and $Connection) { + try { + #If we got -MSSQLServer, create a SQL connection, if we didn't but we got -Connection create an ODBC connection + if ($MsSQLserver -and $Connection) { if ($Connection -notmatch '=') {$Connection = "server=$Connection;trusted_connection=true;timeout=60"} $Session = New-Object -TypeName System.Data.SqlClient.SqlConnection -ArgumentList $Connection if ($Session.State -ne 'Open') {$Session.Open()} if ($DataBase) {$Session.ChangeDatabase($DataBase) } - } - elseif ($Connection) { + } + elseif ($Connection) { $Session = New-Object -TypeName System.Data.Odbc.OdbcConnection -ArgumentList $Connection ; $Session.ConnectionTimeout = 30 + } } - if ($Session) { - #A session was either passed in or just created. If it's a SQL one make a SQL DataAdapter, otherwise make an ODBC one - if ($Session -is [String] -and $Global:DbSessions[$Session]) {$Session = $Global:DbSessions[$Session]} - if ($Session.GetType().name -match "SqlConnection") { - $dataAdapter = New-Object -TypeName System.Data.SqlClient.SqlDataAdapter -ArgumentList ( - New-Object -TypeName System.Data.SqlClient.SqlCommand -ArgumentList $SQL, $Session) - } - else { - $dataAdapter = New-Object -TypeName System.Data.Odbc.OdbcDataAdapter -ArgumentList ( - New-Object -TypeName System.Data.Odbc.OdbcCommand -ArgumentList $SQL, $Session ) - } - if ($QueryTimeout) {$dataAdapter.SelectCommand.CommandTimeout = $QueryTimeout} + catch { + Write-Warning "An Error occured trying to connect to $Connection, the error was $([Environment]::NewLine + $_.Exception.InnerException))" + } + if ($Session -is [String] -and $Global:DbSessions[$Session]) {$Session = $Global:DbSessions[$Session]} - #Both adapter types output the same kind of table, create one and fill it from the adapter - $DataTable = New-Object -TypeName System.Data.DataTable - $rowCount = $dataAdapter.fill($dataTable) - Write-Verbose -Message "Query returned $rowCount row(s)" + if ($Session) { + try { + #A session was either passed in or just created. If it's a SQL one make a SQL DataAdapter, otherwise make an ODBC one + if ($Session.GetType().name -match "SqlConnection") { + $dataAdapter = New-Object -TypeName System.Data.SqlClient.SqlDataAdapter -ArgumentList ( + New-Object -TypeName System.Data.SqlClient.SqlCommand -ArgumentList $SQL, $Session) + } + else { + $dataAdapter = New-Object -TypeName System.Data.Odbc.OdbcDataAdapter -ArgumentList ( + New-Object -TypeName System.Data.Odbc.OdbcCommand -ArgumentList $SQL, $Session ) + } + if ($QueryTimeout) {$dataAdapter.SelectCommand.CommandTimeout = $QueryTimeout} + + #Both adapter types output the same kind of table, create one and fill it from the adapter + $DataTable = New-Object -TypeName System.Data.DataTable + $rowCount = $dataAdapter.fill($dataTable) + Write-Verbose -Message "Query returned $rowCount row(s)" + } + catch { + Write-Warning "An Error occured trying to run the query, the error was $([Environment]::NewLine + $_.Exception.InnerException))" + } } - if ($DataTable.Rows.Count) { + #if force was specified export even if there are no rows. If there are no columns, the query failed and export "null" if forced + if ($Force -or $DataTable.Rows.Count) { #Call export-excel removing parameters which relate to the SQL query, and keeping the rest. - 'Connection' , 'Database' , 'Session' , 'MsSQLserver' , 'SQL' , 'DataTable' , 'QueryTimeout' | ForEach-Object {$null = $PSBoundParameters.Remove($_) } - Export-Excel @PSBoundParameters -InputObject $DataTable + 'Connection' , 'Database' , 'Session' , 'MsSQLserver' , 'SQL' , 'DataTable' , 'QueryTimeout' | + ForEach-Object {$null = $PSBoundParameters.Remove($_) } + if ($DataTable.Columns.Count) { Export-Excel @PSBoundParameters -InputObject $DataTable } + else { Export-Excel @PSBoundParameters -InputObject $null } } else {Write-Warning -Message ' No Data to insert.' } #If we were passed a connection and opened a session, close that session. From d2a378ffda2f74a8706bf7adac82bb0809da8908 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Wed, 30 Oct 2019 11:55:54 +0000 Subject: [PATCH 04/11] Ensured tests the module in Azure CI --- __tests__/AddTrendlinesToAChart.tests.ps1 | 5 ++++- __tests__/Compare-WorkSheet.tests.ps1 | 5 +++-- __tests__/ConvertFromExcelToSQLInsert.tests.ps1 | 5 +++-- __tests__/Export-Excel.Tests.ps1 | 5 +++-- __tests__/FunctionAlias.tests.ps1 | 6 +++--- __tests__/ImportExcelTests/Simple.tests.ps1 | 5 +++-- __tests__/Remove-WorkSheet.tests.ps1 | 5 +++-- 7 files changed, 22 insertions(+), 14 deletions(-) diff --git a/__tests__/AddTrendlinesToAChart.tests.ps1 b/__tests__/AddTrendlinesToAChart.tests.ps1 index 5891fc2..9eaf518 100644 --- a/__tests__/AddTrendlinesToAChart.tests.ps1 +++ b/__tests__/AddTrendlinesToAChart.tests.ps1 @@ -1,4 +1,7 @@ -Describe "Test adding trendlines to charts" { +if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { + Import-Module $PSScriptRoot\..\ImportExcel.psd1 +} +Describe "Test adding trendlines to charts" { BeforeAll { $script:data = ConvertFrom-Csv @" Region,Item,TotalSold diff --git a/__tests__/Compare-WorkSheet.tests.ps1 b/__tests__/Compare-WorkSheet.tests.ps1 index f30bec2..14d2b66 100644 --- a/__tests__/Compare-WorkSheet.tests.ps1 +++ b/__tests__/Compare-WorkSheet.tests.ps1 @@ -1,6 +1,7 @@ #Requires -Modules Pester -#Import-Module $PSScriptRoot\..\ImportExcel.psd1 -Force - +if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { + Import-Module $PSScriptRoot\..\ImportExcel.psd1 +} Describe "Compare Worksheet" { BeforeAll { if ($PSVersionTable.PSVersion.Major -gt 5) { diff --git a/__tests__/ConvertFromExcelToSQLInsert.tests.ps1 b/__tests__/ConvertFromExcelToSQLInsert.tests.ps1 index d506fa9..cd1fb90 100644 --- a/__tests__/ConvertFromExcelToSQLInsert.tests.ps1 +++ b/__tests__/ConvertFromExcelToSQLInsert.tests.ps1 @@ -1,5 +1,6 @@ -#Import-Module $PSScriptRoot\..\ImportExcel.psd1 -Force - +if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { + Import-Module $PSScriptRoot\..\ImportExcel.psd1 +} $xlFile = "TestDrive:\testSQL.xlsx" Describe "ConvertFrom-ExcelToSQLInsert" { diff --git a/__tests__/Export-Excel.Tests.ps1 b/__tests__/Export-Excel.Tests.ps1 index 2bf181c..aae2da7 100644 --- a/__tests__/Export-Excel.Tests.ps1 +++ b/__tests__/Export-Excel.Tests.ps1 @@ -1,7 +1,8 @@ #Requires -Modules Pester -#Import-Module $PSScriptRoot\..\ImportExcel.psd1 -Force - +if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { + Import-Module $PSScriptRoot\..\ImportExcel.psd1 +} Describe ExportExcel { . "$PSScriptRoot\Samples\Samples.ps1" if (Get-process -Name Excel,xlim -ErrorAction SilentlyContinue) { diff --git a/__tests__/FunctionAlias.tests.ps1 b/__tests__/FunctionAlias.tests.ps1 index 86fbe10..8468109 100644 --- a/__tests__/FunctionAlias.tests.ps1 +++ b/__tests__/FunctionAlias.tests.ps1 @@ -1,7 +1,7 @@ #Requires -Modules Pester -#remove-module importExcel -erroraction silentlyContinue -#Import-Module $PSScriptRoot\..\ImportExcel.psd1 -Force - +if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { + Import-Module $PSScriptRoot\..\ImportExcel.psd1 +} Describe "Check if Function aliases exist" { diff --git a/__tests__/ImportExcelTests/Simple.tests.ps1 b/__tests__/ImportExcelTests/Simple.tests.ps1 index 46f8d07..1e91a1f 100644 --- a/__tests__/ImportExcelTests/Simple.tests.ps1 +++ b/__tests__/ImportExcelTests/Simple.tests.ps1 @@ -1,5 +1,6 @@ -#Import-Module $PSScriptRoot\..\..\ImportExcel.psd1 - +if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { + Import-Module $PSScriptRoot\..\..\ImportExcel.psd1 +} Describe "Tests" { BeforeAll { $data = $null diff --git a/__tests__/Remove-WorkSheet.tests.ps1 b/__tests__/Remove-WorkSheet.tests.ps1 index b433b45..427281d 100644 --- a/__tests__/Remove-WorkSheet.tests.ps1 +++ b/__tests__/Remove-WorkSheet.tests.ps1 @@ -1,6 +1,7 @@ #Requires -Modules Pester -#Import-Module $PSScriptRoot\..\ImportExcel.psd1 -Force - +if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { + Import-Module $PSScriptRoot\..\ImportExcel.psd1 +} Describe "Remove Worksheet" { Context "Remove a worksheet output" { BeforeEach { From fb9a592e9e3d61d3afdf4f110d3ccedf07378126 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Wed, 30 Oct 2019 16:16:41 +0000 Subject: [PATCH 05/11] Wasn't removing force from Param to passed thru --- Send-SQLDataToExcel.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Send-SQLDataToExcel.ps1 b/Send-SQLDataToExcel.ps1 index 280f82f..d9b254e 100644 --- a/Send-SQLDataToExcel.ps1 +++ b/Send-SQLDataToExcel.ps1 @@ -180,7 +180,7 @@ #if force was specified export even if there are no rows. If there are no columns, the query failed and export "null" if forced if ($Force -or $DataTable.Rows.Count) { #Call export-excel removing parameters which relate to the SQL query, and keeping the rest. - 'Connection' , 'Database' , 'Session' , 'MsSQLserver' , 'SQL' , 'DataTable' , 'QueryTimeout' | + 'Connection' , 'Database' , 'Session' , 'MsSQLserver' , 'SQL' , 'DataTable' , 'QueryTimeout' , 'Force' | ForEach-Object {$null = $PSBoundParameters.Remove($_) } if ($DataTable.Columns.Count) { Export-Excel @PSBoundParameters -InputObject $DataTable } else { Export-Excel @PSBoundParameters -InputObject $null } From 5d92442488437244f3c3e615eb698ddc88c0d33f Mon Sep 17 00:00:00 2001 From: jhoneill Date: Wed, 30 Oct 2019 17:38:09 +0000 Subject: [PATCH 06/11] New tests for import -asText and send-SQL -Force --- __tests__/InputItemParameter.tests.ps1 | 30 ++++++++++++++++++- .../Set-Row_Set-Column-SetFormat.tests.ps1 | 30 +++++++++---------- 2 files changed, 44 insertions(+), 16 deletions(-) diff --git a/__tests__/InputItemParameter.tests.ps1 b/__tests__/InputItemParameter.tests.ps1 index f85739b..b572f80 100644 --- a/__tests__/InputItemParameter.tests.ps1 +++ b/__tests__/InputItemParameter.tests.ps1 @@ -16,6 +16,9 @@ Describe "Exporting with -Inputobject" { 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 + Send-SQLDataToExcel -path $path -DataTable ([System.Data.DataTable]::new('Test2')) -WorkSheetname Sheet5 -force $excel = Open-ExcelPackage $path $sheet = $excel.Sheet1 } @@ -60,7 +63,7 @@ Describe "Exporting with -Inputobject" { } $sheet = $excel.Sheet3 Context "Table of processes via Send-SQLDataToExcel" { - it "Put the correct rows and columns into the sheet " { + it "Put the correct data rows and columns into the sheet " { $sheet.Dimension.Rows | should be ($results.Count + 1) $sheet.Dimension.Columns | should be 5 $sheet.cells["A1"].Value | should be "Name" @@ -76,4 +79,29 @@ Describe "Exporting with -Inputobject" { $sheet.Cells["E11"].Style.Numberformat.NumFmtID | should be 22 } } + $Sheet = $excel.Sheet4 + Context "Zero row Data Table sent with Send-SQLDataToExcel -Force" { + it "Put the correct data headers into the sheet " { + $sheet.Dimension.Rows | should be 1 + $sheet.Dimension.Columns | should be 5 + $sheet.cells["A1"].Value | should be "Name" + $sheet.cells["E1"].Value | should be "StartTime" + $sheet.cells["A3"].Value | should beNullOrEmpty + } + } + $Sheet = $excel.Sheet5 + Context "Zero column data table handled by Send-SQLDataToExcel -Force" { + it "Put Created a blank Sheet " { + $sheet.Dimension | should beNullOrEmpty + } + } + Close-ExcelPackage $excel + Context "Import As Text returns text values" { + $x = import-excel $path -WorksheetName sheet3 -AsText | Select-Object -last 1 + it "Had fields of type string, not date or int " { + $x.Handles.GetType().Name | should be "String" + $x.StartTime.GetType().Name | should be "String" + } + } + } \ No newline at end of file diff --git a/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 b/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 index 2b6bac0..f2d71c7 100644 --- a/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 +++ b/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 @@ -323,36 +323,36 @@ Describe "AutoNameRange data with a single property name" { Remove-Item $xlfile -ErrorAction SilentlyContinue } - it "Should have a single item as a named range" { - $excel = ConvertFrom-Csv @" + it "Should have a single item as a named range " { + $excel = ConvertFrom-Csv @" Sold 1 2 3 4 -"@ | Export-Excel $xlfile -PassThru -AutoNameRange +"@ | Export-Excel $xlfile -PassThru -AutoNameRange - $ws = $excel.Workbook.Worksheets["Sheet1"] + $ws = $excel.Workbook.Worksheets["Sheet1"] - $ws.Names.Count | Should Be 1 - $ws.Names[0].Name | Should Be 'Sold' - } + $ws.Names.Count | Should Be 1 + $ws.Names[0].Name | Should Be 'Sold' + } - it "Should have a more than a single item as a named range" { - $excel = ConvertFrom-Csv @" + it "Should have a more than a single item as a named range " { + $excel = ConvertFrom-Csv @" Sold,ID 1,a 2,b 3,c 4,d -"@ | Export-Excel $xlfile -PassThru -AutoNameRange +"@ | Export-Excel $xlfile -PassThru -AutoNameRange - $ws = $excel.Workbook.Worksheets["Sheet1"] + $ws = $excel.Workbook.Worksheets["Sheet1"] - $ws.Names.Count | Should Be 2 - $ws.Names[0].Name | Should Be 'Sold' - $ws.Names[1].Name | Should Be 'ID' - } + $ws.Names.Count | Should Be 2 + $ws.Names[0].Name | Should Be 'Sold' + $ws.Names[1].Name | Should Be 'ID' + } } Describe "Table Formatting" { From 3284f592b9cf184a2a17f0c001bf6c8c97731033 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Thu, 31 Oct 2019 10:31:54 +0000 Subject: [PATCH 07/11] -Force behavior clearer in Send-SQLData --- Send-SQLDataToExcel.ps1 | 36 +++++++++++++++++--------- __tests__/InputItemParameter.tests.ps1 | 17 +++++++----- 2 files changed, 34 insertions(+), 19 deletions(-) diff --git a/Send-SQLDataToExcel.ps1 b/Send-SQLDataToExcel.ps1 index d9b254e..c7c3555 100644 --- a/Send-SQLDataToExcel.ps1 +++ b/Send-SQLDataToExcel.ps1 @@ -128,7 +128,7 @@ return $paramDictionary } process { - #Dynamic params mean we can get passed parameter combination Export-Excel will reject, so throw here, rather than get data and then have Export-Excel error. + #region Dynamic params mean we can get passed parameter combination Export-Excel will reject, so throw here, rather than get data and then have Export-Excel error. if ($PSBoundParameters.Path -and $PSBoundParameters.ExcelPackage) { throw 'Parameter error: you cannot specify both a path and an Excel Package.' return @@ -137,7 +137,8 @@ Write-Warning "Tables are automatically auto-filtered, -AutoFilter will be ignored" $null = $PSBoundParameters.Remove('AutoFilter') } - #We were either given a session object or a connection string (with, optionally a MSSQLServer parameter) + #endregion + #region if we were either given a session object or a connection string (& optionally -MSSQLServer) make sure we can connect try { #If we got -MSSQLServer, create a SQL connection, if we didn't but we got -Connection create an ODBC connection if ($MsSQLserver -and $Connection) { @@ -154,10 +155,11 @@ Write-Warning "An Error occured trying to connect to $Connection, the error was $([Environment]::NewLine + $_.Exception.InnerException))" } if ($Session -is [String] -and $Global:DbSessions[$Session]) {$Session = $Global:DbSessions[$Session]} - + #endregion + #region we may have been given a table, but if there is a db session to connect to, send the query if ($Session) { try { - #A session was either passed in or just created. If it's a SQL one make a SQL DataAdapter, otherwise make an ODBC one + #If the session a SQL one make a SQL DataAdapter, otherwise make an ODBC one if ($Session.GetType().name -match "SqlConnection") { $dataAdapter = New-Object -TypeName System.Data.SqlClient.SqlDataAdapter -ArgumentList ( New-Object -TypeName System.Data.SqlClient.SqlCommand -ArgumentList $SQL, $Session) @@ -177,16 +179,26 @@ Write-Warning "An Error occured trying to run the query, the error was $([Environment]::NewLine + $_.Exception.InnerException))" } } - #if force was specified export even if there are no rows. If there are no columns, the query failed and export "null" if forced - if ($Force -or $DataTable.Rows.Count) { - #Call export-excel removing parameters which relate to the SQL query, and keeping the rest. - 'Connection' , 'Database' , 'Session' , 'MsSQLserver' , 'SQL' , 'DataTable' , 'QueryTimeout' , 'Force' | + #endregion + #region send the table to Excel + #remove parameters which relate to querying SQL, leaving the ones used by Export-Excel + 'Connection' , 'Database' , 'Session' , 'MsSQLserver' , 'SQL' , 'DataTable' , 'QueryTimeout' , 'Force' | ForEach-Object {$null = $PSBoundParameters.Remove($_) } - if ($DataTable.Columns.Count) { Export-Excel @PSBoundParameters -InputObject $DataTable } - else { Export-Excel @PSBoundParameters -InputObject $null } + #if force was specified export even if there are no rows. If there are no columns, the query failed and export "null" if forced + if ($DataTable.Rows.Count) { + Export-Excel @PSBoundParameters -InputObject $DataTable } - else {Write-Warning -Message ' No Data to insert.' } - #If we were passed a connection and opened a session, close that session. + elseif ($Force -and $DataTable.Columns.Count) { + Write-Warning -Message "Zero rows returned, and -Force was specified, sending empty table to Excel." + Export-Excel @PSBoundParameters -InputObject $DataTable + } + elseif ($Force) { + Write-Warning -Message "-Force was specified but there is no data to send." + Export-Excel @PSBoundParameters -InputObject $null + } + else {Write-Warning -Message 'There is no Data to insert, and -Force was not specified.' } + #endregion + #If we were passed a connection and opened a session, close that session. if ($Connection) {$Session.close() } } } \ No newline at end of file diff --git a/__tests__/InputItemParameter.tests.ps1 b/__tests__/InputItemParameter.tests.ps1 index b572f80..ceac4a3 100644 --- a/__tests__/InputItemParameter.tests.ps1 +++ b/__tests__/InputItemParameter.tests.ps1 @@ -1,4 +1,4 @@ -Describe "Exporting with -Inputobject" { +Describe "Exporting with -Inputobject; table handling, Send SQL Data and import as " { BeforeAll { $path = "TestDrive:\Results.xlsx" Remove-Item -Path $path -ErrorAction SilentlyContinue @@ -17,8 +17,8 @@ Describe "Exporting with -Inputobject" { 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 - Send-SQLDataToExcel -path $path -DataTable ([System.Data.DataTable]::new('Test2')) -WorkSheetname Sheet5 -force + 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 $excel = Open-ExcelPackage $path $sheet = $excel.Sheet1 } @@ -80,20 +80,23 @@ Describe "Exporting with -Inputobject" { } } $Sheet = $excel.Sheet4 - Context "Zero row Data Table sent with Send-SQLDataToExcel -Force" { - it "Put the correct data headers into the sheet " { + Context "Zero-row Data Table sent with Send-SQLDataToExcel -Force" { + it "Raised a warning and put the correct data headers into the sheet " { $sheet.Dimension.Rows | should be 1 $sheet.Dimension.Columns | should be 5 $sheet.cells["A1"].Value | should be "Name" $sheet.cells["E1"].Value | should be "StartTime" $sheet.cells["A3"].Value | should beNullOrEmpty + $wvone | should not beNullOrEmpty } } $Sheet = $excel.Sheet5 - Context "Zero column data table handled by Send-SQLDataToExcel -Force" { - it "Put Created a blank Sheet " { + Context "Zero-column Data Table handled by Send-SQLDataToExcel -Force" { + it "Put Created a blank Sheet and raised a warning " { $sheet.Dimension | should beNullOrEmpty + $wvTwo | should not beNullOrEmpty } + } Close-ExcelPackage $excel Context "Import As Text returns text values" { From c71afe802e3b5730dc444f8722bd9b5ba83a64c3 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Thu, 31 Oct 2019 15:47:44 +0000 Subject: [PATCH 08/11] *Selective* -asText on import & 1 linux test bug --- ImportExcel.psm1 | 32 ++++++++++++++++++++------ __tests__/InputItemParameter.tests.ps1 | 7 +++--- 2 files changed, 29 insertions(+), 10 deletions(-) diff --git a/ImportExcel.psm1 b/ImportExcel.psm1 index 2d6997d..b357fb0 100644 --- a/ImportExcel.psm1 +++ b/ImportExcel.psm1 @@ -60,19 +60,25 @@ else { Write-Warning 'PowerShell 5 is required for plot.ps1' Write-Warning 'PowerShell Excel is ready, except for that functionality' } -if ($IsLinux -or $IsMacOS) { +if (($IsLinux -or $IsMacOS) -and -not $env:AUTOSIZE) { $ExcelPackage = [OfficeOpenXml.ExcelPackage]::new() $Cells = ($ExcelPackage | Add-WorkSheet).Cells['A1'] $Cells.Value = 'Test' try { $Cells.AutoFitColumns() + Write-Warning -Message ('The library needed for Autosize is present but the environment variable for it has not been set' + [environment]::newline + + 'Set $env:AUTOSIZE="True"') } catch { if ($IsLinux) { - Write-Warning -Message 'ImportExcel Module Cannot Autosize. Please run the following command to install dependencies: "sudo apt-get install -y --no-install-recommends libgdiplus libc6-dev"' + Write-Warning -Message ('ImportExcel Module Cannot Autosize. Please run the following command to install dependencies:' + [environment]::newline + + ' "sudo apt-get install -y --no-install-recommends libgdiplus libc6-dev"' +[environment]::newline + + 'and then set the environment variable AUTOSIZE to True.') } if ($IsMacOS) { - Write-Warning -Message 'ImportExcel Module Cannot Autosize. Please run the following command to install dependencies: "brew install mono-libgdiplus"' + Write-Warning -Message ('ImportExcel Module Cannot Autosize. Please run the following command to install dependencies:' + [environment]::newline + + '"brew install mono-libgdiplus"' +[environment]::newline + + 'and then set the environment variable AUTOSIZE to True.') } } finally { @@ -128,7 +134,7 @@ function Import-Excel { By default the import reads up to the last populated column, -EndColumn tells the import to stop at an earlier number. .PARAMETER AsText - Normally Import-Excel returns the Cell values. If AsText is specified the data is returned as the text displayed in the cells. + Normally Import-Excel returns the Cell values. AsText allows selected columns to be returned as the text displayed in their cells. * is supported as a wildcard. .PARAMETER Password Accepts a string that will be used to open a password protected Excel file. @@ -317,7 +323,7 @@ function Import-Excel { [Alias('RightColumn')] [Int]$EndColumn , [Switch]$DataOnly, - [switch]$AsText, + [string[]]$AsText, [ValidateNotNullOrEmpty()] [String]$Password ) @@ -437,13 +443,25 @@ function Import-Excel { } else { #region Create one object per row + if ($AsText) { + <#join items in AsText together with ~~~ . Escape any regex special characters... + # which turns * into \* make it .*. Convert ~~~ to $|^ and top and tail with ^%; + So if we get "Week", "[Time]" and "*date*" ; make the expression ^week$|^\[Time\]$|^.*Date.*$ + $make a regex for this which is case insensitive (option 1) and compiled (option 8) + #> + $TextColExpression = "^" + [regex]::Escape($AsText -join "~~~").replace("\*",".*").replace("~~~","$|^") +"$" + $TextColRegEx = New-Object -TypeName regex -ArgumentList $TextColExpression , 9 + } foreach ($R in $Rows) { #Disabled write-verbose for speed # Write-Verbose "Import row '$R'" $NewRow = [Ordered]@{ } - if ($AsText) { + if ($TextColRegEx) { foreach ($P in $PropertyNames) { - $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Text + if ($TextColRegEx.IsMatch($P.Value)) { + $NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Text + } + else {$NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Value} } } else { diff --git a/__tests__/InputItemParameter.tests.ps1 b/__tests__/InputItemParameter.tests.ps1 index ceac4a3..d1cee88 100644 --- a/__tests__/InputItemParameter.tests.ps1 +++ b/__tests__/InputItemParameter.tests.ps1 @@ -2,7 +2,7 @@ Describe "Exporting with -Inputobject; table handling, Send SQL Data and import BeforeAll { $path = "TestDrive:\Results.xlsx" Remove-Item -Path $path -ErrorAction SilentlyContinue - #Read race results, and group by race name : export 1 row to get headers, leaving enough rows aboce to put in a link for each race + . "$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') @@ -100,10 +100,11 @@ Describe "Exporting with -Inputobject; table handling, Send SQL Data and import } Close-ExcelPackage $excel Context "Import As Text returns text values" { - $x = import-excel $path -WorksheetName sheet3 -AsText | Select-Object -last 1 - it "Had fields of type string, not date or int " { + $x = import-excel $path -WorksheetName sheet3 -AsText StartTime,hand* | Select-Object -last 1 + it "Had fields of type string, not date or int, where specified as ASText " { $x.Handles.GetType().Name | should be "String" $x.StartTime.GetType().Name | should be "String" + $x.CPU.GetType().Name | should not be "String" } } From 065fc2f1ad2944c48492c1b378df3b2768cc8aa8 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Thu, 31 Oct 2019 15:48:49 +0000 Subject: [PATCH 09/11] Better handling of linux autosize issue. --- Export-Excel.ps1 | 5 +-- Merge-Worksheet.ps1 | 3 +- SetFormat.ps1 | 3 +- __tests__/Export-Excel.Tests.ps1 | 34 +++++++++++++------ __tests__/First10Races.tests.ps1 | 1 + .../Set-Row_Set-Column-SetFormat.tests.ps1 | 8 +++-- 6 files changed, 37 insertions(+), 17 deletions(-) diff --git a/Export-Excel.ps1 b/Export-Excel.ps1 index 1aad858..7f46f92 100644 --- a/Export-Excel.ps1 +++ b/Export-Excel.ps1 @@ -76,7 +76,7 @@ .PARAMETER ConditionalText Applies a Conditional formatting rule defined with New-ConditionalText. When specific conditions are met the format is applied. .PARAMETER NoNumberConversion - By default we convert all values to numbers if possible, but this isn't always desirable. NoNumberConversion allows you to add exceptions for the conversion. Wildcards (like '*') are allowed. + By default we convert all values to numbers if possible, but this isn't always desirable. NoNumberConversion allows you to add exceptions for the conversion. The only Wildcard allowed is * for all properties .PARAMETER BoldTopRow Makes the top row boldface. .PARAMETER NoHeader @@ -909,7 +909,7 @@ } catch {Write-Warning -Message "Failed setting the top row to bold in worksheet '$WorksheetName': $_"} } - if ($AutoSize) { + if ($AutoSize -and ([environment]::OSVersion.Platform -like "win*" -or $env:AUTOSIZE)) { try { #Don't fit the all the columns in the sheet; if we are adding cells beside things with hidden columns, that unhides them if ($MaxAutoSizeRows -and $MaxAutoSizeRows -lt $LastRow ) { @@ -921,6 +921,7 @@ } catch { Write-Warning -Message "Failed autosizing columns of worksheet '$WorksheetName': $_"} } + elseif ($AutoSize) {Write-Warning -Message "Auto-fitting columns is not available with this OS configuration." } foreach ($Sheet in $HideSheet) { try { diff --git a/Merge-Worksheet.ps1 b/Merge-Worksheet.ps1 index 01ae37e..2ddbb44 100644 --- a/Merge-Worksheet.ps1 +++ b/Merge-Worksheet.ps1 @@ -512,7 +512,8 @@ Function Merge-MultipleSheets { Add-ConditionalFormatting @condFormattingParams -ConditionValue ("AND(" +(($sameChecks -join ",") -replace '<>"Same"','="Changed"') +")" ) -BackgroundColor $ChangeBackgroundColor } #We've made a bunch of things wider so now is the time to autofit columns. Any hiding has to come AFTER this, because it unhides things - $sheet.Cells.AutoFitColumns() + if ([environment]::OSVersion.Platform -notlike "win*" -and -not $env:AUTOSIZE) {Write-Warning "Autofit is not available with this OS configuration."} + else {$sheet.Cells.AutoFitColumns()} #if we have a key field (we didn't concatenate all fields) use what we built up in $sameChecks to apply conditional formatting to it (Row no will be in column A, Key in Column B) if ($Key -ne '*') { diff --git a/SetFormat.ps1 b/SetFormat.ps1 index f59d50a..131de0c 100644 --- a/SetFormat.ps1 +++ b/SetFormat.ps1 @@ -229,7 +229,7 @@ } else {Write-Warning -Message ("Can set the height of a row or a range but not a {0} object" -f ($Range.GetType().name)) } } - if ($Autosize) { + if ($Autosize -and ([environment]::OSVersion.Platform -like "win*" -or $env:AUTOSIZE)) { try { if ($Range -is [OfficeOpenXml.ExcelColumn]) {$Range.AutoFit() } elseif ($Range -is [OfficeOpenXml.ExcelRange] ) { @@ -240,6 +240,7 @@ } catch {Write-Warning -Message "Failed autosizing columns of worksheet '$WorksheetName': $_"} } + elseif ($AutoSize) {Write-Warning -Message "Auto-fitting columns is not available with this OS configuration." } elseif ($PSBoundParameters.ContainsKey('Width')) { if ($Range -is [OfficeOpenXml.ExcelColumn]) {$Range.Width = $Width} elseif ($Range -is [OfficeOpenXml.ExcelRange] ) { diff --git a/__tests__/Export-Excel.Tests.ps1 b/__tests__/Export-Excel.Tests.ps1 index aae2da7..424284f 100644 --- a/__tests__/Export-Excel.Tests.ps1 +++ b/__tests__/Export-Excel.Tests.ps1 @@ -3,6 +3,8 @@ if (-not (get-command Import-Excel -ErrorAction SilentlyContinue)) { Import-Module $PSScriptRoot\..\ImportExcel.psd1 } +if ($null -eq $IsWindows) {$IsWindows = [environment]::OSVersion.Platform -like "win*"} +$WarningAction = "SilentlyContinue" Describe ExportExcel { . "$PSScriptRoot\Samples\Samples.ps1" if (Get-process -Name Excel,xlim -ErrorAction SilentlyContinue) { @@ -655,20 +657,21 @@ 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 -WarningAction SilentlyContinue -WarningVariable warnvar + Get-Service | Select-Object -Property Status, Name, DisplayName, StartType, CanPauseAndContinue | Export-Excel -Path $path -AutoSize -TableName "All Services" -TableStyle Medium1 -WarningVariable warnvar 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"] $ws2 = $Excel.Workbook.Worksheets["Sheet2"] - - it "Set Column widths (with autosize) " { + if ($isWindows) { + it "Set Column widths (with autosize) " { $ws1.Column(2).Width | Should not be $ws1.DefaultColWidth $ws2.Column(1).width | Should not be $ws2.DefaultColWidth + } } it "Added tables to both sheets (handling illegal chars) and a title in sheet 2 " { - $warnvar.count | Should be 1 + $warnvar.count | Should beGreaterThan 0 $ws1.tables.Count | Should be 1 $ws2.tables.Count | Should be 1 $ws1.Tables[0].Address.Start.Row | Should be 1 @@ -723,7 +726,8 @@ Describe ExportExcel { #Test freezing top row/first column, adding formats and a pivot table - from Add-Pivot table not a specification variable - after the export $excel = Get-Process | Select-Object -Property Name, Company, Handles, CPU, PM, NPM, WS | Export-Excel -Path $path -ClearSheet -WorkSheetname "Processes" -FreezeTopRowFirstColumn -PassThru $sheet = $excel.Workbook.Worksheets["Processes"] - $sheet.Column(1) | Set-ExcelRange -Bold -AutoFit + if ($isWindows) {$sheet.Column(1) | Set-ExcelRange -Bold -AutoFit } + else {$sheet.Column(1) | Set-ExcelRange -Bold } $sheet.Column(2) | Set-ExcelRange -Width 29 -WrapText $sheet.Column(3) | Set-ExcelRange -HorizontalAlignment Right -NFormat "#,###" Set-ExcelRange -Address $sheet.Cells["E1:H1048576"] -HorizontalAlignment Right -NFormat "#,###" @@ -734,7 +738,7 @@ Describe ExportExcel { $rule = Add-ConditionalFormatting -passthru -Address $sheet.cells["C:C"] -RuleType TopPercent -ConditionValue 20 -Bold -StrikeThru Add-ConditionalFormatting -WorkSheet $sheet -Range "G2:G1048576" -RuleType GreaterThan -ConditionValue "104857600" -ForeGroundColor ([System.Drawing.Color]::Red) -Bold -Italic -Underline -BackgroundColor ([System.Drawing.Color]::Beige) -BackgroundPattern LightUp -PatternColor ([System.Drawing.Color]::Gray) #Test Set-ExcelRange with a column - foreach ($c in 5..9) {Set-ExcelRange $sheet.Column($c) -AutoFit } + if ($isWindows) { foreach ($c in 5..9) {Set-ExcelRange $sheet.Column($c) -AutoFit } } Add-PivotTable -PivotTableName "PT_Procs" -ExcelPackage $excel -SourceWorkSheet 1 -PivotRows Company -PivotData @{'Name' = 'Count'} -IncludePivotChart -ChartType ColumnClustered -NoLegend Export-Excel -ExcelPackage $excel -WorksheetName "Processes" -AutoNameRange #Test adding named ranges seperately from adding data. @@ -747,8 +751,10 @@ Describe ExportExcel { } it "Applied the formating " { $sheet | Should not beNullOrEmpty - $sheet.Column(1).wdith | Should not be $sheet.DefaultColWidth - $sheet.Column(7).wdith | Should not be $sheet.DefaultColWidth + if ($isWindows) { + $sheet.Column(1).width | Should not be $sheet.DefaultColWidth + $sheet.Column(7).width | Should not be $sheet.DefaultColWidth + } $sheet.Column(1).style.font.bold | Should be $true $sheet.Column(2).style.wraptext | Should be $true $sheet.Column(2).width | Should be 29 @@ -1036,7 +1042,9 @@ Describe ExportExcel { $ExcelPackage.File | Should BeLike ([IO.Path]::GetTempPath() + '*') $Worksheet.Tables[0].Name | Should Be 'Table1' $Worksheet.AutoFilterAddress | Should BeNullOrEmpty - $Worksheet.Column(5).Width | Should BeGreaterThan 9.5 + if ($isWindows) { + $Worksheet.Column(5).Width | Should BeGreaterThan 9.5 + } } it "Now allows override of Path and TableName".PadRight(87) { $ExcelPackage = $Processes | Export-Excel -Now -PassThru -Path $Path -TableName:$false @@ -1045,7 +1053,9 @@ Describe ExportExcel { $ExcelPackage.File | Should Be $Path $Worksheet.Tables | Should BeNullOrEmpty $Worksheet.AutoFilterAddress | Should BeNullOrEmpty - $Worksheet.Column(5).Width | Should BeGreaterThan 9.5 + if ($isWindows) { + $Worksheet.Column(5).Width | Should BeGreaterThan 9.5 + } } <# Mock looks unreliable need to check Mock -CommandName 'Invoke-Item' @@ -1072,7 +1082,9 @@ Describe ExportExcel { $Worksheet.Tables[0].Name | Should Be 'Data' $Worksheet.AutoFilterAddress | Should BeNullOrEmpty - $Worksheet.Column(5).Width | Should BeGreaterThan 9.5 + if ($isWindows) { + $Worksheet.Column(5).Width | Should BeGreaterThan 9.5 + } } } } diff --git a/__tests__/First10Races.tests.ps1 b/__tests__/First10Races.tests.ps1 index cb4902d..77d8a6f 100644 --- a/__tests__/First10Races.tests.ps1 +++ b/__tests__/First10Races.tests.ps1 @@ -1,5 +1,6 @@ $scriptPath = Split-Path -Path $MyInvocation.MyCommand.path -Parent $dataPath = Join-Path -Path $scriptPath -ChildPath "First10Races.csv" +$WarningAction = "SilentlyContinue" Describe "Creating small named ranges with hyperlinks" { BeforeAll { diff --git a/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 b/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 index f2d71c7..93a3bd0 100644 --- a/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 +++ b/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 @@ -1,3 +1,5 @@ +if ($null -eq $IsWindows) {$IsWindows = [environment]::OSVersion.Platform -like "win*"} + $path = "TestDrive:\test.xlsx" $data = ConvertFrom-Csv -InputObject @" @@ -142,8 +144,10 @@ Describe "Set-ExcelColumn, Set-ExcelRow and Set-ExcelRange" { Set-ExcelRange -WorkSheet $ws -Range "E1" -ResetFont -HorizontalAlignment General -FontName "Courier New" -fontSize 9 Set-ExcelRange -Address $ws.Cells["E7"] -ResetFont -WrapText -BackgroundColor ([System.Drawing.Color]::AliceBlue) -BackgroundPattern DarkTrellis -PatternColor ([System.Drawing.Color]::Red) -NumberFormat "£#,###.00" Set-ExcelRange -Address $ws.Column(1) -Width 0 - Set-ExcelRange -Address $ws.Column(2) -AutoFit - Set-ExcelRange -Address $ws.Cells["E:E"] -AutoFit + if ($IsWindows) { + Set-ExcelRange -Address $ws.Column(2) -AutoFit + Set-ExcelRange -Address $ws.Cells["E:E"] -AutoFit + } #Test alias Set-Format -Address $ws.row(5) -Height 0 $rr = $r.row From 4d17a09537c63e7963168543b6d3ebe8bf89d947 Mon Sep 17 00:00:00 2001 From: jhoneill Date: Fri, 1 Nov 2019 01:56:11 +0000 Subject: [PATCH 10/11] Better .NET version detection --- __tests__/CI.ps1 | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/__tests__/CI.ps1 b/__tests__/CI.ps1 index 55e90a5..5a0e6c5 100644 --- a/__tests__/CI.ps1 +++ b/__tests__/CI.ps1 @@ -21,7 +21,7 @@ if ($Initialize) { } if ($Test) { function Get-EnvironmentInfo { - if ($null -eq $IsWindows -or $IsWindows) { + if ([environment]::OSVersion.Platform -like "win*") { # Get Windows Version try { $WinRelease, $WinVer = Get-ItemPropertyValue "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" ReleaseId, CurrentMajorVersionNumber, CurrentMinorVersionNumber, CurrentBuildNumber, UBR @@ -30,8 +30,18 @@ if ($Test) { catch { $WindowsVersion = [System.Environment]::OSVersion.Version } +#TODO FIXME BUG this gets the latest version of the .NET Framework on the machine (ok for powershell.exe), not the version of .NET CORE in use by PWSH.EXE +<# +$VersionFilePath = (Get-Process -Id $PID | Select-Object -ExpandProperty Modules | + Where-Object -Property modulename -eq "clrjit.dll").FileName +if (-not $VersionFilePath) { + $VersionFilePath = [System.Reflection.Assembly]::LoadWithPartialName("System.Core").location + } + (Get-ItemProperty -Path $VersionFilePath).VersionInfo | + Select-Object -Property @{n="Version"; e={$_.ProductName + " " + $_.FileVersion}}, ProductName, FileVersionRaw, FileName +#> - # Get .Net Version + # Get .Net Version # https://stackoverflow.com/questions/3487265/powershell-script-to-return-versions-of-net-framework-on-a-machine $Lookup = @{ 378389 = [version]'4.5' From 6b626e8f5fcd0eed0c47ca64eb47343f02ba357a Mon Sep 17 00:00:00 2001 From: jhoneill Date: Fri, 1 Nov 2019 01:57:04 +0000 Subject: [PATCH 11/11] Better handling of autosize (again) --- Export-Excel.ps1 | 2 +- ImportExcel.psm1 | 12 +++++------- Merge-Worksheet.ps1 | 2 +- SetFormat.ps1 | 2 +- __tests__/Set-Row_Set-Column-SetFormat.tests.ps1 | 4 +--- 5 files changed, 9 insertions(+), 13 deletions(-) diff --git a/Export-Excel.ps1 b/Export-Excel.ps1 index 7f46f92..53d79f9 100644 --- a/Export-Excel.ps1 +++ b/Export-Excel.ps1 @@ -909,7 +909,7 @@ } catch {Write-Warning -Message "Failed setting the top row to bold in worksheet '$WorksheetName': $_"} } - if ($AutoSize -and ([environment]::OSVersion.Platform -like "win*" -or $env:AUTOSIZE)) { + if ($AutoSize -and -not $env:NoAutoSize) { try { #Don't fit the all the columns in the sheet; if we are adding cells beside things with hidden columns, that unhides them if ($MaxAutoSizeRows -and $MaxAutoSizeRows -lt $LastRow ) { diff --git a/ImportExcel.psm1 b/ImportExcel.psm1 index b357fb0..91e5fda 100644 --- a/ImportExcel.psm1 +++ b/ImportExcel.psm1 @@ -60,25 +60,23 @@ else { Write-Warning 'PowerShell 5 is required for plot.ps1' Write-Warning 'PowerShell Excel is ready, except for that functionality' } -if (($IsLinux -or $IsMacOS) -and -not $env:AUTOSIZE) { +if (($IsLinux -or $IsMacOS) -or $env:NoAutoSize) { $ExcelPackage = [OfficeOpenXml.ExcelPackage]::new() $Cells = ($ExcelPackage | Add-WorkSheet).Cells['A1'] $Cells.Value = 'Test' try { $Cells.AutoFitColumns() - Write-Warning -Message ('The library needed for Autosize is present but the environment variable for it has not been set' + [environment]::newline + - 'Set $env:AUTOSIZE="True"') + if ($env:NoAutoSize) {Remove-Item Env:\NoAutoSize} } catch { + $env:NoAutoSize = $true if ($IsLinux) { Write-Warning -Message ('ImportExcel Module Cannot Autosize. Please run the following command to install dependencies:' + [environment]::newline + - ' "sudo apt-get install -y --no-install-recommends libgdiplus libc6-dev"' +[environment]::newline + - 'and then set the environment variable AUTOSIZE to True.') + '"sudo apt-get install -y --no-install-recommends libgdiplus libc6-dev"') } if ($IsMacOS) { Write-Warning -Message ('ImportExcel Module Cannot Autosize. Please run the following command to install dependencies:' + [environment]::newline + - '"brew install mono-libgdiplus"' +[environment]::newline + - 'and then set the environment variable AUTOSIZE to True.') + '"brew install mono-libgdiplus"') } } finally { diff --git a/Merge-Worksheet.ps1 b/Merge-Worksheet.ps1 index 2ddbb44..331c339 100644 --- a/Merge-Worksheet.ps1 +++ b/Merge-Worksheet.ps1 @@ -512,7 +512,7 @@ Function Merge-MultipleSheets { Add-ConditionalFormatting @condFormattingParams -ConditionValue ("AND(" +(($sameChecks -join ",") -replace '<>"Same"','="Changed"') +")" ) -BackgroundColor $ChangeBackgroundColor } #We've made a bunch of things wider so now is the time to autofit columns. Any hiding has to come AFTER this, because it unhides things - if ([environment]::OSVersion.Platform -notlike "win*" -and -not $env:AUTOSIZE) {Write-Warning "Autofit is not available with this OS configuration."} + if ($env:NoAutoSize) {Write-Warning "Autofit is not available with this OS configuration."} else {$sheet.Cells.AutoFitColumns()} #if we have a key field (we didn't concatenate all fields) use what we built up in $sameChecks to apply conditional formatting to it (Row no will be in column A, Key in Column B) diff --git a/SetFormat.ps1 b/SetFormat.ps1 index 131de0c..272be88 100644 --- a/SetFormat.ps1 +++ b/SetFormat.ps1 @@ -229,7 +229,7 @@ } else {Write-Warning -Message ("Can set the height of a row or a range but not a {0} object" -f ($Range.GetType().name)) } } - if ($Autosize -and ([environment]::OSVersion.Platform -like "win*" -or $env:AUTOSIZE)) { + if ($Autosize -and -not $env:NoAutoSize) { try { if ($Range -is [OfficeOpenXml.ExcelColumn]) {$Range.AutoFit() } elseif ($Range -is [OfficeOpenXml.ExcelRange] ) { diff --git a/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 b/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 index 93a3bd0..962a08e 100644 --- a/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 +++ b/__tests__/Set-Row_Set-Column-SetFormat.tests.ps1 @@ -1,5 +1,3 @@ -if ($null -eq $IsWindows) {$IsWindows = [environment]::OSVersion.Platform -like "win*"} - $path = "TestDrive:\test.xlsx" $data = ConvertFrom-Csv -InputObject @" @@ -144,7 +142,7 @@ Describe "Set-ExcelColumn, Set-ExcelRow and Set-ExcelRange" { Set-ExcelRange -WorkSheet $ws -Range "E1" -ResetFont -HorizontalAlignment General -FontName "Courier New" -fontSize 9 Set-ExcelRange -Address $ws.Cells["E7"] -ResetFont -WrapText -BackgroundColor ([System.Drawing.Color]::AliceBlue) -BackgroundPattern DarkTrellis -PatternColor ([System.Drawing.Color]::Red) -NumberFormat "£#,###.00" Set-ExcelRange -Address $ws.Column(1) -Width 0 - if ($IsWindows) { + if (-not $env:NoAutoSize) { Set-ExcelRange -Address $ws.Column(2) -AutoFit Set-ExcelRange -Address $ws.Cells["E:E"] -AutoFit }