Merge pull request #954 from jhoneill/master

Fixed the pester issues. (Locally and in AzDo pipelines)
This commit is contained in:
Doug Finke
2020-11-23 18:38:51 -05:00
committed by GitHub
23 changed files with 28772 additions and 879 deletions

1
.gitignore vendored
View File

@@ -65,3 +65,4 @@ ImportExcel.zip
~$*
# InstallModule.ps1
# PublishToGallery.ps1
.vscode/*

View File

@@ -225,7 +225,7 @@ if (-not $SkipPostChecks) {
PivotData = @{RuleName = 'Count' }
PivotRows = 'Severity', 'RuleName'
PivotTotals = 'Rows'
PivotChartDefinition = $chartDef
PivotChartDefinition = $chartDef
}
}
}
@@ -249,9 +249,18 @@ if (-not $SkipPesterTests -and (Get-ChildItem -Recurse *.tests.ps1)) {
if (-not (Get-Module -ListAvailable pester | Where-Object -Property version -ge ([version]::new(4, 4, 1)))) {
Install-Module Pester -Force -SkipPublisherCheck -MaximumVersion 4.99.99
}
Import-Module Pester
$PesterOutputPath = Join-Path $pwd -ChildPath ('TestResultsPS{0}.xml' -f $PSVersionTable.PSVersion)
$pester = Import-Module Pester -PassThru
$pester
$pesterOutputPath = Join-Path $pwd -ChildPath ('TestResultsPS{0}.xml' -f $PSVersionTable.PSVersion)
if ($PSScriptRoot) { Pop-Location }
Invoke-Pester -OutputFile $PesterOutputPath
if ($pester.Version.Major -lt 5) {Invoke-Pester -OutputFile $pesterOutputPath}
else {
$pesterArgs = [PesterConfiguration]::Default
$pesterArgs.Run.Exit = $true
$pesterArgs.Output.Verbosity = "Normal"
$pesterArgs.TestResult.Enabled = $true
$pesterArgs.TestResult.OutputPath = $pesterOutputPath
Invoke-Pester -Configuration $pesterArgs
}
}
elseif ($PSScriptRoot) { Pop-Location }

View File

@@ -0,0 +1,52 @@
Function Import-Bycolumns {
Param(
[Parameter(Mandatory=$true)]
[OfficeOpenXml.ExcelPackage]$ExcelPackage,
[Int]$StartRow = 1,
[String]$WorksheetName,
[Int]$EndRow ,
[Int]$StartColumn = 1,
[Int]$EndColumn
)
Function Get-RowNames {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = "Name would be incorrect, and command is not exported")]
param(
[Parameter(Mandatory)]
[Int[]]$Rows,
[Parameter(Mandatory)]
[Int]$StartColumn
)
foreach ($R in $Rows) {
#allow "False" or "0" to be headings
$Worksheet.Cells[$R, $StartColumn] | Where-Object {-not [string]::IsNullOrEmpty($_.Value) } | Select-Object @{N = 'Row'; E = { $R } }, Value
}
}
if (-not $WorksheetName) { $Worksheet = $ExcelPackage.Workbook.Worksheets[1] }
elseif (-not ($Worksheet = $ExcelPackage.Workbook.Worksheets[$WorkSheetName])) {
throw "Worksheet '$WorksheetName' not found, the workbook only contains the worksheets '$($ExcelPackage.Workbook.Worksheets)'. If you only wish to select the first worksheet, please remove the '-WorksheetName' parameter." ; return
}
if (-not $EndRow ) { $EndRow = $Worksheet.Dimension.End.Row }
if (-not $EndColumn) { $EndColumn = $Worksheet.Dimension.End.Column }
$Rows = $Startrow .. $EndRow ;
$Columns = (1 + $StartColumn)..$EndColumn
if ((-not $rows) -or (-not ($PropertyNames = Get-RowNames -Rows $Rows -StartColumn $StartColumn))) {
throw "No headers found in left coulmn '$Startcolumn'. "; return
}
if (-not $Columns) {
Write-Warning "Worksheet '$WorksheetName' in workbook contains no data in the rows after left column '$StartColumn'"
}
else {
foreach ($c in $Columns) {
$NewColumn = [Ordered]@{ }
foreach ($p in $PropertyNames) {
$NewColumn[$p.Value] = $Worksheet.Cells[$p.row,$c].text
}
[PSCustomObject]$NewColumn
}
}
}

View File

@@ -69,7 +69,7 @@
$Address = "$($Address.Row):$($Address.Row)"
}
elseif ($Address -is [OfficeOpenXml.ExcelColumn]) {
$Address = (New-Object 'OfficeOpenXml.ExcelAddress' @(1, $address.ColumnMin, 1, $address.ColumnMax).Address) -replace '1',''
$Address = (New-Object 'OfficeOpenXml.ExcelAddress' @(1, $address.ColumnMin, 1, $address.ColumnMax)).Address -replace '1',''
if ($Address -notmatch ':') {$Address = "$Address`:$Address"}
}
if ( $Address -is [string] -and $Address -match "!") {$Address = $Address -replace '^.*!',''}

View File

@@ -12,6 +12,9 @@ Describe "Compare Worksheet" {
}
}
else { Add-Type -AssemblyName System.Windows.Forms } #>
if (-not (Get-command Get-Service -ErrorAction SilentlyContinue)) {
Function Get-Service {Import-Clixml $PSScriptRoot\Mockservices.xml}
}
. "$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
@@ -196,6 +199,9 @@ Describe "Compare Worksheet" {
Describe "Merge Worksheet" {
BeforeAll {
if (-not (Get-command Get-Service -ErrorAction SilentlyContinue)) {
Function Get-Service {Import-Clixml $PSScriptRoot\Mockservices.xml}
}
Remove-Item -Path "TestDrive:\server*.xlsx" , "TestDrive:\combined*.xlsx" -ErrorAction SilentlyContinue
[System.Collections.ArrayList]$s = Get-service | Select-Object -first 25 -Property *
@@ -261,6 +267,11 @@ Describe "Merge Worksheet" {
}
}
Describe "Merge Multiple sheets" {
BeforeAll {
if (-not (Get-command Get-Service -ErrorAction SilentlyContinue)) {
Function Get-Service {Import-Clixml $PSScriptRoot\Mockservices.xml}
}
}
Context "Merge 3 sheets with 3 properties" {
BeforeAll {
Remove-Item -Path "TestDrive:\server*.xlsx" , "TestDrive:\combined*.xlsx" -ErrorAction SilentlyContinue

View File

@@ -1,19 +1,18 @@
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')]
$scriptPath = Split-Path -Path $MyInvocation.MyCommand.path -Parent
$dataPath = Join-Path -Path $scriptPath -ChildPath "First10Races.xlsx"
$Outpath = "TestDrive:\"
Describe 'ConvertFrom-ExcelSheet / Export-ExcelSheet' {
BeforeAll {
$scriptPath = $PSScriptRoot
$dataPath = Join-Path -Path $scriptPath -ChildPath "First10Races.xlsx"
$Outpath = "TestDrive:\"
ConvertFrom-ExcelSheet -Path $dataPath -OutputPath $Outpath
$firstText = Get-Content (Join-path -Path $Outpath -ChildPath "First10Races.csv")
ConvertFrom-ExcelSheet -Path $dataPath -OutputPath $Outpath -AsText GridPosition,date
$SecondText = Get-Content (Join-path -Path $Outpath -ChildPath "First10Races.csv")
$script:firstText = Get-Content (Join-path -Path $Outpath -ChildPath "First10Races.csv")
ConvertFrom-ExcelSheet -Path $dataPath -OutputPath $Outpath -AsText GridPosition, date
$script:SecondText = Get-Content (Join-path -Path $Outpath -ChildPath "First10Races.csv")
ConvertFrom-ExcelSheet -Path $dataPath -OutputPath $Outpath -AsText "GridPosition" -Property driver,
@{n="date"; e={[datetime]::FromOADate($_.Date).tostring("#MM/dd/yyyy#")}} , FinishPosition, GridPosition
$ThirdText = Get-Content (Join-path -Path $Outpath -ChildPath "First10Races.csv")
@{n = "date"; e = { [datetime]::FromOADate($_.Date).tostring("#MM/dd/yyyy#") } } , FinishPosition, GridPosition
$script:ThirdText = Get-Content (Join-path -Path $Outpath -ChildPath "First10Races.csv")
ConvertFrom-ExcelSheet -Path $dataPath -OutputPath $Outpath -AsDate "date"
$FourthText = Get-Content (Join-path -Path $Outpath -ChildPath "First10Races.csv")
$script:FourthText = Get-Content (Join-path -Path $Outpath -ChildPath "First10Races.csv")
}
Context "Exporting to CSV" {
it "Exported the expected columns to a CSV file " {
@@ -24,7 +23,7 @@ Describe 'ConvertFrom-ExcelSheet / Export-ExcelSheet' {
}
it "Applied AsText, AsDate and Properties correctly " {
$firstText[1] | Should -Match '^"\w+","\d{5}","\d{1,2}","\w+ \w+","[1-9]\d?","\w+","\d{1,2}"$'
$date = $firstText[1] -replace '^.*(\d{5}).*$', '$1'
$date = $firstText[1] -replace '^.*(\d{5}).*$', '$1'
$date = [datetime]::FromOADate($date).toString("D")
$secondText[1] | Should -Belike "*$date*"
$secondText[1] | Should -Match '"0\d","\w+","\d{1,2}"$'
@@ -32,7 +31,7 @@ Describe 'ConvertFrom-ExcelSheet / Export-ExcelSheet' {
$FourthText[1] | Should -Match '^"\w+","([012]\d/|[1-9]/)'
}
}
Context "Export aliased to ConvertFrom" {
Context "Export aliased to ConvertFrom" {
it "Definded the alias name with " {
(Get-Alias Export-ExcelSheet).source | Should -Be "ImportExcel"
(Get-Alias Export-ExcelSheet).Definition | Should -Be "ConvertFrom-ExcelSheet"

View File

@@ -1,32 +1,34 @@
if (-not (Get-command Import-Excel -ErrorAction SilentlyContinue)) {
Import-Module $PSScriptRoot\..\ImportExcel.psd1
}
$xlFile = "TestDrive:\testSQL.xlsx"
Describe "ConvertFrom-ExcelToSQLInsert" {
BeforeAll {
$script:xlFile = "TestDrive:\testSQL.xlsx"
}
BeforeEach {
$([PSCustomObject]@{
Name="John"
Age=$null
}) | Export-Excel $xlFile
Name = "John"
Age = $null
}) | Export-Excel $xlFile
}
AfterAll {
Remove-Item $xlFile -Recurse -Force -ErrorAction Ignore
}
It "Should be empty double single quotes".PadRight(90) {
$expected="INSERT INTO Sheet1 ('Name', 'Age') Values('John', '');"
It "Should be empty double single quotes".PadRight(90) {
$expected = "INSERT INTO Sheet1 ('Name', 'Age') Values('John', '');"
$actual = ConvertFrom-ExcelToSQLInsert -Path $xlFile Sheet1
$actual | Should -Be $expected
}
It "Should have NULL".PadRight(90) {
$expected="INSERT INTO Sheet1 ('Name', 'Age') Values('John', NULL);"
It "Should have NULL".PadRight(90) {
$expected = "INSERT INTO Sheet1 ('Name', 'Age') Values('John', NULL);"
$actual = ConvertFrom-ExcelToSQLInsert -Path $xlFile Sheet1 -ConvertEmptyStringsToNull

View File

@@ -1,41 +1,46 @@
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'False Positives')]
param()
Describe "Copy-Worksheet" {
$path1 = "TestDrive:\Test1.xlsx"
$path2 = "TestDrive:\Test2.xlsx"
Remove-Item -Path $path1, $path2 -ErrorAction SilentlyContinue
BeforeAll {
$path1 = "TestDrive:\Test1.xlsx"
$path2 = "TestDrive:\Test2.xlsx"
Remove-Item -Path $path1, $path2 -ErrorAction SilentlyContinue
$ProcRange = Get-Process | Export-Excel $path1 -DisplayPropertySet -WorkSheetname Processes -ReturnRange
$ProcRange = Get-Process | Export-Excel $path1 -DisplayPropertySet -WorkSheetname Processes -ReturnRange
if ((Get-Culture).NumberFormat.CurrencySymbol -eq "£") { $OtherCurrencySymbol = "$" }
else { $OtherCurrencySymbol = "£" }
[PSCustOmobject][Ordered]@{
Date = Get-Date
Formula1 = '=SUM(F2:G2)'
String1 = 'My String'
Float = [math]::pi
IPAddress = '10.10.25.5'
StrLeadZero = '07670'
StrComma = '0,26'
StrEngThousand = '1,234.56'
StrEuroThousand = '1.555,83'
StrDot = '1.2'
StrNegInt = '-31'
StrTrailingNeg = '31-'
StrParens = '(123)'
strLocalCurrency = ('{0}123.45' -f (Get-Culture).NumberFormat.CurrencySymbol )
strOtherCurrency = ('{0}123.45' -f $OtherCurrencySymbol )
StrE164Phone = '+32 (444) 444 4444'
StrAltPhone1 = '+32 4 4444 444'
StrAltPhone2 = '+3244444444'
StrLeadSpace = ' 123'
StrTrailSpace = '123 '
Link1 = [uri]"https://github.com/dfinke/ImportExcel"
Link2 = "https://github.com/dfinke/ImportExcel" # Links are not copied correctly, hopefully this will be fixed at some future date
} | Export-Excel -NoNumberConversion IPAddress, StrLeadZero, StrAltPhone2 -WorkSheetname MixedTypes -Path $path2
if ((Get-Culture).NumberFormat.CurrencySymbol -eq "£") { $OtherCurrencySymbol = "$" }
else { $OtherCurrencySymbol = "£" }
[PSCustOmobject][Ordered]@{
Date = Get-Date
Formula1 = '=SUM(F2:G2)'
String1 = 'My String'
Float = [math]::pi
IPAddress = '10.10.25.5'
StrLeadZero = '07670'
StrComma = '0,26'
StrEngThousand = '1,234.56'
StrEuroThousand = '1.555,83'
StrDot = '1.2'
StrNegInt = '-31'
StrTrailingNeg = '31-'
StrParens = '(123)'
strLocalCurrency = ('{0}123.45' -f (Get-Culture).NumberFormat.CurrencySymbol )
strOtherCurrency = ('{0}123.45' -f $OtherCurrencySymbol )
StrE164Phone = '+32 (444) 444 4444'
StrAltPhone1 = '+32 4 4444 444'
StrAltPhone2 = '+3244444444'
StrLeadSpace = ' 123'
StrTrailSpace = '123 '
Link1 = [uri]"https://github.com/dfinke/ImportExcel"
Link2 = "https://github.com/dfinke/ImportExcel" # Links are not copied correctly, hopefully this will be fixed at some future date
} | Export-Excel -NoNumberConversion IPAddress, StrLeadZero, StrAltPhone2 -WorkSheetname MixedTypes -Path $path2
}
Context "Simplest copy" {
BeforeAll {
$path1 = "TestDrive:\Test1.xlsx"
$path2 = "TestDrive:\Test2.xlsx"
Copy-ExcelWorksheet -SourceWorkbook $path1 -DestinationWorkbook $path2
$excel = Open-ExcelPackage -Path $path2
$ws = $excel.Workbook.Worksheets["Processes"]
@@ -46,8 +51,9 @@ Describe "Copy-Worksheet" {
$ws.Dimension.Address | Should -Be $ProcRange
}
}
Context "Mixed types using a package object" {
Context "Mixed types using a package object" {
BeforeAll {
$excel = Open-ExcelPackage -Path $path2
Copy-ExcelWorksheet -SourceWorkbook $excel -DestinationWorkbook $excel -DestinationWorkSheet "CopyOfMixedTypes"
Close-ExcelPackage -ExcelPackage $excel
$excel = Open-ExcelPackage -Path $path2
@@ -66,26 +72,26 @@ Describe "Copy-Worksheet" {
$ws.Cells[2, 5].Value.GetType().name | Should -Be 'String'
$ws.Cells[2, 6].Value.GetType().name | Should -Be 'String'
$ws.Cells[2, 18].Value.GetType().name | Should -Be 'String'
($ws.Cells[2, 11].Value -is [valuetype] ) | Should -Be $true
($ws.Cells[2, 12].Value -is [valuetype] ) | Should -Be $true
($ws.Cells[2, 13].Value -is [valuetype] ) | Should -Be $true
($ws.Cells[2, 11].Value -is [valuetype] ) | Should -Be $true
($ws.Cells[2, 12].Value -is [valuetype] ) | Should -Be $true
($ws.Cells[2, 13].Value -is [valuetype] ) | Should -Be $true
$ws.Cells[2, 11].Value | Should -BeLessThan 0
$ws.Cells[2, 12].Value | Should -BeLessThan 0
$ws.Cells[2, 13].Value | Should -BeLessThan 0
if ((Get-Culture).NumberFormat.NumberGroupSeparator -EQ ",") {
($ws.Cells[2, 8].Value -is [valuetype] ) | Should -Be $true
($ws.Cells[2, 8].Value -is [valuetype] ) | Should -Be $true
$ws.Cells[2, 9].Value.GetType().name | Should -Be 'String'
}
elseif ((Get-Culture).NumberFormat.NumberGroupSeparator -EQ ".") {
($ws.Cells[2, 9].Value -is [valuetype] ) | Should -Be $true
($ws.Cells[2, 9].Value -is [valuetype] ) | Should -Be $true
$ws.Cells[2, 8].Value.GetType().name | Should -Be 'String'
}
($ws.Cells[2, 14].Value -is [valuetype] ) | Should -Be $true
($ws.Cells[2, 14].Value -is [valuetype] ) | Should -Be $true
$ws.Cells[2, 15].Value.GetType().name | Should -Be 'String'
$ws.Cells[2, 16].Value.GetType().name | Should -Be 'String'
$ws.Cells[2, 17].Value.GetType().name | Should -Be 'String'
($ws.Cells[2, 19].Value -is [valuetype] ) | Should -Be $true
($ws.Cells[2, 20].Value -is [valuetype] ) | Should -Be $true
($ws.Cells[2, 19].Value -is [valuetype] ) | Should -Be $true
($ws.Cells[2, 20].Value -is [valuetype] ) | Should -Be $true
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,10 @@
Describe "Creating workbook with a single line" {
$path = "TestDrive:\test.xlsx"
remove-item -path $path -ErrorAction SilentlyContinue
ConvertFrom-Csv @"
BeforeAll {
$path = "TestDrive:\test.xlsx"
remove-item -path $path -ErrorAction SilentlyContinue
ConvertFrom-Csv @"
Product, City, Gross, Net
Apple, London , 300, 250
Orange, London , 400, 350
@@ -12,14 +13,17 @@ Orange, Paris, 600, 500
Banana, Paris, 300, 200
Apple, New York, 1200,700
"@ | Export-Excel -Path $path -TableStyle Medium13 -tablename "RawData" -ConditionalFormat @{Range="C2:C7"; DataBarColor="Green"} -ExcelChartDefinition @{ChartType="Doughnut";XRange="A2:B7"; YRange="C2:C7"; width=800; } -PivotTableDefinition @{Sales=@{
PivotRows="City"; PivotColumns="Product"; PivotData=@{Gross="Sum";Net="Sum"}; PivotNumberFormat="$#,##0.00"; PivotTotals="Both"; PivotTableStyle="Medium12"; Activate=$true
"@ | Export-Excel -Path $path -TableStyle Medium13 -tablename "RawData" -ConditionalFormat @{Range = "C2:C7"; DataBarColor = "Green" } -ExcelChartDefinition @{ChartType = "Doughnut"; XRange = "A2:B7"; YRange = "C2:C7"; width = 800; } -PivotTableDefinition @{Sales = @{
PivotRows = "City"; PivotColumns = "Product"; PivotData = @{Gross = "Sum"; Net = "Sum" }; PivotNumberFormat = "$#,##0.00"; PivotTotals = "Both"; PivotTableStyle = "Medium12"; Activate = $true
PivotChartDefinition=@{Title="Gross and net by city and product"; ChartType="ColumnClustered"; Column=6; Width=600; Height=360; YMajorUnit=500; YMinorUnit=100; YAxisNumberformat="$#,##0"; LegendPosition="Bottom"}}}
PivotChartDefinition = @{Title = "Gross and net by city and product"; ChartType = "ColumnClustered"; Column = 6; Width = 600; Height = 360; YMajorUnit = 500; YMinorUnit = 100; YAxisNumberformat = "$#,##0"; LegendPosition = "Bottom" }
}
}
$excel = Open-ExcelPackage $path
$ws1 = $excel.Workbook.Worksheets[1]
$ws2 = $excel.Workbook.Worksheets[2]
$excel = Open-ExcelPackage $path
$ws1 = $excel.Workbook.Worksheets[1]
$ws2 = $excel.Workbook.Worksheets[2]
}
Context "Data Page" {
It "Inserted the data and created the table " {
$ws1.Tables[0] | Should -Not -BeNullOrEmpty
@@ -39,7 +43,7 @@ Apple, New York, 1200,700
$ws1.Drawings[0].Series[0].Series | Should -Be "'Sheet1'!C2:C7"
}
}
Context "PivotTable" {
Context "PivotTable" {
it "Created the PivotTable on a new page " {
$ws2 | Should -Not -BeNullOrEmpty
$ws2.PivotTables[0] | Should -Not -BeNullOrEmpty

View File

@@ -1,17 +1,15 @@
[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"

Describe "Creating small named ranges with hyperlinks" {
BeforeAll {
$scriptPath = $PSScriptRoot
$dataPath = Join-Path -Path $scriptPath -ChildPath "First10Races.csv"
$WarningAction = "SilentlyContinue"
$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
$results = Import-Csv -Path $dataPath |
Select-Object Race, @{n = "Date"; e = {[datetime]::ParseExact($_.date, "dd/MM/yyyy", (Get-Culture))}}, FinishPosition, Driver, GridPosition, Team, Points |
Group-Object -Property RACE
Select-Object Race, @{n = "Date"; e = { [datetime]::ParseExact($_.date, "dd/MM/yyyy", (Get-Culture)) } }, FinishPosition, Driver, GridPosition, Team, Points |
Group-Object -Property RACE
$topRow = $lastDataRow = 1 + $results.Count
$excel = $results[0].Group[0] | Export-Excel -Path $path -StartRow $TopRow -BoldTopRow -PassThru
@@ -23,7 +21,7 @@ Describe "Creating small named ranges with hyperlinks" {
$worksheet = $excel.Workbook.Worksheets[1]
$columns = $worksheet.Dimension.Columns
1..$columns | ForEach-Object {Add-ExcelName -Range $worksheet.cells[$topRow, $_, $lastDataRow, $_]} #Test Add-Excel Name on its own (outside Export-Excel)
1..$columns | ForEach-Object { Add-ExcelName -Range $worksheet.cells[$topRow, $_, $lastDataRow, $_] } #Test Add-Excel Name on its own (outside Export-Excel)
$scwarnVar = $null
Set-ExcelColumn -Worksheet $worksheet -StartRow $topRow -Heading "PlacesGained/Lost" `
@@ -33,7 +31,7 @@ Describe "Creating small named ranges with hyperlinks" {
#create a table which covers all the data. And define a pivot table which uses the same address range.
$table = Add-ExcelTable -PassThru -Range $worksheet.cells[$topRow, 1, $lastDataRow, $columns] -TableName "AllResults" -TableStyle Light4 `
-ShowHeader -ShowFilter -ShowColumnStripes -ShowRowStripes:$false -ShowFirstColumn:$false -ShowLastColumn:$false -ShowTotal:$false #Test Add-ExcelTable outside Export-Excel with as many options as possible.
$pt = New-PivotTableDefinition -PivotTableName Analysis -SourceWorkSheet $worksheet -SourceRange $table.address.address -PivotRows Driver -PivotData @{Points = "SUM"} -PivotTotals None
$pt = New-PivotTableDefinition -PivotTableName Analysis -SourceWorkSheet $worksheet -SourceRange $table.address.address -PivotRows Driver -PivotData @{Points = "SUM" } -PivotTotals None
$cf = Add-ConditionalFormatting -Address $worksheet.cells[$topRow, $columns, $lastDataRow, $columns] -ThreeIconsSet Arrows -Passthru #Test using cells[r1,c1,r2,c2]
$cf.Icon2.Type = $cf.Icon3.Type = "Num"
@@ -44,14 +42,14 @@ Describe "Creating small named ranges with hyperlinks" {
$ct = New-ConditionalText -Text "Ferrari"
$ct2 = New-ConditionalText -Range $worksheet.Names["FinishPosition"].Address -ConditionalType LessThanOrEqual -Text 3 -ConditionalText ([System.Drawing.Color]::Red) -Background ([System.Drawing.Color]::White) #Test New-ConditionalText in shortest and longest forms.
#Create links for each group name (race) and Export them so they start at Cell A1; create a pivot table with definition just created, save the file and open in Excel
$excel = $results | ForEach-Object {(New-Object -TypeName OfficeOpenXml.ExcelHyperLink -ArgumentList "Sheet1!$($_.Name)" , "$($_.name) GP")} | #Test Exporting Hyperlinks with display property.
Export-Excel -ExcelPackage $excel -AutoSize -PivotTableDefinition $pt -Calculate -ConditionalFormat $ct, $ct2 -PassThru #Test conditional text rules in conditional format (orignally icon sets only )
$excel = $results | ForEach-Object { (New-Object -TypeName OfficeOpenXml.ExcelHyperLink -ArgumentList "Sheet1!$($_.Name)" , "$($_.name) GP") } | #Test Exporting Hyperlinks with display property.
Export-Excel -ExcelPackage $excel -AutoSize -PivotTableDefinition $pt -Calculate -ConditionalFormat $ct, $ct2 -PassThru #Test conditional text rules in conditional format (orignally icon sets only )
$null = Add-Worksheet -ExcelPackage $excel -WorksheetName "Points1"
Add-PivotTable -PivotTableName "Points1" -Address $excel.Points1.Cells["A1"] -ExcelPackage $excel -SourceWorkSheet sheet1 -SourceRange $excel.Sheet1.Tables[0].Address.Address -PivotRows Driver, Date -PivotData @{Points = "SUM"} -GroupDateRow Date -GroupDatePart Years, Months
Add-PivotTable -PivotTableName "Points1" -Address $excel.Points1.Cells["A1"] -ExcelPackage $excel -SourceWorkSheet sheet1 -SourceRange $excel.Sheet1.Tables[0].Address.Address -PivotRows Driver, Date -PivotData @{Points = "SUM" } -GroupDateRow Date -GroupDatePart Years, Months
$null = Add-Worksheet -ExcelPackage $excel -WorksheetName "Places1"
$newpt = Add-PivotTable -PivotTableName "Places1" -Address $excel.Places1.Cells["A1"] -ExcelPackage $excel -SourceWorkSheet sheet1 -SourceRange $excel.Sheet1.Tables[0].Address.Address -PivotRows Driver, FinishPosition -PivotData @{Date = "Count"} -GroupNumericRow FinishPosition -GroupNumericMin 1 -GroupNumericMax 25 -GroupNumericInterval 3 -PassThru
$newpt = Add-PivotTable -PivotTableName "Places1" -Address $excel.Places1.Cells["A1"] -ExcelPackage $excel -SourceWorkSheet sheet1 -SourceRange $excel.Sheet1.Tables[0].Address.Address -PivotRows Driver, FinishPosition -PivotData @{Date = "Count" } -GroupNumericRow FinishPosition -GroupNumericMin 1 -GroupNumericMax 25 -GroupNumericInterval 3 -PassThru
$newpt.RowFields[0].SubTotalFunctions = [OfficeOpenXml.Table.PivotTable.eSubTotalFunctions]::None
Close-ExcelPackage -ExcelPackage $excel

View File

@@ -19,7 +19,7 @@ $map = @{
(Get-ExcelColumnName 26).columnName | Should -Be 'Z'
(Get-ExcelColumnName 27).columnName | Should -Be 'AA'
(Get-ExcelColumnName 28).columnNamee | Should -Be 'AB'
(Get-ExcelColumnName 28).columnName | Should -Be 'AB'
(Get-ExcelColumnName 30).columnName | Should -Be 'AD'
(Get-ExcelColumnName 48).columnName | Should -Be 'AV'

View File

@@ -1,9 +1,9 @@
$xlfile = "TestDrive:\testImportExcel.xlsx"
$xlfileHeaderOnly = "TestDrive:\testImportExcelHeaderOnly.xlsx"
Describe "Import-Excel on a sheet with no headings" {
BeforeAll {
$xlfile = "TestDrive:\testImportExcel.xlsx"
$xlfileHeaderOnly = "TestDrive:\testImportExcelHeaderOnly.xlsx"
$xl = "" | Export-excel $xlfile -PassThru
Set-ExcelRange -Worksheet $xl.Sheet1 -Range A1 -Value 'A'
@@ -204,24 +204,24 @@ Describe "Import-Excel on a sheet with no headings" {
}
It "Should handle data correctly if there is only a single row" {
$actual = Import-Excel $xlfileHeaderOnly
$actual = Import-Excel $xlfileHeaderOnly -WarningAction SilentlyContinue
$names = $actual.psobject.properties.Name
$names | should be $null
$actual.Count | should be 0
$names | Should -Be $null
$actual.Count | Should -Be 0
}
It "Should handle data correctly if there is only a single row and using -NoHeader " {
$actual = @(Import-Excel $xlfileHeaderOnly -WorksheetName Sheet1 -NoHeader)
$names = $actual[0].psobject.properties.Name
$names.count | should be 3
$names[0] | should be 'P1'
$names[1] | should be 'P2'
$names[2] | should be 'P3'
$names.count | Should -Be 3
$names[0] | Should -Be 'P1'
$names[1] | Should -Be 'P2'
$names[2] | Should -Be 'P3'
$actual.Count | should be 1
$actual[0].P1 | should be 'A'
$actual[0].P2 | should be 'B'
$actual[0].P3 | should be 'C'
$actual.Count | Should -Be 1
$actual[0].P1 | Should -Be 'A'
$actual[0].P2 | Should -Be 'B'
$actual[0].P3 | Should -Be 'C'
}
}

View File

@@ -1,192 +1,192 @@
[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"
$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')
$null = $DataTable.Columns.Add('Name')
$null = $DataTable.Columns.Add('CPU', [double])
$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)
}
$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" -WarningVariable WVThree -WarningAction SilentlyContinue
# [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"
# $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')
# $null = $DataTable.Columns.Add('Name')
# $null = $DataTable.Columns.Add('CPU', [double])
# $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)
# }
# $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" -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 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 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 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
# 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
}
Context "Array of processes" {
it "Put the correct 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"
$sheet.cells["E1"].Value | Should -Be "StartTime"
$sheet.cells["A3"].Value | Should -Be $results[1].Name
}
it "Created a range for the whole sheet " {
$sheet.Names[0].Name | Should -Be "Whole"
$sheet.Names[0].Start.Address | Should -Be "A1"
$sheet.Names[0].End.row | Should -Be ($results.Count + 1)
$sheet.Names[0].End.Column | Should -Be 5
}
it "Formatted date fields with date type " {
$sheet.Cells["E11"].Style.Numberformat.NumFmtID | Should -Be 22
}
}
$sheet = $excel.Sheet2
Context "Table of processes" {
it "Put the correct 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"
$sheet.cells["E1"].Value | Should -Be "StartTime"
$sheet.cells["A3"].Value | Should -Be $results[1].Name
}
it "Created named ranges for each column " {
$sheet.Names.count | Should -Be 5
$sheet.Names[0].Name | Should -Be "Name"
$sheet.Names[1].Start.Address | Should -Be "B2"
$sheet.Names[2].End.row | Should -Be ($results.Count + 1)
$sheet.Names[3].End.Column | Should -Be 4
$sheet.Names[4].Start.Column | Should -Be 5
}
it "Formatted date fields with date type " {
$sheet.Cells["E11"].Style.Numberformat.NumFmtID | Should -Be 22
}
}
# $excel = Open-ExcelPackage $path
# $sheet = $excel.Sheet1
# }
# Context "Array of processes" {
# it "Put the correct 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"
# $sheet.cells["E1"].Value | Should -Be "StartTime"
# $sheet.cells["A3"].Value | Should -Be $results[1].Name
# }
# it "Created a range for the whole sheet " {
# $sheet.Names[0].Name | Should -Be "Whole"
# $sheet.Names[0].Start.Address | Should -Be "A1"
# $sheet.Names[0].End.row | Should -Be ($results.Count + 1)
# $sheet.Names[0].End.Column | Should -Be 5
# }
# it "Formatted date fields with date type " {
# $sheet.Cells["E11"].Style.Numberformat.NumFmtID | Should -Be 22
# }
# }
# $sheet = $excel.Sheet2
# Context "Table of processes" {
# it "Put the correct 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"
# $sheet.cells["E1"].Value | Should -Be "StartTime"
# $sheet.cells["A3"].Value | Should -Be $results[1].Name
# }
# it "Created named ranges for each column " {
# $sheet.Names.count | Should -Be 5
# $sheet.Names[0].Name | Should -Be "Name"
# $sheet.Names[1].Start.Address | Should -Be "B2"
# $sheet.Names[2].End.row | Should -Be ($results.Count + 1)
# $sheet.Names[3].End.Column | Should -Be 4
# $sheet.Names[4].Start.Column | Should -Be 5
# }
# it "Formatted date fields with date type " {
# $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 " {
$sheet.Dimension.Rows | Should -Be ($results.Count + 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 -Be $results[1].Name
}
it "Created a table " {
$sheet.Tables.count | Should -Be 1
$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" {
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[0] | Should -Match "Zero"
}
it "Applied table formatting " {
$sheet.Tables.Count | Should -Be 1
$sheet.Tables[0].Name | Should -Be "Data"
}
# 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 " {
# $sheet.Dimension.Rows | Should -Be ($results.Count + 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 -Be $results[1].Name
# }
# it "Created a table " {
# $sheet.Tables.count | Should -Be 1
# $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" {
# 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[0] | Should -Match "Zero"
# }
# it "Applied table formatting " {
# $sheet.Tables.Count | Should -Be 1
# $sheet.Tables[0].Name | Should -Be "Data"
# }
}
$Sheet = $excel.Sheet5
Context "Zero-column Data Table handled by Send-SQLDataToExcel -Force" {
it "Created a blank Sheet and raised a warning " {
$sheet.Dimension | Should -BeNullOrEmpty
$wvTwo | Should -Not -BeNullOrEmpty
}
# }
# $Sheet = $excel.Sheet5
# Context "Zero-column Data Table handled by Send-SQLDataToExcel -Force" {
# it "Created a blank Sheet and raised a warning " {
# $sheet.Dimension | Should -BeNullOrEmpty
# $wvTwo | Should -Not -BeNullOrEmpty
# }
}
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
# $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
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"
}
}
# 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,46 +1,47 @@
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')]
#Requires -Modules Pester
[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
12003,Saw,12,15.37,184.44
12010,Drill,20,8,160
12011,Crowbar,7,23.48,164.36
"@
$data2 = ConvertFrom-Csv -InputObject @"
ID,Product,Quantity,Price,Total
12001,Nails,53,3.99,211.47
12002,Hammer,6,12.10,72.60
12003,Saw,10,15.37,153.70
12010,Drill,10,8,80
12012,Pliers,2,14.99,29.98
"@
$data3 = ConvertFrom-Csv -InputObject @"
ID,Product,Quantity,Price,Total
12001,Nails,20,3.99,79.80
12002,Hammer,2,12.10,24.20
12010,Drill,11,8,88
12012,Pliers,3,14.99,44.97
"@
Describe "Join Worksheet part 1" {
BeforeAll {
$data1 = ConvertFrom-Csv -InputObject @"
ID,Product,Quantity,Price,Total
12001,Nails,37,3.99,147.63
12002,Hammer,5,12.10,60.5
12003,Saw,12,15.37,184.44
12010,Drill,20,8,160
12011,Crowbar,7,23.48,164.36
"@
$data2 = ConvertFrom-Csv -InputObject @"
ID,Product,Quantity,Price,Total
12001,Nails,53,3.99,211.47
12002,Hammer,6,12.10,72.60
12003,Saw,10,15.37,153.70
12010,Drill,10,8,80
12012,Pliers,2,14.99,29.98
"@
$data3 = ConvertFrom-Csv -InputObject @"
ID,Product,Quantity,Price,Total
12001,Nails,20,3.99,79.80
12002,Hammer,2,12.10,24.20
12010,Drill,11,8,88
12012,Pliers,3,14.99,44.97
"@
. "$PSScriptRoot\Samples\Samples.ps1"
$path = "TestDrive:\test.xlsx"
Remove-Item -Path $path -ErrorAction SilentlyContinue
$data1 | Export-Excel -Path $path -WorkSheetname Oxford
$data2 | Export-Excel -Path $path -WorkSheetname Abingdon
$data3 | Export-Excel -Path $path -WorkSheetname Banbury
$ptdef = New-PivotTableDefinition -PivotTableName "SummaryPivot" -PivotRows "Store" -PivotColumns "Product" -PivotData @{"Total"="SUM"} -IncludePivotChart -ChartTitle "Sales Breakdown" -ChartType ColumnStacked -ChartColumn 10
Join-Worksheet -Path $path -WorkSheetName "Total" -Clearsheet -FromLabel "Store" -TableName "SummaryTable" -TableStyle Light1 -AutoSize -BoldTopRow -FreezePane 2,1 -Title "Store Sales Summary" -TitleBold -TitleSize 14 -TitleBackgroundColor ([System.Drawing.Color]::AliceBlue) -PivotTableDefinition $ptdef
$ptdef = New-PivotTableDefinition -PivotTableName "SummaryPivot" -PivotRows "Store" -PivotColumns "Product" -PivotData @{"Total" = "SUM" } -IncludePivotChart -ChartTitle "Sales Breakdown" -ChartType ColumnStacked -ChartColumn 10
Join-Worksheet -Path $path -WorkSheetName "Total" -Clearsheet -FromLabel "Store" -TableName "SummaryTable" -TableStyle Light1 -AutoSize -BoldTopRow -FreezePane 2, 1 -Title "Store Sales Summary" -TitleBold -TitleSize 14 -TitleBackgroundColor ([System.Drawing.Color]::AliceBlue) -PivotTableDefinition $ptdef
$excel = Export-Excel -path $path -WorkSheetname SummaryPivot -Activate -NoTotalsInPivot -PivotDataToColumn -HideSheet * -UnHideSheet "Total","SummaryPivot" -PassThru
$excel = Export-Excel -path $path -WorkSheetname SummaryPivot -Activate -NoTotalsInPivot -PivotDataToColumn -HideSheet * -UnHideSheet "Total", "SummaryPivot" -PassThru
# Open-ExcelPackage -Path $path
$ws = $excel.Workbook.Worksheets["Total"]
$pt = $excel.Workbook.Worksheets["SummaryPivot"].pivottables[0]
$pc = $excel.Workbook.Worksheets["SummaryPivot"].Drawings[0]
$ws = $excel.Workbook.Worksheets["Total"]
$pt = $excel.Workbook.Worksheets["SummaryPivot"].pivottables[0]
$pc = $excel.Workbook.Worksheets["SummaryPivot"].Drawings[0]
}
Context "Export-Excel setting spreadsheet visibility" {
it "Hid the worksheets " {
@@ -93,20 +94,31 @@ Describe "Join Worksheet part 1" {
}
}
}
$path = "TestDrive:\Test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue
#switched to CIM objects so test runs on V6
Describe "Join Worksheet part 2" {
Get-CimInstance -ClassName win32_logicaldisk |
Select-Object -Property DeviceId,VolumeName, Size,Freespace |
Export-Excel -Path $path -WorkSheetname Volumes -NumberFormat "0,000"
Get-CimInstance -Namespace root/StandardCimv2 -class MSFT_NetAdapter |
Select-Object -Property Name,InterfaceDescription,MacAddress,LinkSpeed |
Export-Excel -Path $path -WorkSheetname NetAdapters
Join-Worksheet -Path $path -HideSource -WorkSheetName Summary -NoHeader -LabelBlocks -AutoSize -Title "Summary" -TitleBold -TitleSize 22
$excel = Open-ExcelPackage -Path $path
$ws = $excel.Workbook.Worksheets["Summary"]
Describe "Join Worksheet part 2" {
BeforeAll {
if (-not (Get-command Get-CimInstance -ErrorAction SilentlyContinue)) {
Function Get-CimInstance {
param ($classname , $namespace)
Import-Clixml "$PSScriptRoot\$classname.xml"
}
}
}
BeforeEach {
$path = "TestDrive:\Test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue
#switched to CIM objects so test runs on V6+
Get-CimInstance -ClassName win32_logicaldisk |
Select-Object -Property DeviceId, VolumeName, Size, Freespace |
Export-Excel -Path $path -WorkSheetname Volumes -NumberFormat "0,000"
Get-CimInstance -Namespace root/StandardCimv2 -class MSFT_NetAdapter |
Select-Object -Property Name, InterfaceDescription, MacAddress, LinkSpeed |
Export-Excel -Path $path -WorkSheetname NetAdapters
Join-Worksheet -Path $path -HideSource -WorkSheetName Summary -NoHeader -LabelBlocks -AutoSize -Title "Summary" -TitleBold -TitleSize 22
$excel = Open-ExcelPackage -Path $path
$ws = $excel.Workbook.Worksheets["Summary"]
}
Context "Bringing 3 Unlinked blocks onto one page" {
it "Hid the source worksheets " {
$excel.Workbook.Worksheets[1].Hidden.tostring() | Should -Be "Hidden"
@@ -128,4 +140,3 @@ Describe "Join Worksheet part 2" {
}
}
}

File diff suppressed because one or more lines are too long

26460
__tests__/Mockservices.xml Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -14,25 +14,25 @@
$actual.Count | Should -Be 1
}
It "Should read with pwd".PadRight(90){
It "Should read with pwd".PadRight(90) {
$actual = Import-Excel -Path (Join-Path $PWD "$($script:xlfileName)")
$actual | Should -Not -Be $null
}
It "Should read with just a file name and resolve to cwd".PadRight(90){
It "Should read with just a file name and resolve to cwd".PadRight(90) {
$actual = Import-Excel -Path "$($script:xlfileName)"
$actual | Should -Not -Be $null
}
It "Should fail for not found".PadRight(90){
It "Should fail for not found".PadRight(90) {
{ Import-Excel -Path "ExcelFileDoesNotExist.xlsx" } | Should -Throw "'ExcelFileDoesNotExist.xlsx' file not found"
}
It "Should fail for xls extension".PadRight(90){
It "Should fail for xls extension".PadRight(90) {
{ Import-Excel -Path "ExcelFileDoesNotExist.xls" } | Should -Throw "Import-Excel does not support reading this extension type .xls"
}
It "Should fail for xlsxs extension".PadRight(90){
It "Should fail for xlsxs extension".PadRight(90) {
{ Import-Excel -Path "ExcelFileDoesNotExist.xlsxs" } | Should -Throw "Import-Excel does not support reading this extension type .xlsxs"
}
}

View File

@@ -1,11 +1,19 @@
#Requires -Modules Pester
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingCmdletAliases','',Justification='Testing for presence of alias')]
param()
$path = "TestDrive:\test.xlsx"
describe "Consistent passing of ranges." {
BeforeAll {
$path = "TestDrive:\test.xlsx"
if (-not (Get-command Get-Service -ErrorAction SilentlyContinue)) {
Function Get-Service {Import-Clixml $PSScriptRoot\Mockservices.xml}
}
}
Context "Conditional Formatting" {
Remove-Item -path $path -ErrorAction SilentlyContinue
$excel = Get-Service | Export-Excel -Path $path -WorksheetName Services -PassThru -AutoSize -DisplayPropertySet -AutoNameRange -Title "Services on $Env:COMPUTERNAME"
it "accepts named ranges, cells['name'], worksheet + Name, worksheet + column " {
Remove-Item -path $path -ErrorAction SilentlyContinue
$excel = Get-Service | Export-Excel -Path $path -WorksheetName Services -PassThru -AutoSize -DisplayPropertySet -AutoNameRange -Title "Services on $Env:COMPUTERNAME"
{Add-ConditionalFormatting $excel.Services.Names["Status"] -StrikeThru -RuleType ContainsText -ConditionValue "Stopped" } | Should -Not -Throw
$excel.Services.ConditionalFormatting.Count | Should -Be 1
{Add-ConditionalFormatting $excel.Services.Cells["Name"] -Italic -RuleType ContainsText -ConditionValue "SVC" } | Should -Not -Throw
@@ -23,11 +31,12 @@ describe "Consistent passing of ranges." {
{Add-ConditionalFormatting "Status" -Worksheet $excel.Services `
-ForeGroundColor ([System.Drawing.Color]::Green) -RuleType ContainsText -ConditionValue "Running"} | Should -Not -Throw
$excel.Services.ConditionalFormatting.Count | Should -Be 4
Close-ExcelPackage -NoSave $excel
}
Close-ExcelPackage -NoSave $excel
$excel = Get-Service | Export-Excel -Path $path -WorksheetName Services -PassThru -AutoSize -DisplayPropertySet -TableName servicetable -Title "Services on $Env:COMPUTERNAME"
it "accepts table, table.Address and worksheet + 'C:C' " {
{Add-ConditionalFormatting $excel.Services.Tables[0] `
$excel = Get-Service | Export-Excel -Path $path -WorksheetName Services -PassThru -AutoSize -DisplayPropertySet -TableName servicetable -Title "Services on $Env:COMPUTERNAME"
{Add-ConditionalFormatting $excel.Services.Tables[0] `
-Italic -RuleType ContainsText -ConditionValue "Svc" } | Should -Not -Throw
$excel.Services.ConditionalFormatting.Count | Should -Be 1
{Add-ConditionalFormatting $excel.Services.Tables["ServiceTable"].Address `
@@ -36,8 +45,8 @@ describe "Consistent passing of ranges." {
{Add-ConditionalFormatting -Worksheet $excel.Services -Address "a:a" `
-RuleType ContainsText -ConditionValue "stopped" -ForeGroundColor ([System.Drawing.Color]::Red) } | Should -Not -Throw
$excel.Services.ConditionalFormatting.Count | Should -Be 3
Close-ExcelPackage -NoSave $excel
}
Close-ExcelPackage -NoSave $excel
}
Context "Formating (Set-ExcelRange or its alias Set-Format) " {
@@ -54,8 +63,9 @@ describe "Consistent passing of ranges." {
$excel.Services.cells["B3"].Style.Font.Strike | Should -Be $true
{Set-ExcelRange -Worksheet $excel.Services -Range "A5:B6" -FontSize 8 } | Should -Not -Throw
$excel.Services.cells["A5"].Style.Font.Size | Should -Be 8
Close-ExcelPackage -NoSave $excel
}
Close-ExcelPackage -NoSave $excel
it "Accepts Table, Table.Address , worksheet + Name, Column," {
$excel = Get-Service | Export-Excel -Path test2.xlsx -WorksheetName Services -PassThru -AutoNameRange -AutoSize -DisplayPropertySet -TableName servicetable -Title "Services on $Env:COMPUTERNAME"
{Set-ExcelRange $excel.Services.Tables[0] -Italic } | Should -Not -Throw
@@ -66,8 +76,9 @@ describe "Consistent passing of ranges." {
$excel.Services.cells["B4"].Style.Font.Bold | Should -Be $true
{$excel.Services.Column(3) | Set-ExcelRange -FontColor ([System.Drawing.Color]::Red) } | Should -Not -Throw
$excel.Services.cells["C4"].Style.Font.Color.Rgb | Should -Be "FFFF0000"
Close-ExcelPackage -NoSave $excel
}
Close-ExcelPackage -NoSave $excel
}
Context "PivotTables" {
@@ -109,8 +120,5 @@ describe "Consistent passing of ranges." {
$excel.Workbook.Worksheets["pt2"] | Should -Not -BeNullOrEmpty
Close-ExcelPackage -NoSave $excel
}
}
}

View File

@@ -1,31 +1,29 @@
[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 @"
ID,Product,Quantity,Price
12001,Nails,37,3.99
12002,Hammer,5,12.10
12003,Saw,12,15.37
12010,Drill,20,8
12011,Crowbar,7,23.48
"@
$DriverData = convertFrom-CSv @"
Name,Wikipage,DateOfBirth
Fernando Alonso,/wiki/Fernando_Alonso,1981-07-29
Jenson Button,/wiki/Jenson_Button,1980-01-19
Kimi Räikkönen,/wiki/Kimi_R%C3%A4ikk%C3%B6nen,1979-10-17
Lewis Hamilton,/wiki/Lewis_Hamilton,1985-01-07
Nico Rosberg,/wiki/Nico_Rosberg,1985-06-27
Sebastian Vettel,/wiki/Sebastian_Vettel,1987-07-03
"@ | ForEach-Object {$_.DateOfBirth = [datetime]$_.DateofBirth; $_ }

Describe "Number format expansion and setting" {
BeforeAll {
$path = "TestDrive:\test.xlsx"
$data = ConvertFrom-Csv -InputObject @"
ID,Product,Quantity,Price
12001,Nails,37,3.99
12002,Hammer,5,12.10
12003,Saw,12,15.37
12010,Drill,20,8
12011,Crowbar,7,23.48
"@
$DriverData = convertFrom-CSv @"
Name,Wikipage,DateOfBirth
Fernando Alonso,/wiki/Fernando_Alonso,1981-07-29
Jenson Button,/wiki/Jenson_Button,1980-01-19
Kimi Räikkönen,/wiki/Kimi_R%C3%A4ikk%C3%B6nen,1979-10-17
Lewis Hamilton,/wiki/Lewis_Hamilton,1985-01-07
Nico Rosberg,/wiki/Nico_Rosberg,1985-06-27
Sebastian Vettel,/wiki/Sebastian_Vettel,1987-07-03
"@ | ForEach-Object { $_.DateOfBirth = [datetime]$_.DateofBirth; $_ }
}
Context "Expand-NumberFormat function" {
It "Expanded named number formats as expected " {
$r = [regex]::Escape([cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol)
@@ -46,7 +44,7 @@ Describe "Number format expansion and setting" {
Remove-Item -Path $path -ErrorAction SilentlyContinue
$n = [datetime]::Now.ToOADate()
$excel = 1..32 | ForEach-Object {$n} | Export-Excel -Path $path -show -WorksheetName s2 -PassThru
$excel = 1..32 | ForEach-Object { $n } | Export-Excel -Path $path -show -WorksheetName s2 -PassThru
$ws = $excel.Workbook.Worksheets[1]
Set-ExcelRange -Worksheet $ws -Range "A1" -numberFormat 'General'
Set-ExcelRange -Worksheet $ws -Range "A2" -numberFormat 'Number'
@@ -121,14 +119,35 @@ Describe "Number format expansion and setting" {
}
}
Describe "Set-ExcelColumn, Set-ExcelRow and Set-ExcelRange" {
Describe "Set-ExcelColumn, Set-ExcelRow and Set-ExcelRange" {
BeforeAll {
$path = "TestDrive:\test.xlsx"
$data = ConvertFrom-Csv -InputObject @"
ID,Product,Quantity,Price
12001,Nails,37,3.99
12002,Hammer,5,12.10
12003,Saw,12,15.37
12010,Drill,20,8
12011,Crowbar,7,23.48
"@
$DriverData = convertFrom-CSv @"
Name,Wikipage,DateOfBirth
Fernando Alonso,/wiki/Fernando_Alonso,1981-07-29
Jenson Button,/wiki/Jenson_Button,1980-01-19
Kimi Räikkönen,/wiki/Kimi_R%C3%A4ikk%C3%B6nen,1979-10-17
Lewis Hamilton,/wiki/Lewis_Hamilton,1985-01-07
Nico Rosberg,/wiki/Nico_Rosberg,1985-06-27
Sebastian Vettel,/wiki/Sebastian_Vettel,1987-07-03
"@ | ForEach-Object { $_.DateOfBirth = [datetime]$_.DateofBirth; $_ }
Remove-Item -Path $path -ErrorAction SilentlyContinue
$excel = $data| Export-Excel -Path $path -AutoNameRange -PassThru
$excel = $data | Export-Excel -Path $path -AutoNameRange -PassThru
$ws = $excel.Workbook.Worksheets["Sheet1"]
$c = Set-ExcelColumn -PassThru -Worksheet $ws -Heading "Total" -Value "=Quantity*Price" -NumberFormat "£#,###.00" -FontColor ([System.Drawing.Color]::Blue) -Bold -HorizontalAlignment Right -VerticalAlignment Top
$r = Set-ExcelRow -PassThru -Worksheet $ws -StartColumn 3 -BorderAround Thin -Italic -Underline -FontSize 14 -Value {"=sum($columnName`2:$columnName$endrow)" } -VerticalAlignment Bottom
$r = Set-ExcelRow -PassThru -Worksheet $ws -StartColumn 3 -BorderAround Thin -Italic -Underline -FontSize 14 -Value { "=sum($columnName`2:$columnName$endrow)" } -VerticalAlignment Bottom
Set-ExcelRange -Address $excel.Workbook.Worksheets["Sheet1"].Cells["b3"] -HorizontalAlignment Right -VerticalAlignment Center -BorderAround Thick -BorderColor ([System.Drawing.Color]::Red) -StrikeThru
Set-ExcelRange -Address $excel.Workbook.Worksheets["Sheet1"].Cells["c3"] -BorderColor ([System.Drawing.Color]::Red) -BorderTop DashDot -BorderLeft DashDotDot -BorderBottom Dashed -BorderRight Dotted
Set-ExcelRange -Worksheet $ws -Range "E3" -Bold:$false -FontShift Superscript -HorizontalAlignment Left
@@ -229,14 +248,14 @@ Describe "Set-ExcelColumn, Set-ExcelRow and Set-ExcelRange" {
$excel = $DriverData | Export-Excel -PassThru -Path $path -AutoSize -AutoNameRange
$ws = $excel.Workbook.Worksheets[1]
Set-ExcelColumn -Worksheet $ws -Heading "Link" -AutoSize -Value {"https://en.wikipedia.org" + $worksheet.Cells["B$Row"].value }
Set-ExcelColumn -Worksheet $ws -Heading "Link" -AutoSize -Value { "https://en.wikipedia.org" + $worksheet.Cells["B$Row"].value }
$c = Set-ExcelColumn -PassThru -Worksheet $ws -Heading "NextBirthday" -Value {
$bmonth = $worksheet.Cells["C$Row"].value.month ; $bDay = $worksheet.Cells["C$Row"].value.day
$cMonth = [datetime]::Now.Month ; $cday = [datetime]::Now.day ; $cyear = [datetime]::Now.Year
if (($cmonth -gt $bmonth) -or (($cMonth -eq $bmonth) -and ($cday -ge $bDay))) {
[datetime]::new($cyear + 1, $bmonth, $bDay)
}
else {[datetime]::new($cyear, $bmonth, $bday) }
else { [datetime]::new($cyear, $bmonth, $bday) }
}
Set-ExcelColumn -Worksheet $ws -Heading "Age" -Value "=INT((NOW()-DateOfBirth)/365)"
# Test Piping column Numbers into Set excelColumn
@@ -277,7 +296,7 @@ Describe "Set-ExcelColumn, Set-ExcelRow and Set-ExcelRange" {
Describe "Conditional Formatting" {
BeforeAll {
#Remove-Item $path
$path = "TestDrive:\test.xlsx"
$data = Get-Process | Where-Object company | Select-Object company, name, pm, handles, *mem*
$cfmt = New-ConditionalFormattingIconSet -Range "c:c" -ConditionalFormat ThreeIconSet -IconType Arrows
$data | Export-Excel -path $Path -AutoSize -ConditionalFormat $cfmt
@@ -293,33 +312,33 @@ Describe "Conditional Formatting" {
}
}
$path = "TestDrive:\test.xlsx"
$data2 = ConvertFrom-Csv -InputObject @"
ID,Product,Quantity,Price,Total
12001,Nails,37,3.99,147.63
12002,Hammer,5,12.10,60.5
12003,Saw,12,15.37,184.44
12010,Drill,20,8,160
12011,Crowbar,7,23.48,164.36
12001,Nails,53,3.99,211.47
12002,Hammer,6,12.10,72.60
12003,Saw,10,15.37,153.70
12010,Drill,10,8,80
12012,Pliers,2,14.99,29.98
12001,Nails,20,3.99,79.80
12002,Hammer,2,12.10,24.20
12010,Drill,11,8,88
12012,Pliers,3,14.99,44.97
"@
Describe "AutoNameRange data with a single property name" {
BeforeEach {
$path = "TestDrive:\test.xlsx"
$data2 = ConvertFrom-Csv -InputObject @"
ID,Product,Quantity,Price,Total
12001,Nails,37,3.99,147.63
12002,Hammer,5,12.10,60.5
12003,Saw,12,15.37,184.44
12010,Drill,20,8,160
12011,Crowbar,7,23.48,164.36
12001,Nails,53,3.99,211.47
12002,Hammer,6,12.10,72.60
12003,Saw,10,15.37,153.70
12010,Drill,10,8,80
12012,Pliers,2,14.99,29.98
12001,Nails,20,3.99,79.80
12002,Hammer,2,12.10,24.20
12010,Drill,11,8,88
12012,Pliers,3,14.99,44.97
"@
$xlfile = "TestDrive:\testNamedRange.xlsx"
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
@@ -327,14 +346,14 @@ Sold
4
"@ | 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
@@ -342,17 +361,34 @@ Sold,ID
4,d
"@ | 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" {
Describe "Table Formatting" {
BeforeAll {
#Remove-Item $path
$path = "TestDrive:\test.xlsx"
$data2 = ConvertFrom-Csv -InputObject @"
ID,Product,Quantity,Price,Total
12001,Nails,37,3.99,147.63
12002,Hammer,5,12.10,60.5
12003,Saw,12,15.37,184.44
12010,Drill,20,8,160
12011,Crowbar,7,23.48,164.36
12001,Nails,53,3.99,211.47
12002,Hammer,6,12.10,72.60
12003,Saw,10,15.37,153.70
12010,Drill,10,8,80
12012,Pliers,2,14.99,29.98
12001,Nails,20,3.99,79.80
12002,Hammer,2,12.10,24.20
12010,Drill,11,8,88
12012,Pliers,3,14.99,44.97
"@
$excel = $data2 | Export-excel -path $path -WorksheetName Hardware -AutoNameRange -AutoSize -BoldTopRow -FreezeTopRow -PassThru
$ws = $excel.Workbook.Worksheets[1]
#test showfilter & TotalSettings

View File

@@ -1,31 +1,27 @@
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')]
param()
$data = ConvertFrom-Csv -InputObject @"
ID,Product,Quantity,Price
12001,Nails,37,3.99
12002,Hammer,5,12.10
12003,Saw,12,15.37
12010,Drill,20,8
12011,Crowbar,7,23.48
"@
$path = "TestDrive:\DataValidation.xlsx"
Describe "Data validation and protection" {
Context "Data Validation rules" {
BeforeAll {
$data = ConvertFrom-Csv -InputObject @"
ID,Product,Quantity,Price
12001,Nails,37,3.99
12002,Hammer,5,12.10
12003,Saw,12,15.37
12010,Drill,20,8
12011,Crowbar,7,23.48
"@
$path = "TestDrive:\DataValidation.xlsx"
Remove-Item $path -ErrorAction SilentlyContinue
$excelPackage = $Data | Export-excel -WorksheetName "Sales" -path $path -PassThru
$excelPackage = @('Chisel','Crowbar','Drill','Hammer','Nails','Saw','Screwdriver','Wrench') |
Export-excel -ExcelPackage $excelPackage -WorksheetName Values -PassThru
$excelPackage = $Data | Export-excel -WorksheetName "Sales" -path $path -PassThru
$excelPackage = @('Chisel', 'Crowbar', 'Drill', 'Hammer', 'Nails', 'Saw', 'Screwdriver', 'Wrench') |
Export-excel -ExcelPackage $excelPackage -WorksheetName Values -PassThru
$VParams = @{Worksheet = $excelPackage.sales; ShowErrorMessage=$true; ErrorStyle='stop'; ErrorTitle='Invalid Data' }
$VParams = @{Worksheet = $excelPackage.sales; ShowErrorMessage = $true; ErrorStyle = 'stop'; ErrorTitle = 'Invalid Data' }
Add-ExcelDataValidationRule @VParams -Range 'B2:B1001' -ValidationType List -Formula 'values!$a$1:$a$10' -ErrorBody "You must select an item from the list.`r`nYou can add to the list on the values page" #Bucket
Add-ExcelDataValidationRule @VParams -Range 'E2:E1001' -ValidationType Integer -Operator between -Value 0 -Value2 10000 -ErrorBody 'Quantity must be a whole number between 0 and 10000'
Close-ExcelPackage -ExcelPackage $excelPackage
$excelPackage = Open-ExcelPackage -Path $path
$ws = $excelPackage.Sales
$ws = $excelPackage.Sales
}
It "Created the expected number of rules " {
$ws.DataValidations.count | Should -Be 2

File diff suppressed because one or more lines are too long

View File

@@ -20,7 +20,7 @@ jobs:
vmImage: 'windows-latest'
steps:
- powershell: 'Install-Module -Name Pester -Force -SkipPublisherCheck -MaximumVersion 4.99.99'
- powershell: 'Install-Module -Name Pester -Force -SkipPublisherCheck'
displayName: 'Update Pester'
- powershell: './CI/CI.ps1 -Test'
displayName: 'Install and Test'
@@ -49,7 +49,7 @@ jobs:
vmImage: 'windows-latest'
steps:
- pwsh: 'Install-Module -Name Pester -Force -MaximumVersion 4.99.99'
- pwsh: 'Install-Module -Name Pester -Force'
displayName: 'Update Pester'
- pwsh: './CI/CI.ps1 -Test'
displayName: 'Install and Test'
@@ -65,7 +65,7 @@ jobs:
vmImage: 'ubuntu-latest'
steps:
- powershell: 'Install-Module -Name Pester -Force -MaximumVersion 4.99.99'
- powershell: 'Install-Module -Name Pester -Force'
displayName: 'Update Pester'
- powershell: './CI/CI.ps1 -Test'
displayName: 'Install and Test'
@@ -83,7 +83,7 @@ jobs:
steps:
- script: brew install mono-libgdiplus
displayName: 'Install mono-libgdiplus'
- powershell: 'Install-Module -Name Pester -Force -MaximumVersion 4.99.99'
- powershell: 'Install-Module -Name Pester -Force'
displayName: 'Update Pester'
- powershell: './CI/CI.ps1 -Test'
displayName: 'Install and Test'
@@ -99,7 +99,7 @@ jobs:
vmImage: 'macOS-latest'
steps:
- powershell: 'Install-Module -Name Pester -Force -MaximumVersion 4.99.99'
- powershell: 'Install-Module -Name Pester -Force'
displayName: 'Update Pester'
- powershell: './CI/CI.ps1 -TestImportOnly'
displayName: 'Install and Test Import Only'