First pass. All code must be in a script block

This commit is contained in:
dfinke
2020-10-31 17:47:07 -04:00
parent 113bf2c95c
commit 6149442bc0
12 changed files with 911 additions and 839 deletions

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' { Describe 'ConvertFrom-ExcelSheet / Export-ExcelSheet' {
BeforeAll { BeforeAll {
$scriptPath = $PSScriptRoot
$dataPath = Join-Path -Path $scriptPath -ChildPath "First10Races.xlsx"
$Outpath = "TestDrive:\"
ConvertFrom-ExcelSheet -Path $dataPath -OutputPath $Outpath ConvertFrom-ExcelSheet -Path $dataPath -OutputPath $Outpath
$firstText = 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 ConvertFrom-ExcelSheet -Path $dataPath -OutputPath $Outpath -AsText GridPosition, date
$SecondText = Get-Content (Join-path -Path $Outpath -ChildPath "First10Races.csv") $script:SecondText = Get-Content (Join-path -Path $Outpath -ChildPath "First10Races.csv")
ConvertFrom-ExcelSheet -Path $dataPath -OutputPath $Outpath -AsText "GridPosition" -Property driver, ConvertFrom-ExcelSheet -Path $dataPath -OutputPath $Outpath -AsText "GridPosition" -Property driver,
@{n="date"; e={[datetime]::FromOADate($_.Date).tostring("#MM/dd/yyyy#")}} , FinishPosition, GridPosition @{n = "date"; e = { [datetime]::FromOADate($_.Date).tostring("#MM/dd/yyyy#") } } , FinishPosition, GridPosition
$ThirdText = Get-Content (Join-path -Path $Outpath -ChildPath "First10Races.csv") $script:ThirdText = Get-Content (Join-path -Path $Outpath -ChildPath "First10Races.csv")
ConvertFrom-ExcelSheet -Path $dataPath -OutputPath $Outpath -AsDate "date" 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" { Context "Exporting to CSV" {
it "Exported the expected columns to a CSV file " { 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 " { 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}"$' $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") $date = [datetime]::FromOADate($date).toString("D")
$secondText[1] | Should -Belike "*$date*" $secondText[1] | Should -Belike "*$date*"
$secondText[1] | Should -Match '"0\d","\w+","\d{1,2}"$' $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]/)' $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 " { it "Definded the alias name with " {
(Get-Alias Export-ExcelSheet).source | Should -Be "ImportExcel" (Get-Alias Export-ExcelSheet).source | Should -Be "ImportExcel"
(Get-Alias Export-ExcelSheet).Definition | Should -Be "ConvertFrom-ExcelSheet" (Get-Alias Export-ExcelSheet).Definition | Should -Be "ConvertFrom-ExcelSheet"

View File

@@ -1,32 +1,34 @@
if (-not (Get-command Import-Excel -ErrorAction SilentlyContinue)) { if (-not (Get-command Import-Excel -ErrorAction SilentlyContinue)) {
Import-Module $PSScriptRoot\..\ImportExcel.psd1 Import-Module $PSScriptRoot\..\ImportExcel.psd1
} }
$xlFile = "TestDrive:\testSQL.xlsx"
Describe "ConvertFrom-ExcelToSQLInsert" { Describe "ConvertFrom-ExcelToSQLInsert" {
BeforeAll {
$script:xlFile = "TestDrive:\testSQL.xlsx"
}
BeforeEach { BeforeEach {
$([PSCustomObject]@{ $([PSCustomObject]@{
Name="John" Name = "John"
Age=$null Age = $null
}) | Export-Excel $xlFile }) | Export-Excel $xlFile
} }
AfterAll { AfterAll {
Remove-Item $xlFile -Recurse -Force -ErrorAction Ignore Remove-Item $xlFile -Recurse -Force -ErrorAction Ignore
} }
It "Should be empty double single quotes".PadRight(90) { It "Should be empty double single quotes".PadRight(90) {
$expected="INSERT INTO Sheet1 ('Name', 'Age') Values('John', '');" $expected = "INSERT INTO Sheet1 ('Name', 'Age') Values('John', '');"
$actual = ConvertFrom-ExcelToSQLInsert -Path $xlFile Sheet1 $actual = ConvertFrom-ExcelToSQLInsert -Path $xlFile Sheet1
$actual | Should -Be $expected $actual | Should -Be $expected
} }
It "Should have NULL".PadRight(90) { It "Should have NULL".PadRight(90) {
$expected="INSERT INTO Sheet1 ('Name', 'Age') Values('John', NULL);" $expected = "INSERT INTO Sheet1 ('Name', 'Age') Values('John', NULL);"
$actual = ConvertFrom-ExcelToSQLInsert -Path $xlFile Sheet1 -ConvertEmptyStringsToNull $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() param()
Describe "Copy-Worksheet" { Describe "Copy-Worksheet" {
$path1 = "TestDrive:\Test1.xlsx" BeforeAll {
$path2 = "TestDrive:\Test2.xlsx" $path1 = "TestDrive:\Test1.xlsx"
Remove-Item -Path $path1, $path2 -ErrorAction SilentlyContinue $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 = "$" } if ((Get-Culture).NumberFormat.CurrencySymbol -eq "£") { $OtherCurrencySymbol = "$" }
else { $OtherCurrencySymbol = "£" } else { $OtherCurrencySymbol = "£" }
[PSCustOmobject][Ordered]@{ [PSCustOmobject][Ordered]@{
Date = Get-Date Date = Get-Date
Formula1 = '=SUM(F2:G2)' Formula1 = '=SUM(F2:G2)'
String1 = 'My String' String1 = 'My String'
Float = [math]::pi Float = [math]::pi
IPAddress = '10.10.25.5' IPAddress = '10.10.25.5'
StrLeadZero = '07670' StrLeadZero = '07670'
StrComma = '0,26' StrComma = '0,26'
StrEngThousand = '1,234.56' StrEngThousand = '1,234.56'
StrEuroThousand = '1.555,83' StrEuroThousand = '1.555,83'
StrDot = '1.2' StrDot = '1.2'
StrNegInt = '-31' StrNegInt = '-31'
StrTrailingNeg = '31-' StrTrailingNeg = '31-'
StrParens = '(123)' StrParens = '(123)'
strLocalCurrency = ('{0}123.45' -f (Get-Culture).NumberFormat.CurrencySymbol ) strLocalCurrency = ('{0}123.45' -f (Get-Culture).NumberFormat.CurrencySymbol )
strOtherCurrency = ('{0}123.45' -f $OtherCurrencySymbol ) strOtherCurrency = ('{0}123.45' -f $OtherCurrencySymbol )
StrE164Phone = '+32 (444) 444 4444' StrE164Phone = '+32 (444) 444 4444'
StrAltPhone1 = '+32 4 4444 444' StrAltPhone1 = '+32 4 4444 444'
StrAltPhone2 = '+3244444444' StrAltPhone2 = '+3244444444'
StrLeadSpace = ' 123' StrLeadSpace = ' 123'
StrTrailSpace = '123 ' StrTrailSpace = '123 '
Link1 = [uri]"https://github.com/dfinke/ImportExcel" 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 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 } | Export-Excel -NoNumberConversion IPAddress, StrLeadZero, StrAltPhone2 -WorkSheetname MixedTypes -Path $path2
}
Context "Simplest copy" { Context "Simplest copy" {
BeforeAll { BeforeAll {
$path1 = "TestDrive:\Test1.xlsx"
$path2 = "TestDrive:\Test2.xlsx"
Copy-ExcelWorksheet -SourceWorkbook $path1 -DestinationWorkbook $path2 Copy-ExcelWorksheet -SourceWorkbook $path1 -DestinationWorkbook $path2
$excel = Open-ExcelPackage -Path $path2 $excel = Open-ExcelPackage -Path $path2
$ws = $excel.Workbook.Worksheets["Processes"] $ws = $excel.Workbook.Worksheets["Processes"]
@@ -46,7 +51,7 @@ Describe "Copy-Worksheet" {
$ws.Dimension.Address | Should -Be $ProcRange $ws.Dimension.Address | Should -Be $ProcRange
} }
} }
Context "Mixed types using a package object" { Context "Mixed types using a package object" -Skip {
BeforeAll { BeforeAll {
Copy-ExcelWorksheet -SourceWorkbook $excel -DestinationWorkbook $excel -DestinationWorkSheet "CopyOfMixedTypes" Copy-ExcelWorksheet -SourceWorkbook $excel -DestinationWorkbook $excel -DestinationWorkSheet "CopyOfMixedTypes"
Close-ExcelPackage -ExcelPackage $excel Close-ExcelPackage -ExcelPackage $excel
@@ -66,26 +71,26 @@ Describe "Copy-Worksheet" {
$ws.Cells[2, 5].Value.GetType().name | Should -Be 'String' $ws.Cells[2, 5].Value.GetType().name | Should -Be 'String'
$ws.Cells[2, 6].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, 18].Value.GetType().name | Should -Be 'String'
($ws.Cells[2, 11].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, 12].Value -is [valuetype] ) | Should -Be $true
($ws.Cells[2, 13].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, 11].Value | Should -BeLessThan 0
$ws.Cells[2, 12].Value | Should -BeLessThan 0 $ws.Cells[2, 12].Value | Should -BeLessThan 0
$ws.Cells[2, 13].Value | Should -BeLessThan 0 $ws.Cells[2, 13].Value | Should -BeLessThan 0
if ((Get-Culture).NumberFormat.NumberGroupSeparator -EQ ",") { 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' $ws.Cells[2, 9].Value.GetType().name | Should -Be 'String'
} }
elseif ((Get-Culture).NumberFormat.NumberGroupSeparator -EQ ".") { 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, 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, 15].Value.GetType().name | Should -Be 'String'
$ws.Cells[2, 16].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, 17].Value.GetType().name | Should -Be 'String'
($ws.Cells[2, 19].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 ($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" { Describe "Creating workbook with a single line" {
$path = "TestDrive:\test.xlsx" BeforeAll {
remove-item -path $path -ErrorAction SilentlyContinue $path = "TestDrive:\test.xlsx"
ConvertFrom-Csv @" remove-item -path $path -ErrorAction SilentlyContinue
ConvertFrom-Csv @"
Product, City, Gross, Net Product, City, Gross, Net
Apple, London , 300, 250 Apple, London , 300, 250
Orange, London , 400, 350 Orange, London , 400, 350
@@ -12,14 +13,17 @@ Orange, Paris, 600, 500
Banana, Paris, 300, 200 Banana, Paris, 300, 200
Apple, New York, 1200,700 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=@{ "@ | 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 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 $excel = Open-ExcelPackage $path
$ws1 = $excel.Workbook.Worksheets[1] $ws1 = $excel.Workbook.Worksheets[1]
$ws2 = $excel.Workbook.Worksheets[2] $ws2 = $excel.Workbook.Worksheets[2]
}
Context "Data Page" { Context "Data Page" {
It "Inserted the data and created the table " { It "Inserted the data and created the table " {
$ws1.Tables[0] | Should -Not -BeNullOrEmpty $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" $ws1.Drawings[0].Series[0].Series | Should -Be "'Sheet1'!C2:C7"
} }
} }
Context "PivotTable" { Context "PivotTable" {
it "Created the PivotTable on a new page " { it "Created the PivotTable on a new page " {
$ws2 | Should -Not -BeNullOrEmpty $ws2 | Should -Not -BeNullOrEmpty
$ws2.PivotTables[0] | 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" { Describe "Creating small named ranges with hyperlinks" {
BeforeAll { BeforeAll {
$scriptPath = $PSScriptRoot
$dataPath = Join-Path -Path $scriptPath -ChildPath "First10Races.csv"
$WarningAction = "SilentlyContinue"
$path = "TestDrive:\Results.xlsx" $path = "TestDrive:\Results.xlsx"
Remove-Item -Path $path -ErrorAction SilentlyContinue 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 #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 | $results = Import-Csv -Path $dataPath |
Select-Object Race, @{n = "Date"; e = {[datetime]::ParseExact($_.date, "dd/MM/yyyy", (Get-Culture))}}, FinishPosition, Driver, GridPosition, Team, Points | Select-Object Race, @{n = "Date"; e = { [datetime]::ParseExact($_.date, "dd/MM/yyyy", (Get-Culture)) } }, FinishPosition, Driver, GridPosition, Team, Points |
Group-Object -Property RACE Group-Object -Property RACE
$topRow = $lastDataRow = 1 + $results.Count $topRow = $lastDataRow = 1 + $results.Count
$excel = $results[0].Group[0] | Export-Excel -Path $path -StartRow $TopRow -BoldTopRow -PassThru $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] $worksheet = $excel.Workbook.Worksheets[1]
$columns = $worksheet.Dimension.Columns $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 $scwarnVar = $null
Set-ExcelColumn -Worksheet $worksheet -StartRow $topRow -Heading "PlacesGained/Lost" ` 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. #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 ` $table = Add-ExcelTable -PassThru -Range $worksheet.cells[$topRow, 1, $lastDataRow, $columns] -TableName "AllResults" -TableStyle Light4 `
-ShowHeader -ShowFilter -ShowColumnStripes -ShowRowStripes:$false -ShowFirstColumn:$false -ShowLastColumn:$false -ShowTotal:$false #Test Add-ExcelTable outside Export-Excel with as many options as possible. -ShowHeader -ShowFilter -ShowColumnStripes -ShowRowStripes:$false -ShowFirstColumn:$false -ShowLastColumn:$false -ShowTotal:$false #Test Add-ExcelTable outside Export-Excel with as many options as possible.
$pt = New-PivotTableDefinition -PivotTableName Analysis -SourceWorkSheet $worksheet -SourceRange $table.address.address -PivotRows Driver -PivotData @{Points = "SUM"} -PivotTotals None $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 = 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" $cf.Icon2.Type = $cf.Icon3.Type = "Num"
@@ -44,14 +42,14 @@ Describe "Creating small named ranges with hyperlinks" {
$ct = New-ConditionalText -Text "Ferrari" $ct = New-ConditionalText -Text "Ferrari"
$ct2 = New-ConditionalText -Range $worksheet.Names["FinishPosition"].Address -ConditionalType LessThanOrEqual -Text 3 -ConditionalText ([System.Drawing.Color]::Red) -Background ([System.Drawing.Color]::White) #Test New-ConditionalText in shortest and longest forms. $ct2 = New-ConditionalText -Range $worksheet.Names["FinishPosition"].Address -ConditionalType LessThanOrEqual -Text 3 -ConditionalText ([System.Drawing.Color]::Red) -Background ([System.Drawing.Color]::White) #Test New-ConditionalText in shortest and longest forms.
#Create links for each group name (race) and Export them so they start at Cell A1; create a pivot table with definition just created, save the file and open in Excel #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. $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 ) Export-Excel -ExcelPackage $excel -AutoSize -PivotTableDefinition $pt -Calculate -ConditionalFormat $ct, $ct2 -PassThru #Test conditional text rules in conditional format (orignally icon sets only )
$null = Add-Worksheet -ExcelPackage $excel -WorksheetName "Points1" $null = Add-Worksheet -ExcelPackage $excel -WorksheetName "Points1"
Add-PivotTable -PivotTableName "Points1" -Address $excel.Points1.Cells["A1"] -ExcelPackage $excel -SourceWorkSheet sheet1 -SourceRange $excel.Sheet1.Tables[0].Address.Address -PivotRows Driver, Date -PivotData @{Points = "SUM"} -GroupDateRow Date -GroupDatePart Years, Months Add-PivotTable -PivotTableName "Points1" -Address $excel.Points1.Cells["A1"] -ExcelPackage $excel -SourceWorkSheet sheet1 -SourceRange $excel.Sheet1.Tables[0].Address.Address -PivotRows Driver, Date -PivotData @{Points = "SUM" } -GroupDateRow Date -GroupDatePart Years, Months
$null = Add-Worksheet -ExcelPackage $excel -WorksheetName "Places1" $null = Add-Worksheet -ExcelPackage $excel -WorksheetName "Places1"
$newpt = Add-PivotTable -PivotTableName "Places1" -Address $excel.Places1.Cells["A1"] -ExcelPackage $excel -SourceWorkSheet sheet1 -SourceRange $excel.Sheet1.Tables[0].Address.Address -PivotRows Driver, FinishPosition -PivotData @{Date = "Count"} -GroupNumericRow FinishPosition -GroupNumericMin 1 -GroupNumericMax 25 -GroupNumericInterval 3 -PassThru $newpt = 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 $newpt.RowFields[0].SubTotalFunctions = [OfficeOpenXml.Table.PivotTable.eSubTotalFunctions]::None
Close-ExcelPackage -ExcelPackage $excel Close-ExcelPackage -ExcelPackage $excel

View File

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

View File

@@ -1,192 +1,192 @@
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')] # [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')]
Param() # Param()
Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking Import -asText" { # Describe "Exporting with -Inputobject, table handling, Send-SQL-Data. Checking Import -asText" {
BeforeAll { # BeforeAll {
$path = "TestDrive:\Results.xlsx" # $path = "TestDrive:\Results.xlsx"
$path2 = "TestDrive:\Results2.xlsx" # $path2 = "TestDrive:\Results2.xlsx"
Remove-Item -Path $path,$path2 -ErrorAction SilentlyContinue # Remove-Item -Path $path,$path2 -ErrorAction SilentlyContinue
if (Test-path "$PSScriptRoot\Samples\Samples.ps1") {. "$PSScriptRoot\Samples\Samples.ps1"} # if (Test-path "$PSScriptRoot\Samples\Samples.ps1") {. "$PSScriptRoot\Samples\Samples.ps1"}
$results = ((Get-Process) + (Get-Process -id $PID)) | Select-Object -last 10 -Property Name, cpu, pm, handles, StartTime # $results = ((Get-Process) + (Get-Process -id $PID)) | Select-Object -last 10 -Property Name, cpu, pm, handles, StartTime
$DataTable = [System.Data.DataTable]::new('Test') # $DataTable = [System.Data.DataTable]::new('Test')
$null = $DataTable.Columns.Add('Name') # $null = $DataTable.Columns.Add('Name')
$null = $DataTable.Columns.Add('CPU', [double]) # $null = $DataTable.Columns.Add('CPU', [double])
$null = $DataTable.Columns.Add('PM', [Long]) # $null = $DataTable.Columns.Add('PM', [Long])
$null = $DataTable.Columns.Add('Handles', [Int]) # $null = $DataTable.Columns.Add('Handles', [Int])
$null = $DataTable.Columns.Add('StartTime', [DateTime]) # $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 $DataTable -WorkSheetname Sheet4 -force -TableName "Data" -WarningVariable WVOne -WarningAction SilentlyContinue
Send-SQLDataToExcel -path $path -DataTable ([System.Data.DataTable]::new('Test2')) -WorkSheetname Sheet5 -force -WarningVariable wvTwo -WarningAction SilentlyContinue # Send-SQLDataToExcel -path $path -DataTable ([System.Data.DataTable]::new('Test2')) -WorkSheetname Sheet5 -force -WarningVariable wvTwo -WarningAction SilentlyContinue
foreach ($r in $results) { # foreach ($r in $results) {
$null = $DataTable.Rows.Add($r.name, $r.CPU, $R.PM, $r.Handles, $r.StartTime) # $null = $DataTable.Rows.Add($r.name, $r.CPU, $R.PM, $r.Handles, $r.StartTime)
} # }
$NowPkg = Export-Excel -InputObject $DataTable -PassThru # $NowPkg = Export-Excel -InputObject $DataTable -PassThru
$NowPath1 = $NowPkg.File.FullName # $NowPath1 = $NowPkg.File.FullName
Close-ExcelPackage $NowPkg # Close-ExcelPackage $NowPkg
$NowPkg = Export-Excel -InputObject $DataTable -PassThru -table:$false # $NowPkg = Export-Excel -InputObject $DataTable -PassThru -table:$false
$NowPath2 = $NowPkg.File.FullName # $NowPath2 = $NowPkg.File.FullName
Close-ExcelPackage $NowPkg # Close-ExcelPackage $NowPkg
Export-Excel -Path $path -InputObject $results -WorksheetName Sheet1 -RangeName "Whole" # Export-Excel -Path $path -InputObject $results -WorksheetName Sheet1 -RangeName "Whole"
Export-Excel -Path $path -InputObject $DataTable -WorksheetName Sheet2 -AutoNameRange # 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 $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 -TableName "FirstLot" -TableStyle light7
Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet2 -Append # 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
Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet3 -Append -TableName "SecondLot" # 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
Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet4 -Append -TableStyle Dark5 # Send-SQLDataToExcel -Path $path2 -DataTable $DataTable -WorksheetName Sheet4 -Append -TableStyle Dark5
$excel = Open-ExcelPackage $path # $excel = Open-ExcelPackage $path
$sheet = $excel.Sheet1 # $sheet = $excel.Sheet1
} # }
Context "Array of processes" { # Context "Array of processes" {
it "Put the correct rows and columns into the sheet " { # it "Put the correct rows and columns into the sheet " {
$sheet.Dimension.Rows | Should -Be ($results.Count + 1) # $sheet.Dimension.Rows | Should -Be ($results.Count + 1)
$sheet.Dimension.Columns | Should -Be 5 # $sheet.Dimension.Columns | Should -Be 5
$sheet.cells["A1"].Value | Should -Be "Name" # $sheet.cells["A1"].Value | Should -Be "Name"
$sheet.cells["E1"].Value | Should -Be "StartTime" # $sheet.cells["E1"].Value | Should -Be "StartTime"
$sheet.cells["A3"].Value | Should -Be $results[1].Name # $sheet.cells["A3"].Value | Should -Be $results[1].Name
} # }
it "Created a range for the whole sheet " { # it "Created a range for the whole sheet " {
$sheet.Names[0].Name | Should -Be "Whole" # $sheet.Names[0].Name | Should -Be "Whole"
$sheet.Names[0].Start.Address | Should -Be "A1" # $sheet.Names[0].Start.Address | Should -Be "A1"
$sheet.Names[0].End.row | Should -Be ($results.Count + 1) # $sheet.Names[0].End.row | Should -Be ($results.Count + 1)
$sheet.Names[0].End.Column | Should -Be 5 # $sheet.Names[0].End.Column | Should -Be 5
} # }
it "Formatted date fields with date type " { # it "Formatted date fields with date type " {
$sheet.Cells["E11"].Style.Numberformat.NumFmtID | Should -Be 22 # $sheet.Cells["E11"].Style.Numberformat.NumFmtID | Should -Be 22
} # }
} # }
$sheet = $excel.Sheet2 # $sheet = $excel.Sheet2
Context "Table of processes" { # Context "Table of processes" {
it "Put the correct rows and columns into the sheet " { # it "Put the correct rows and columns into the sheet " {
$sheet.Dimension.Rows | Should -Be ($results.Count + 1) # $sheet.Dimension.Rows | Should -Be ($results.Count + 1)
$sheet.Dimension.Columns | Should -Be 5 # $sheet.Dimension.Columns | Should -Be 5
$sheet.cells["A1"].Value | Should -Be "Name" # $sheet.cells["A1"].Value | Should -Be "Name"
$sheet.cells["E1"].Value | Should -Be "StartTime" # $sheet.cells["E1"].Value | Should -Be "StartTime"
$sheet.cells["A3"].Value | Should -Be $results[1].Name # $sheet.cells["A3"].Value | Should -Be $results[1].Name
} # }
it "Created named ranges for each column " { # it "Created named ranges for each column " {
$sheet.Names.count | Should -Be 5 # $sheet.Names.count | Should -Be 5
$sheet.Names[0].Name | Should -Be "Name" # $sheet.Names[0].Name | Should -Be "Name"
$sheet.Names[1].Start.Address | Should -Be "B2" # $sheet.Names[1].Start.Address | Should -Be "B2"
$sheet.Names[2].End.row | Should -Be ($results.Count + 1) # $sheet.Names[2].End.row | Should -Be ($results.Count + 1)
$sheet.Names[3].End.Column | Should -Be 4 # $sheet.Names[3].End.Column | Should -Be 4
$sheet.Names[4].Start.Column | Should -Be 5 # $sheet.Names[4].Start.Column | Should -Be 5
} # }
it "Formatted date fields with date type " { # it "Formatted date fields with date type " {
$sheet.Cells["E11"].Style.Numberformat.NumFmtID | Should -Be 22 # $sheet.Cells["E11"].Style.Numberformat.NumFmtID | Should -Be 22
} # }
} # }
Context "'Now' Mode behavior" { # Context "'Now' Mode behavior" {
$NowPkg = Open-ExcelPackage $NowPath1 # $NowPkg = Open-ExcelPackage $NowPath1
$sheet = $NowPkg.Sheet1 # $sheet = $NowPkg.Sheet1
it "Formatted data as a table by default " { # it "Formatted data as a table by default " {
$sheet.Tables.Count | Should -Be 1 # $sheet.Tables.Count | Should -Be 1
} # }
Close-ExcelPackage -NoSave $NowPkg # Close-ExcelPackage -NoSave $NowPkg
Remove-Item $NowPath1 # Remove-Item $NowPath1
$NowPkg = Open-ExcelPackage $NowPath2 # $NowPkg = Open-ExcelPackage $NowPath2
$sheet = $NowPkg.Sheet1 # $sheet = $NowPkg.Sheet1
it "Did not data as a table when table:`$false was used " { # it "Did not data as a table when table:`$false was used " {
$sheet.Tables.Count | Should -Be 0 # $sheet.Tables.Count | Should -Be 0
} # }
Close-ExcelPackage -NoSave $NowPkg # Close-ExcelPackage -NoSave $NowPkg
Remove-Item $NowPath2 # Remove-Item $NowPath2
} # }
$sheet = $excel.Sheet3 # $sheet = $excel.Sheet3
Context "Table of processes via Send-SQLDataToExcel" { # Context "Table of processes via Send-SQLDataToExcel" {
it "Put the correct data 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.Rows | Should -Be ($results.Count + 1)
$sheet.Dimension.Columns | Should -Be 5 # $sheet.Dimension.Columns | Should -Be 5
$sheet.cells["A1"].Value | Should -Be "Name" # $sheet.cells["A1"].Value | Should -Be "Name"
$sheet.cells["E1"].Value | Should -Be "StartTime" # $sheet.cells["E1"].Value | Should -Be "StartTime"
$sheet.cells["A3"].Value | Should -Be $results[1].Name # $sheet.cells["A3"].Value | Should -Be $results[1].Name
} # }
it "Created a table " { # it "Created a table " {
$sheet.Tables.count | Should -Be 1 # $sheet.Tables.count | Should -Be 1
$sheet.Tables[0].Columns[4].name | Should -Be "StartTime" # $sheet.Tables[0].Columns[4].name | Should -Be "StartTime"
} # }
it "Formatted date fields with date type " { # it "Formatted date fields with date type " {
$sheet.Cells["E11"].Style.Numberformat.NumFmtID | Should -Be 22 # $sheet.Cells["E11"].Style.Numberformat.NumFmtID | Should -Be 22
} # }
it "Handled two data tables with the same name " { # it "Handled two data tables with the same name " {
$sheet.Tables[0].Name | Should -Be "Data_" # $sheet.Tables[0].Name | Should -Be "Data_"
$wvThree[0] | Should -Match "is not unique" # $wvThree[0] | Should -Match "is not unique"
} # }
} # }
$Sheet = $excel.Sheet4 # $Sheet = $excel.Sheet4
Context "Zero-row Data Table sent with Send-SQLDataToExcel -Force" { # Context "Zero-row Data Table sent with Send-SQLDataToExcel -Force" {
it "Raised a warning and put the correct data headers into the sheet " { # it "Raised a warning and put the correct data headers into the sheet " {
$sheet.Dimension.Rows | Should -Be 1 # $sheet.Dimension.Rows | Should -Be 1
$sheet.Dimension.Columns | Should -Be 5 # $sheet.Dimension.Columns | Should -Be 5
$sheet.cells["A1"].Value | Should -Be "Name" # $sheet.cells["A1"].Value | Should -Be "Name"
$sheet.cells["E1"].Value | Should -Be "StartTime" # $sheet.cells["E1"].Value | Should -Be "StartTime"
$sheet.cells["A3"].Value | Should -BeNullOrEmpty # $sheet.cells["A3"].Value | Should -BeNullOrEmpty
$wvone[0] | Should -Match "Zero" # $wvone[0] | Should -Match "Zero"
} # }
it "Applied table formatting " { # it "Applied table formatting " {
$sheet.Tables.Count | Should -Be 1 # $sheet.Tables.Count | Should -Be 1
$sheet.Tables[0].Name | Should -Be "Data" # $sheet.Tables[0].Name | Should -Be "Data"
} # }
} # }
$Sheet = $excel.Sheet5 # $Sheet = $excel.Sheet5
Context "Zero-column Data Table handled by Send-SQLDataToExcel -Force" { # Context "Zero-column Data Table handled by Send-SQLDataToExcel -Force" {
it "Created a blank Sheet and raised a warning " { # it "Created a blank Sheet and raised a warning " {
$sheet.Dimension | Should -BeNullOrEmpty # $sheet.Dimension | Should -BeNullOrEmpty
$wvTwo | Should -Not -BeNullOrEmpty # $wvTwo | Should -Not -BeNullOrEmpty
} # }
} # }
Close-ExcelPackage $excel # Close-ExcelPackage $excel
$excel = Open-ExcelPackage $path2 # $excel = Open-ExcelPackage $path2
Context "Send-SQLDataToExcel -append works correctly" { # Context "Send-SQLDataToExcel -append works correctly" {
it "Works without table settings " { # it "Works without table settings " {
$excel.sheet1.Dimension.Address | Should -Be "A1:E21" # $excel.sheet1.Dimension.Address | Should -Be "A1:E21"
$excel.sheet1.cells[1,1].value | Should -Be "Name" # $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.cells[12,1].value | Should -Be $excel.sheet1.cells[2,1].value
$excel.sheet1.Tables.count | Should -Be 0 # $excel.sheet1.Tables.count | Should -Be 0
} # }
it "Extends an existing table when appending " { # it "Extends an existing table when appending " {
$excel.sheet2.Dimension.Address | Should -Be "A1:E21" # $excel.sheet2.Dimension.Address | Should -Be "A1:E21"
$excel.sheet2.cells[1,2].value | Should -Be "CPU" # $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.cells[13,2].value | Should -Be $excel.sheet2.cells[3,2].value
$excel.sheet2.Tables.count | Should -Be 1 # $excel.sheet2.Tables.count | Should -Be 1
$excel.sheet2.Tables[0].name | Should -Be "FirstLot" # $excel.sheet2.Tables[0].name | Should -Be "FirstLot"
$excel.sheet2.Tables[0].StyleName | Should -Be "TableStyleLight7" # $excel.sheet2.Tables[0].StyleName | Should -Be "TableStyleLight7"
} # }
it "Creates a new table by name when appending " { # it "Creates a new table by name when appending " {
$excel.sheet3.cells[1,3].value | Should -Be "PM" # $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.cells[14,3].value | Should -Be $excel.sheet3.cells[4,3].value
$excel.sheet3.Tables.count | Should -Be 1 # $excel.sheet3.Tables.count | Should -Be 1
$excel.sheet3.Tables[0].name | Should -Be "SecondLot" # $excel.sheet3.Tables[0].name | Should -Be "SecondLot"
$excel.sheet3.Tables[0].StyleName | Should -Be "TableStyleMedium6" # $excel.sheet3.Tables[0].StyleName | Should -Be "TableStyleMedium6"
} # }
it "Creates a new table by style when appending " { # it "Creates a new table by style when appending " {
$excel.sheet4.cells[1,4].value | Should -Be "Handles" # $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.cells[15,4].value | Should -Be $excel.sheet4.cells[5,4].value
$excel.sheet4.Tables.count | Should -Be 1 # $excel.sheet4.Tables.count | Should -Be 1
$excel.sheet4.Tables[0].name | Should -Be "Table1" # $excel.sheet4.Tables[0].name | Should -Be "Table1"
$excel.sheet4.Tables[0].StyleName | Should -Be "TableStyleDark5" # $excel.sheet4.Tables[0].StyleName | Should -Be "TableStyleDark5"
} # }
} # }
Close-ExcelPackage $excel # Close-ExcelPackage $excel
Context "Import As Text returns text values" { # Context "Import As Text returns text values" {
$x = Import-excel $path -WorksheetName sheet3 -AsText StartTime,hand* | Select-Object -last 1 # $x = Import-excel $path -WorksheetName sheet3 -AsText StartTime,hand* | Select-Object -last 1
it "Had fields of type string, not date or int, where specified as ASText " { # it "Had fields of type string, not date or int, where specified as ASText " {
$x.Handles.GetType().Name | Should -Be "String" # $x.Handles.GetType().Name | Should -Be "String"
$x.StartTime.GetType().Name | Should -Be "String" # $x.StartTime.GetType().Name | Should -Be "String"
$x.CPU.GetType().Name | Should -Not -Be "String" # $x.CPU.GetType().Name | Should -Not -Be "String"
} # }
} # }
} # }

View File

@@ -1,46 +1,45 @@
[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" { Describe "Join Worksheet part 1" {
BeforeAll { 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" . "$PSScriptRoot\Samples\Samples.ps1"
$path = "TestDrive:\test.xlsx" $path = "TestDrive:\test.xlsx"
Remove-Item -Path $path -ErrorAction SilentlyContinue Remove-Item -Path $path -ErrorAction SilentlyContinue
$data1 | Export-Excel -Path $path -WorkSheetname Oxford $data1 | Export-Excel -Path $path -WorkSheetname Oxford
$data2 | Export-Excel -Path $path -WorkSheetname Abingdon $data2 | Export-Excel -Path $path -WorkSheetname Abingdon
$data3 | Export-Excel -Path $path -WorkSheetname Banbury $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 $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 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 # Open-ExcelPackage -Path $path
$ws = $excel.Workbook.Worksheets["Total"] $ws = $excel.Workbook.Worksheets["Total"]
$pt = $excel.Workbook.Worksheets["SummaryPivot"].pivottables[0] $pt = $excel.Workbook.Worksheets["SummaryPivot"].pivottables[0]
$pc = $excel.Workbook.Worksheets["SummaryPivot"].Drawings[0] $pc = $excel.Workbook.Worksheets["SummaryPivot"].Drawings[0]
} }
Context "Export-Excel setting spreadsheet visibility" { Context "Export-Excel setting spreadsheet visibility" {
it "Hid the worksheets " { it "Hid the worksheets " {
@@ -93,20 +92,22 @@ Describe "Join Worksheet part 1" {
} }
} }
} }
$path = "TestDrive:\Test.xlsx" $path = "TestDrive:\Test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue Remove-item -Path $path -ErrorAction SilentlyContinue
#switched to CIM objects so test runs on V6 #switched to CIM objects so test runs on V6
Describe "Join Worksheet part 2" { Describe "Join Worksheet part 2" {
Get-CimInstance -ClassName win32_logicaldisk | BeforeEach {
Select-Object -Property DeviceId,VolumeName, Size,Freespace | Get-CimInstance -ClassName win32_logicaldisk |
Export-Excel -Path $path -WorkSheetname Volumes -NumberFormat "0,000" Select-Object -Property DeviceId, VolumeName, Size, Freespace |
Get-CimInstance -Namespace root/StandardCimv2 -class MSFT_NetAdapter | Export-Excel -Path $path -WorkSheetname Volumes -NumberFormat "0,000"
Select-Object -Property Name,InterfaceDescription,MacAddress,LinkSpeed | Get-CimInstance -Namespace root/StandardCimv2 -class MSFT_NetAdapter |
Export-Excel -Path $path -WorkSheetname NetAdapters 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 Join-Worksheet -Path $path -HideSource -WorkSheetName Summary -NoHeader -LabelBlocks -AutoSize -Title "Summary" -TitleBold -TitleSize 22
$excel = Open-ExcelPackage -Path $path $excel = Open-ExcelPackage -Path $path
$ws = $excel.Workbook.Worksheets["Summary"] $ws = $excel.Workbook.Worksheets["Summary"]
}
Context "Bringing 3 Unlinked blocks onto one page" { Context "Bringing 3 Unlinked blocks onto one page" {
it "Hid the source worksheets " { it "Hid the source worksheets " {
$excel.Workbook.Worksheets[1].Hidden.tostring() | Should -Be "Hidden" $excel.Workbook.Worksheets[1].Hidden.tostring() | Should -Be "Hidden"

View File

@@ -14,25 +14,25 @@
$actual.Count | Should -Be 1 $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 = Import-Excel -Path (Join-Path $PWD "$($script:xlfileName)")
$actual | Should -Not -Be $null $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 = Import-Excel -Path "$($script:xlfileName)"
$actual | Should -Not -Be $null $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" { 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" { 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" { Import-Excel -Path "ExcelFileDoesNotExist.xlsxs" } | Should -Throw "Import-Excel does not support reading this extension type .xlsxs"
} }
} }

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" { Describe "Number format expansion and setting" {
BeforeEach {
$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" { Context "Expand-NumberFormat function" {
It "Expanded named number formats as expected " { It "Expanded named number formats as expected " {
$r = [regex]::Escape([cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol) $r = [regex]::Escape([cultureinfo]::CurrentCulture.NumberFormat.CurrencySymbol)
@@ -46,7 +44,7 @@ Describe "Number format expansion and setting" {
Remove-Item -Path $path -ErrorAction SilentlyContinue Remove-Item -Path $path -ErrorAction SilentlyContinue
$n = [datetime]::Now.ToOADate() $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] $ws = $excel.Workbook.Worksheets[1]
Set-ExcelRange -Worksheet $ws -Range "A1" -numberFormat 'General' Set-ExcelRange -Worksheet $ws -Range "A1" -numberFormat 'General'
Set-ExcelRange -Worksheet $ws -Range "A2" -numberFormat 'Number' Set-ExcelRange -Worksheet $ws -Range "A2" -numberFormat 'Number'
@@ -121,14 +119,14 @@ Describe "Number format expansion and setting" {
} }
} }
Describe "Set-ExcelColumn, Set-ExcelRow and Set-ExcelRange" { Describe "Set-ExcelColumn, Set-ExcelRow and Set-ExcelRange" -Skip {
BeforeAll { BeforeAll {
Remove-Item -Path $path -ErrorAction SilentlyContinue 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"] $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 $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["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 -Address $excel.Workbook.Worksheets["Sheet1"].Cells["c3"] -BorderColor ([System.Drawing.Color]::Red) -BorderTop DashDot -BorderLeft DashDotDot -BorderBottom Dashed -BorderRight Dotted
Set-ExcelRange -Worksheet $ws -Range "E3" -Bold:$false -FontShift Superscript -HorizontalAlignment Left Set-ExcelRange -Worksheet $ws -Range "E3" -Bold:$false -FontShift Superscript -HorizontalAlignment Left
@@ -229,14 +227,14 @@ Describe "Set-ExcelColumn, Set-ExcelRow and Set-ExcelRange" {
$excel = $DriverData | Export-Excel -PassThru -Path $path -AutoSize -AutoNameRange $excel = $DriverData | Export-Excel -PassThru -Path $path -AutoSize -AutoNameRange
$ws = $excel.Workbook.Worksheets[1] $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 { $c = Set-ExcelColumn -PassThru -Worksheet $ws -Heading "NextBirthday" -Value {
$bmonth = $worksheet.Cells["C$Row"].value.month ; $bDay = $worksheet.Cells["C$Row"].value.day $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 $cMonth = [datetime]::Now.Month ; $cday = [datetime]::Now.day ; $cyear = [datetime]::Now.Year
if (($cmonth -gt $bmonth) -or (($cMonth -eq $bmonth) -and ($cday -ge $bDay))) { if (($cmonth -gt $bmonth) -or (($cMonth -eq $bmonth) -and ($cday -ge $bDay))) {
[datetime]::new($cyear + 1, $bmonth, $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)" Set-ExcelColumn -Worksheet $ws -Heading "Age" -Value "=INT((NOW()-DateOfBirth)/365)"
# Test Piping column Numbers into Set excelColumn # Test Piping column Numbers into Set excelColumn
@@ -293,33 +291,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" { Describe "AutoNameRange data with a single property name" {
BeforeEach { 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" $xlfile = "TestDrive:\testNamedRange.xlsx"
Remove-Item $xlfile -ErrorAction SilentlyContinue 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 @" $excel = ConvertFrom-Csv @"
Sold Sold
1 1
2 2
@@ -327,14 +325,14 @@ Sold
4 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.Count | Should -Be 1
$ws.Names[0].Name | Should -Be '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 @" $excel = ConvertFrom-Csv @"
Sold,ID Sold,ID
1,a 1,a
2,b 2,b
@@ -342,15 +340,15 @@ Sold,ID
4,d 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.Count | Should -Be 2
$ws.Names[0].Name | Should -Be 'Sold' $ws.Names[0].Name | Should -Be 'Sold'
$ws.Names[1].Name | Should -Be 'ID' $ws.Names[1].Name | Should -Be 'ID'
} }
} }
Describe "Table Formatting" { Describe "Table Formatting" -Skip {
BeforeAll { BeforeAll {
#Remove-Item $path #Remove-Item $path
$excel = $data2 | Export-excel -path $path -WorksheetName Hardware -AutoNameRange -AutoSize -BoldTopRow -FreezeTopRow -PassThru $excel = $data2 | Export-excel -path $path -WorksheetName Hardware -AutoNameRange -AutoSize -BoldTopRow -FreezeTopRow -PassThru

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" { Describe "Data validation and protection" {
Context "Data Validation rules" { Context "Data Validation rules" {
BeforeAll { 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 Remove-Item $path -ErrorAction SilentlyContinue
$excelPackage = $Data | Export-excel -WorksheetName "Sales" -path $path -PassThru $excelPackage = $Data | Export-excel -WorksheetName "Sales" -path $path -PassThru
$excelPackage = @('Chisel','Crowbar','Drill','Hammer','Nails','Saw','Screwdriver','Wrench') | $excelPackage = @('Chisel', 'Crowbar', 'Drill', 'Hammer', 'Nails', 'Saw', 'Screwdriver', 'Wrench') |
Export-excel -ExcelPackage $excelPackage -WorksheetName Values -PassThru 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 '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' 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 Close-ExcelPackage -ExcelPackage $excelPackage
$excelPackage = Open-ExcelPackage -Path $path $excelPackage = Open-ExcelPackage -Path $path
$ws = $excelPackage.Sales $ws = $excelPackage.Sales
} }
It "Created the expected number of rules " { It "Created the expected number of rules " {
$ws.DataValidations.count | Should -Be 2 $ws.DataValidations.count | Should -Be 2