Merge pull request #706 from jhoneill/master

SQL -Force , import -asText , test fixes, better Linux behavior
This commit is contained in:
Doug Finke
2019-11-01 18:57:02 -04:00
committed by GitHub
16 changed files with 209 additions and 96 deletions

View File

@@ -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 -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 ) {
@@ -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 {

View File

@@ -60,19 +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) {
if (($IsLinux -or $IsMacOS) -or $env:NoAutoSize) {
$ExcelPackage = [OfficeOpenXml.ExcelPackage]::new()
$Cells = ($ExcelPackage | Add-WorkSheet).Cells['A1']
$Cells.Value = 'Test'
try {
$Cells.AutoFitColumns()
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: "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"')
}
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"')
}
}
finally {
@@ -127,6 +131,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. 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.
@@ -314,6 +321,7 @@ function Import-Excel {
[Alias('RightColumn')]
[Int]$EndColumn ,
[Switch]$DataOnly,
[string[]]$AsText,
[ValidateNotNullOrEmpty()]
[String]$Password
)
@@ -433,16 +441,33 @@ 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 ($TextColRegEx) {
foreach ($P in $PropertyNames) {
if ($TextColRegEx.IsMatch($P.Value)) {
$NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Text
}
else {$NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Value}
}
}
else {
foreach ($P in $PropertyNames) {
$NewRow[$P.Value] = $Worksheet.Cells[$R, $P.Column].Value
# Write-Verbose "Import cell '$($Worksheet.Cells[$R, $P.Column].Address)' with property name '$($p.Value)' and value '$($Worksheet.Cells[$R, $P.Column].Value)'."
}
}
[PSCustomObject]$NewRow
}
#endregion

View File

@@ -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 ($env:NoAutoSize) {Write-Warning "Autofit is not available with this OS configuration."}
else {$sheet.Cells.AutoFitColumns()}
#if we have a key field (we didn't concatenate all fields) use what we built up in $sameChecks to apply conditional formatting to it (Row no will be in column A, Key in Column B)
if ($Key -ne '*') {

View File

@@ -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.
@@ -125,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
@@ -134,7 +137,9 @@
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) {
if ($Connection -notmatch '=') {$Connection = "server=$Connection;trusted_connection=true;timeout=60"}
@@ -145,9 +150,16 @@
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
}
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]}
#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 {
#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)
@@ -163,12 +175,29 @@
$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))"
}
}
#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 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) {
#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
}
else {Write-Warning -Message ' No Data to insert.' }
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() }
}

View File

@@ -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 -not $env:NoAutoSize) {
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] ) {

View File

@@ -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

View File

@@ -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,6 +30,16 @@ 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
# https://stackoverflow.com/questions/3487265/powershell-script-to-return-versions-of-net-framework-on-a-machine

View File

@@ -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) {
@@ -54,18 +55,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]

View File

@@ -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" {

View File

@@ -1,7 +1,10 @@
#Requires -Modules Pester
#Import-Module $PSScriptRoot\..\ImportExcel.psd1 -Force
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) {
@@ -654,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"]
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
@@ -722,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 "#,###"
@@ -733,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.
@@ -746,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
@@ -1035,8 +1042,10 @@ Describe ExportExcel {
$ExcelPackage.File | 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
}
}
it "Now allows override of Path and TableName".PadRight(87) {
$ExcelPackage = $Processes | Export-Excel -Now -PassThru -Path $Path -TableName:$false
$Worksheet = $ExcelPackage.Workbook.Worksheets[1]
@@ -1044,8 +1053,10 @@ Describe ExportExcel {
$ExcelPackage.File | Should Be $Path
$Worksheet.Tables | Should BeNullOrEmpty
$Worksheet.AutoFilterAddress | Should BeNullOrEmpty
if ($isWindows) {
$Worksheet.Column(5).Width | Should BeGreaterThan 9.5
}
}
<# Mock looks unreliable need to check
Mock -CommandName 'Invoke-Item'
it "Now will Show".PadRight(87) {
@@ -1071,7 +1082,9 @@ Describe ExportExcel {
$Worksheet.Tables[0].Name | Should Be 'Data'
$Worksheet.AutoFilterAddress | Should BeNullOrEmpty
if ($isWindows) {
$Worksheet.Column(5).Width | Should BeGreaterThan 9.5
}
}
}
}

View File

@@ -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 {

View File

@@ -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" {

View File

@@ -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

View File

@@ -1,8 +1,8 @@
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
#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')
@@ -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 -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
}
@@ -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,33 @@ 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 "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 and raised a warning " {
$sheet.Dimension | should beNullOrEmpty
$wvTwo | should not beNullOrEmpty
}
}
Close-ExcelPackage $excel
Context "Import As Text returns text values" {
$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"
}
}
}

View File

@@ -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 {

View File

@@ -142,8 +142,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
if (-not $env:NoAutoSize) {
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
@@ -323,7 +325,7 @@ Describe "AutoNameRange data with a single property name" {
Remove-Item $xlfile -ErrorAction SilentlyContinue
}
it "Should have a single item as a named range" {
it "Should have a single item as a named range " {
$excel = ConvertFrom-Csv @"
Sold
1
@@ -338,7 +340,7 @@ Sold
$ws.Names[0].Name | Should Be 'Sold'
}
it "Should have a more than a single item as a named range" {
it "Should have a more than a single item as a named range " {
$excel = ConvertFrom-Csv @"
Sold,ID
1,a