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

View File

@@ -1,15 +1,17 @@
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
Name = "John"
Age = $null
}) | Export-Excel $xlFile
}
@@ -18,7 +20,7 @@ Describe "ConvertFrom-ExcelToSQLInsert" {
}
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
@@ -26,7 +28,7 @@ Describe "ConvertFrom-ExcelToSQLInsert" {
}
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

View File

@@ -1,7 +1,8 @@
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'False Positives')]
param()
Describe "Copy-Worksheet" {
BeforeAll {
$path1 = "TestDrive:\Test1.xlsx"
$path2 = "TestDrive:\Test2.xlsx"
Remove-Item -Path $path1, $path2 -ErrorAction SilentlyContinue
@@ -34,8 +35,12 @@ Describe "Copy-Worksheet" {
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,7 +51,7 @@ Describe "Copy-Worksheet" {
$ws.Dimension.Address | Should -Be $ProcRange
}
}
Context "Mixed types using a package object" {
Context "Mixed types using a package object" -Skip {
BeforeAll {
Copy-ExcelWorksheet -SourceWorkbook $excel -DestinationWorkbook $excel -DestinationWorkSheet "CopyOfMixedTypes"
Close-ExcelPackage -ExcelPackage $excel

View File

@@ -1,15 +1,9 @@
#Requires -Modules Pester
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidAssignmentToAutomaticVariable", "", Justification='Sets IsWindows on pre-6.0 only')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')]
param()
if (-not (Get-command Import-Excel -ErrorAction SilentlyContinue)) {
Import-Module $PSScriptRoot\..\ImportExcel.psd1
}
if ($null -eq $IsWindows) {$IsWindows = [environment]::OSVersion.Platform -like "win*"}
$WarningAction = "SilentlyContinue"
Describe ExportExcel {
Describe ExportExcel -Tag "ExportExcel" {
BeforeAll {
if ($null -eq $IsWindows) { $IsWindows = [environment]::OSVersion.Platform -like "win*" }
$WarningAction = "SilentlyContinue"
. "$PSScriptRoot\Samples\Samples.ps1"
if (Get-process -Name Excel,xlim -ErrorAction SilentlyContinue) {
if (Get-process -Name Excel, xlim -ErrorAction SilentlyContinue) {
It "Excel is open" {
$Warning = "You need to close Excel before running the tests."
Write-Warning -Message $Warning
@@ -17,29 +11,31 @@ Describe ExportExcel {
}
return
}
}
Context "#Example 1 # Creates and opens a file with the right number of rows and columns" {
BeforeAll {
$path = "TestDrive:\test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue
#Test with a maximum of 100 processes for speed; export all properties, then export smaller subsets.
$processes = Get-Process | Where-Object {$_.StartTime} | Select-Object -First 100 -Property * -ExcludeProperty Parent
$processes = Get-Process | Where-Object { $_.StartTime } | Select-Object -First 100 -Property * -ExcludeProperty Parent
$propertyNames = $Processes[0].psobject.properties.name
$rowcount = $Processes.Count
$Processes | Export-Excel $path #-show
}
BeforeEach {
#Open-ExcelPackage with -Create is tested in Export-Excel
#This is a test of using it with -KillExcel
#TODO Need to test opening pre-existing file with no -create switch (and graceful failure when file does not exist) somewhere else
$Excel = Open-ExcelPackage -Path $path -KillExcel
$ws = $Excel.Workbook.Worksheets[1]
$headingNames = $ws.cells["1:1"].Value
}
it "Created a new file " {
Test-Path -Path $path -ErrorAction SilentlyContinue | Should -Be $true
}
# it "Started Excel to display the file " {
# Get-process -Name Excel, xlim -ErrorAction SilentlyContinue | Should -Not -BeNullOrEmpty
# }
#Start-Sleep -Seconds 5 ;
#Open-ExcelPackage with -Create is tested in Export-Excel
#This is a test of using it with -KillExcel
#TODO Need to test opening pre-existing file with no -create switch (and graceful failure when file does not exist) somewhere else
$Excel = Open-ExcelPackage -Path $path -KillExcel
it "Killed Excel when Open-Excelpackage was told to " {
Get-process -Name Excel, xlim -ErrorAction SilentlyContinue | Should -BeNullOrEmpty
}
@@ -53,14 +49,12 @@ Describe ExportExcel {
$Excel.Sheet1 | Should -Not -BeNullOrEmpty
}
$ws = $Excel.Workbook.Worksheets[1]
it "Created the worksheet with the expected name, number of rows and number of columns " {
$ws.Name | Should -Be "sheet1"
$ws.Dimension.Columns | Should -Be $propertyNames.Count
$ws.Dimension.Rows | Should -Be ($rowcount + 1)
}
$headingNames = $ws.cells["1:1"].Value
it "Created the worksheet with the correct header names " {
foreach ($p in $propertyNames) {
$headingnames -contains $p | Should -Be $true
@@ -68,23 +62,24 @@ Describe ExportExcel {
}
it "Formatted the process StartTime field as 'localized Date-Time' " {
$STHeader = $ws.cells["1:1"].where( {$_.Value -eq "StartTime"})[0]
$STHeader = $ws.cells["1:1"].where( { $_.Value -eq "StartTime" })[0]
$STCell = $STHeader.Address -replace '1$', '2'
$ws.cells[$stcell].Style.Numberformat.NumFmtID | Should -Be 22
}
it "Formatted the process ID field as 'General' " {
$IDHeader = $ws.cells["1:1"].where( {$_.Value -eq "ID"})[0]
$IDHeader = $ws.cells["1:1"].where( { $_.Value -eq "ID" })[0]
$IDCell = $IDHeader.Address -replace '1$', '2'
$ws.cells[$IDcell].Style.Numberformat.NumFmtID | Should -Be 0
}
}
Context " # NoAliasOrScriptPropeties -ExcludeProperty and -DisplayPropertySet work" {
BeforeAll {
$path = "TestDrive:\test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue
$processes = Get-Process | Select-Object -First 100
$propertyNames = $Processes[0].psobject.properties.where( {$_.MemberType -eq 'Property'}).name
$propertyNames = $Processes[0].psobject.properties.where( { $_.MemberType -eq 'Property' }).name
$rowcount = $Processes.Count
#Test -NoAliasOrScriptPropeties option and creating a range with a name which needs illegal chars removing - check this sends back a warning
$warnVar = $null
@@ -108,12 +103,15 @@ Describe ExportExcel {
$Excel = Open-ExcelPackage -Path $path
$ws = $Excel.Workbook.Worksheets[1]
}
it "Created a new file with further properties excluded and cleared the old sheet " {
$ws.Name | Should -Be "sheet1"
$ws.Dimension.Columns | Should -Be ($propertyNames.Count - 10)
$ws.Dimension.Rows | Should -Be ($rowcount + 1) # +1 for the header
}
it "Created a new file with just the members of the Display Property Set " {
$propertyNames = $Processes[0].psStandardmembers.DefaultDisplayPropertySet.ReferencedPropertyNames
Remove-item -Path $path -ErrorAction SilentlyContinue
#Test -DisplayPropertySet
@@ -121,7 +119,6 @@ Describe ExportExcel {
$Excel = Open-ExcelPackage -Path $path
$ws = $Excel.Workbook.Worksheets[1]
it "Created a new file with just the members of the Display Property Set " {
$ws.Name | Should -Be "sheet1"
$ws.Dimension.Columns | Should -Be $propertyNames.Count
$ws.Dimension.Rows | Should -Be ($rowcount + 1)
@@ -130,21 +127,27 @@ Describe ExportExcel {
Context "#Example 2 # Exports a list of numbers and applies number format " {
BeforeAll {
$path = "TestDrive:\test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue
#testing -ReturnRange switch and applying number format to Formulas as well as values.
$returnedRange = @($null, -1, 0, 34, 777, "", -0.5, 119, -0.1, 234, 788,"=A9+A10") | Export-Excel -NumberFormat '[Blue]$#,##0.00;[Red]-$#,##0.00' -Path $path -ReturnRange
$returnedRange = @($null, -1, 0, 34, 777, "", -0.5, 119, -0.1, 234, 788, "=A9+A10") | Export-Excel -NumberFormat '[Blue]$#,##0.00;[Red]-$#,##0.00' -Path $path -ReturnRange
it "Created a new file and returned the expected range " {
Test-Path -Path $path -ErrorAction SilentlyContinue | Should -Be $true
$returnedRange | Should -Be "A1:A12"
}
$Excel = Open-ExcelPackage -Path $path
}
BeforeEach {
$ws = $Excel.Workbook.Worksheets[1]
}
it "Created 1 worksheet " {
$Excel.Workbook.Worksheets.count | Should -Be 1
}
$ws = $Excel.Workbook.Worksheets[1]
it "Created the worksheet with the expected name, number of rows and number of columns " {
$ws.Name | Should -Be "sheet1"
$ws.Dimension.Columns | Should -Be 1
@@ -190,8 +193,9 @@ Describe ExportExcel {
Context "#Examples 3 & 4 # Setting cells for different data types Also added test for URI type" {
if ((Get-Culture).NumberFormat.CurrencySymbol -eq "£") {$OtherCurrencySymbol = "$"}
else {$OtherCurrencySymbol = "£"}
BeforeAll {
if ((Get-Culture).NumberFormat.CurrencySymbol -eq "£") { $OtherCurrencySymbol = "$" }
else { $OtherCurrencySymbol = "£" }
$path = "TestDrive:\test.xlsx"
$warnVar = $null
#Test correct export of different data types and number formats; test hyperlinks, test -NoNumberConversion test object is converted to a string with no warnings, test calcuation of formula
@@ -210,8 +214,8 @@ Describe ExportExcel {
StrNegInt = '-31'
StrTrailingNeg = '31-'
StrParens = '(123)'
strLocalCurrency = ('{0}123{1}45' -f (Get-Culture).NumberFormat.CurrencySymbol,(Get-Culture).NumberFormat.CurrencyDecimalSeparator)
strOtherCurrency = ('{0}123{1}45' -f $OtherCurrencySymbol ,(Get-Culture).NumberFormat.CurrencyDecimalSeparator)
strLocalCurrency = ('{0}123{1}45' -f (Get-Culture).NumberFormat.CurrencySymbol, (Get-Culture).NumberFormat.CurrencyDecimalSeparator)
strOtherCurrency = ('{0}123{1}45' -f $OtherCurrencySymbol , (Get-Culture).NumberFormat.CurrencyDecimalSeparator)
StrE164Phone = '+32 (444) 444 4444'
StrAltPhone1 = '+32 4 4444 444'
StrAltPhone2 = '+3244444444'
@@ -225,15 +229,21 @@ Describe ExportExcel {
Process = (Get-Process -Id $PID)
TimeSpan = [datetime]::Now.Subtract([datetime]::Today)
} | Export-Excel -NoNumberConversion IPAddress, StrLeadZero, StrAltPhone2 -Path $path -Calculate -WarningVariable $warnVar
}
BeforeEach {
$Excel = Open-ExcelPackage -Path $path
$ws = $Excel.Workbook.Worksheets[1]
}
it "Created a new file " {
Test-Path -Path $path -ErrorAction SilentlyContinue | Should -Be $true
}
$Excel = Open-ExcelPackage -Path $path
it "Created 1 worksheet with no warnings " {
$Excel.Workbook.Worksheets.count | Should -Be 1
$warnVar | Should -BeNullorEmpty
}
$ws = $Excel.Workbook.Worksheets[1]
it "Created the worksheet with the expected name, number of rows and number of columns " {
$ws.Name | Should -Be "sheet1"
$ws.Dimension.Columns | Should -Be 27
@@ -309,6 +319,7 @@ Describe ExportExcel {
Context "# # Setting cells for different data types with -noHeader" {
BeforeAll {
$path = "TestDrive:\test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue
#Test -NoHeader & -NoNumberConversion
@@ -328,16 +339,21 @@ Describe ExportExcel {
PhoneNr3 = '+3244444444'
Link = [uri]"https://github.com/dfinke/ImportExcel"
} | Export-Excel -NoNumberConversion IPAddress, Number1 -Path $path -NoHeader
}
BeforeEach {
$Excel = Open-ExcelPackage -Path $path
$ws = $Excel.Workbook.Worksheets[1]
}
it "Created a new file " {
Test-Path -Path $path -ErrorAction SilentlyContinue | Should -Be $true
}
$Excel = Open-ExcelPackage -Path $path
it "Created 1 worksheet " {
$Excel.Workbook.Worksheets.count | Should -Be 1
}
$ws = $Excel.Workbook.Worksheets[1]
it "Created the worksheet with the expected name, number of rows and number of columns " {
$ws.Name | Should -Be "sheet1"
$ws.Dimension.Columns | Should -Be 14
@@ -366,7 +382,8 @@ Describe ExportExcel {
}
}
Context "#Example 5 # Adding a single conditional format " {
Context "#Example 5 # Adding a single conditional format " -Skip {
BeforeEach {
#Test New-ConditionalText builds correctly
$ct = New-ConditionalText -ConditionalType GreaterThan 525 -ConditionalTextColor ([System.Drawing.Color]::DarkRed) -BackgroundColor ([System.Drawing.Color]::LightPink)
@@ -382,13 +399,14 @@ Describe ExportExcel {
#ToDo need to test applying conitional formatting to a pre-existing worksheet and removing = from formula
$Excel = Open-ExcelPackage -Path $path
$ws = $Excel.Workbook.Worksheets[1]
$cf = $ws.ConditionalFormatting[0]
}
it "Added one block of conditional formating for the data range " {
$ws.ConditionalFormatting.Count | Should -Be 1
$ws.ConditionalFormatting[0].Address | Should -Be ($ws.Dimension.Address)
}
$cf = $ws.ConditionalFormatting[0]
it "Set the conditional formatting properties correctly " {
$cf.Formula | Should -Be $ct.Text
$cf.Type.ToString() | Should -Be $ct.ConditionalType
@@ -397,6 +415,8 @@ Describe ExportExcel {
}
}
Context "#Example 6 # Adding multiple conditional formats using short form syntax. " {
BeforeAll {
#Test adding mutliple conditional blocks and using the minimal syntax for New-ConditionalText
$path = "TestDrive:\test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue
@@ -408,8 +428,12 @@ Describe ExportExcel {
New-ConditionalText Running ([System.Drawing.Color]::Blue) ([System.Drawing.Color]::Cyan)
)
$ws = $Excel.Workbook.Worksheets[1]
}
AfterAll {
Close-ExcelPackage -ExcelPackage $Excel
}
Context "#Example 6 # Adding multiple conditional formats using short form syntax. " {
it "Added two blocks of conditional formating for the data range " {
$ws.ConditionalFormatting.Count | Should -Be 2
$ws.ConditionalFormatting[0].Address | Should -Be ($ws.Dimension.Address)
@@ -423,9 +447,9 @@ Describe ExportExcel {
#Add RGB Comparison
}
}
Close-ExcelPackage -ExcelPackage $Excel
Context "#Example 7 # Update-FirstObjectProperties works " {
BeforeAll {
$Array = @()
$Obj1 = [PSCustomObject]@{
@@ -449,6 +473,8 @@ Describe ExportExcel {
$Array = $Obj1, $Obj2, $Obj3
#test Update-FirstObjectProperties
$newarray = $Array | Update-FirstObjectProperties
}
it "Outputs as many objects as it input " {
$newarray.Count | Should -Be $Array.Count
}
@@ -461,7 +487,8 @@ Describe ExportExcel {
}
}
Context "#Examples 8 & 9 # Adding Pivot tables and charts from parameters" {
Context "#Examples 8 & 9 # Adding Pivot tables and charts from parameters" -Skip {
BeforeAll {
$path = "TestDrive:\test.xlsx"
#Test -passthru and -worksheetName creating a new, named, sheet in an existing file.
$Excel = Get-Process | Select-Object -first 20 -Property Name, cpu, pm, handles, company | Export-Excel $path -WorkSheetname Processes -PassThru
@@ -471,6 +498,23 @@ Describe ExportExcel {
$Excel = Open-ExcelPackage $path
$PTws = $Excel.Workbook.Worksheets["ProcessesPivotTable"]
$wCount = $Excel.Workbook.Worksheets.Count
$pt = $PTws.PivotTables[0]
#test adding pivot chart using the already open sheet
$warnvar = $null
Export-Excel -ExcelPackage $Excel -WorkSheetname Processes -IncludePivotTable -PivotRows Company -PivotData PM -IncludePivotChart -ChartType PieExploded3D -ShowCategory -ShowPercent -NoLegend -WarningAction SilentlyContinue -WarningVariable warnvar
}
BeforeEach {
$Excel = Open-ExcelPackage $path
#Test appending data extends pivot chart (with a warning) .
$warnVar = $null
Get-Process | Select-Object -Last 20 -Property Name, cpu, pm, handles, company | Export-Excel $path -WorkSheetname Processes -Append -IncludePivotTable -PivotRows Company -PivotData PM -IncludePivotChart -ChartType PieExploded3D -WarningAction SilentlyContinue -WarningVariable warnvar
$Excel = Open-ExcelPackage $path
$pt = $Excel.Workbook.Worksheets["ProcessesPivotTable"].PivotTables[0]
}
it "Added the named sheet and pivot table to the workbook " {
$excel.ProcessesPivotTable | Should -Not -BeNullOrEmpty
$PTws | Should -Not -BeNullOrEmpty
@@ -483,7 +527,6 @@ Describe ExportExcel {
Set-ItResult -Pending -Because "Bug in EPPLus 4.5"
$PTws.View.TabSelected | Should -Be $true
}
$pt = $PTws.PivotTables[0]
it "Built the expected Pivot table " {
$pt.RowFields.Count | Should -Be 1
$pt.RowFields[0].Name | Should -Be "Company"
@@ -492,10 +535,6 @@ Describe ExportExcel {
$pt.DataFields[0].Field.Name | Should -Be "PM"
$PTws.Drawings.Count | Should -Be 0
}
#test adding pivot chart using the already open sheet
$warnvar = $null
Export-Excel -ExcelPackage $Excel -WorkSheetname Processes -IncludePivotTable -PivotRows Company -PivotData PM -IncludePivotChart -ChartType PieExploded3D -ShowCategory -ShowPercent -NoLegend -WarningAction SilentlyContinue -WarningVariable warnvar
$Excel = Open-ExcelPackage $path
it "Added a chart to the pivot table without rebuilding " {
$ws = $Excel.Workbook.Worksheets["ProcessesPivotTable"]
$Excel.Workbook.Worksheets.Count | Should -Be $wCount
@@ -505,11 +544,6 @@ Describe ExportExcel {
it "Generated a message on re-processing the Pivot table " {
$warnVar | Should -Not -BeNullOrEmpty
}
#Test appending data extends pivot chart (with a warning) .
$warnVar = $null
Get-Process | Select-Object -Last 20 -Property Name, cpu, pm, handles, company | Export-Excel $path -WorkSheetname Processes -Append -IncludePivotTable -PivotRows Company -PivotData PM -IncludePivotChart -ChartType PieExploded3D -WarningAction SilentlyContinue -WarningVariable warnvar
$Excel = Open-ExcelPackage $path
$pt = $Excel.Workbook.Worksheets["ProcessesPivotTable"].PivotTables[0]
it "Appended to the Worksheet and Extended the Pivot table " {
$Excel.Workbook.Worksheets.Count | Should -Be $wCount
$excel.Workbook.Worksheets["Processes"].Dimension.rows | Should -Be 41 #appended 20 rows to the previous total
@@ -521,7 +555,8 @@ Describe ExportExcel {
}
}
Context " # Add-Worksheet inserted sheets, moved them correctly, and copied a sheet" {
Context " # Add-Worksheet inserted sheets, moved them correctly, and copied a sheet" -Skip {
BeforeAll {
$path = "TestDrive:\test.xlsx"
#Test the -CopySource and -Movexxxx parameters for Add-Worksheet
$Excel = Open-ExcelPackage $path
@@ -535,6 +570,7 @@ Describe ExportExcel {
Close-ExcelPackage $Excel
$Excel = Open-ExcelPackage $path
}
it "Got the Sheets in the right order " {
$excel.Workbook.Worksheets[1].Name | Should -Be "Another"
@@ -557,6 +593,7 @@ Describe ExportExcel {
}
Context " # Create and append with Start row and Start Column, inc ranges and Pivot table. " {
BeforeAll {
$path = "TestDrive:\test.xlsx"
remove-item -Path $path -ErrorAction SilentlyContinue
#Catch warning
@@ -567,6 +604,8 @@ Describe ExportExcel {
$Excel = Open-ExcelPackage $path
$dataWs = $Excel.Workbook.Worksheets["withOffset"]
$pt = $Excel.Workbook.Worksheets["PTOffset"].PivotTables[0]
}
it "Created and appended to a sheet offset from the top left corner " {
$dataWs.Cells[1, 1].Value | Should -BeNullOrEmpty
$dataWs.Cells[2, 2].Value | Should -BeNullOrEmpty
@@ -593,8 +632,7 @@ Describe ExportExcel {
$dataWs.Names["CPU"].Columns | Should -Be 1
}
it "Created and extended the pivot table " {
$pt.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref |
Should be "C3:G23"
$pt.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref | Should -be "C3:G23"
$pt.ColumGrandTotals | Should -Be $false
$pt.RowGrandTotals | Should -Be $false
$pt.Fields["Company"].IsRowField | Should -Be $true
@@ -607,6 +645,7 @@ Describe ExportExcel {
}
Context " # Create and append explicit and auto table and range extension" {
BeforeAll {
$path = "TestDrive:\test.xlsx"
#Test -Append automatically extends a table, even when it is not specified in the append command;
Get-Process | Select-Object -first 10 -Property Name, cpu, pm, handles, company | Export-Excel -Path $path -TableName ProcTab -AutoNameRange -WorkSheetname NoOffset -ClearSheet
@@ -614,6 +653,8 @@ Describe ExportExcel {
Get-Process | Select-Object -last 10 -Property Name, cpu, pm, handles, company | Export-Excel -Path $path -AutoNameRange -WorkSheetname NoOffset -Append -Numberformat 'Number'
$Excel = Open-ExcelPackage $path
$dataWs = $Excel.Workbook.Worksheets["NoOffset"]
}
#table should be 20 rows + header after extending the data. CPU range should be 1x20
it "Created a new sheet and auto-extended a table and explicitly extended named ranges " {
$dataWs.Tables["ProcTab"].Address.Address | Should -Be "A1:E21"
@@ -624,13 +665,14 @@ Describe ExportExcel {
$dataWs.cells["C2"].Style.Numberformat.Format | Should -Be "General"
$dataWs.cells["C12"].Style.Numberformat.Format | Should -Be "0.00"
}
#Test extneding autofilter and range when explicitly specified in the append
it "Created a new sheet and explicitly extended named range and autofilter " {
#Test extending autofilter and range when explicitly specified in the append
$excel = Get-Process | Select-Object -first 10 -Property Name, cpu, pm, handles, company | Export-Excel -ExcelPackage $excel -RangeName procs -AutoFilter -WorkSheetname NoOffset -ClearSheet -PassThru
Get-Process | Select-Object -last 10 -Property Name, cpu, pm, handles, company | Export-Excel -ExcelPackage $excel -RangeName procs -AutoFilter -WorkSheetname NoOffset -Append
$Excel = Open-ExcelPackage $path
$dataWs = $Excel.Workbook.Worksheets["NoOffset"]
it "Created a new sheet and explicitly extended named range and autofilter " {
$dataWs.names["procs"].rows | Should -Be 21
$dataWs.names["procs"].Columns | Should -Be 5
$dataWs.Names["_xlnm._FilterDatabase"].Rows | Should -Be 21 #2 x 10 data + 1 header
@@ -639,97 +681,98 @@ Describe ExportExcel {
}
}
Context "#Example 11 # Create and append with title, inc ranges and Pivot table" {
$path = "TestDrive:\test.xlsx"
#Test New-PivotTableDefinition builds definition using -Pivotfilter and -PivotTotals options.
$ptDef = [ordered]@{}
$ptDef += New-PivotTableDefinition -PivotTableName "PT1" -SourceWorkSheet 'Sheet1' -PivotRows "Status" -PivotData @{'Status' = 'Count'} -PivotTotals Columns -PivotFilter "StartType" -IncludePivotChart -ChartType BarClustered3D -ChartTitle "Services by status" -ChartHeight 512 -ChartWidth 768 -ChartRow 10 -ChartColumn 0 -NoLegend -PivotColumns CanPauseAndContinue
$ptDef += New-PivotTableDefinition -PivotTableName "PT2" -SourceWorkSheet 'Sheet2' -PivotRows "Company" -PivotData @{'Company' = 'Count'} -PivotTotalS Rows -IncludePivotChart -ChartType PieExploded3D -ShowPercent -WarningAction SilentlyContinue
# Context "#Example 11 # Create and append with title, inc ranges and Pivot table" {
# $path = "TestDrive:\test.xlsx"
# #Test New-PivotTableDefinition builds definition using -Pivotfilter and -PivotTotals options.
# $ptDef = [ordered]@{}
# $ptDef += New-PivotTableDefinition -PivotTableName "PT1" -SourceWorkSheet 'Sheet1' -PivotRows "Status" -PivotData @{'Status' = 'Count' } -PivotTotals Columns -PivotFilter "StartType" -IncludePivotChart -ChartType BarClustered3D -ChartTitle "Services by status" -ChartHeight 512 -ChartWidth 768 -ChartRow 10 -ChartColumn 0 -NoLegend -PivotColumns CanPauseAndContinue
# $ptDef += New-PivotTableDefinition -PivotTableName "PT2" -SourceWorkSheet 'Sheet2' -PivotRows "Company" -PivotData @{'Company' = 'Count' } -PivotTotalS Rows -IncludePivotChart -ChartType PieExploded3D -ShowPercent -WarningAction SilentlyContinue
it "Built a pivot definition using New-PivotTableDefinition " {
$ptDef.PT1.SourceWorkSheet | Should -Be 'Sheet1'
$ptDef.PT1.PivotRows | Should -Be 'Status'
$ptDef.PT1.PivotData.Status | Should -Be 'Count'
$ptDef.PT1.PivotFilter | Should -Be 'StartType'
$ptDef.PT1.IncludePivotChart | Should -Be $true
$ptDef.PT1.ChartType.tostring() | Should -Be 'BarClustered3D'
$ptDef.PT1.PivotTotals | Should -Be 'Columns'
}
Remove-Item -Path $path
#Catch warning
$warnvar = $null
#Test create two data pages; as part of adding the second give both their own pivot table, test -autosize switch
Get-Service | Select-Object -Property Status, Name, DisplayName, StartType, CanPauseAndContinue | Export-Excel -Path $path -AutoSize -TableName "All Services" -TableStyle Medium1 -WarningVariable warnvar -WarningAction SilentlyContinue
Get-Process | Select-Object -Property Name, Company, Handles, CPU, VM | Export-Excel -Path $path -AutoSize -WorkSheetname 'sheet2' -TableName "Processes" -TableStyle Light1 -Title "Processes" -TitleFillPattern Solid -TitleBackgroundColor ([System.Drawing.Color]::AliceBlue) -TitleBold -TitleSize 22 -PivotTableDefinition $ptDef
$Excel = Open-ExcelPackage $path
$ws1 = $Excel.Workbook.Worksheets["Sheet1"]
$ws2 = $Excel.Workbook.Worksheets["Sheet2"]
# it "Built a pivot definition using New-PivotTableDefinition " {
# $ptDef.PT1.SourceWorkSheet | Should -Be 'Sheet1'
# $ptDef.PT1.PivotRows | Should -Be 'Status'
# $ptDef.PT1.PivotData.Status | Should -Be 'Count'
# $ptDef.PT1.PivotFilter | Should -Be 'StartType'
# $ptDef.PT1.IncludePivotChart | Should -Be $true
# $ptDef.PT1.ChartType.tostring() | Should -Be 'BarClustered3D'
# $ptDef.PT1.PivotTotals | Should -Be 'Columns'
# }
# Remove-Item -Path $path
# #Catch warning
# $warnvar = $null
# #Test create two data pages; as part of adding the second give both their own pivot table, test -autosize switch
# Get-Service | Select-Object -Property Status, Name, DisplayName, StartType, CanPauseAndContinue | Export-Excel -Path $path -AutoSize -TableName "All Services" -TableStyle Medium1 -WarningVariable warnvar -WarningAction SilentlyContinue
# Get-Process | Select-Object -Property Name, Company, Handles, CPU, VM | Export-Excel -Path $path -AutoSize -WorkSheetname 'sheet2' -TableName "Processes" -TableStyle Light1 -Title "Processes" -TitleFillPattern Solid -TitleBackgroundColor ([System.Drawing.Color]::AliceBlue) -TitleBold -TitleSize 22 -PivotTableDefinition $ptDef
# $Excel = Open-ExcelPackage $path
# $ws1 = $Excel.Workbook.Worksheets["Sheet1"]
# $ws2 = $Excel.Workbook.Worksheets["Sheet2"]
if ($isWindows) {
it "Set Column widths (with autosize) " {
$ws1.Column(2).Width | Should -Not -Be $ws1.DefaultColWidth
$ws2.Column(1).width | Should -Not -Be $ws2.DefaultColWidth
}
}
# if ($isWindows) {
# it "Set Column widths (with autosize) " {
# $ws1.Column(2).Width | Should -Not -Be $ws1.DefaultColWidth
# $ws2.Column(1).width | Should -Not -Be $ws2.DefaultColWidth
# }
# }
it "Added tables to both sheets (handling illegal chars) and a title in sheet 2 " {
$warnvar.count | Should -BeGreaterThan 0
$ws1.tables.Count | Should -Be 1
$ws2.tables.Count | Should -Be 1
$ws1.Tables[0].Address.Start.Row | Should -Be 1
$ws2.Tables[0].Address.Start.Row | Should -Be 2 #Title in row 1
$ws1.Tables[0].Address.End.Address | Should -Be $ws1.Dimension.End.Address
$ws2.Tables[0].Address.End.Address | Should -Be $ws2.Dimension.End.Address
$ws2.Tables[0].Name | Should -Be "Processes"
$ws2.Tables[0].StyleName | Should -Be "TableStyleLight1"
$ws2.Cells["A1"].Value | Should -Be "Processes"
$ws2.Cells["A1"].Style.Font.Bold | Should -Be $true
$ws2.Cells["A1"].Style.Font.Size | Should -Be 22
$ws2.Cells["A1"].Style.Fill.PatternType.tostring() | Should -Be "solid"
$ws2.Cells["A1"].Style.Fill.BackgroundColor.Rgb | Should -Be "fff0f8ff"
}
# it "Added tables to both sheets (handling illegal chars) and a title in sheet 2 " {
# $warnvar.count | Should -BeGreaterThan 0
# $ws1.tables.Count | Should -Be 1
# $ws2.tables.Count | Should -Be 1
# $ws1.Tables[0].Address.Start.Row | Should -Be 1
# $ws2.Tables[0].Address.Start.Row | Should -Be 2 #Title in row 1
# $ws1.Tables[0].Address.End.Address | Should -Be $ws1.Dimension.End.Address
# $ws2.Tables[0].Address.End.Address | Should -Be $ws2.Dimension.End.Address
# $ws2.Tables[0].Name | Should -Be "Processes"
# $ws2.Tables[0].StyleName | Should -Be "TableStyleLight1"
# $ws2.Cells["A1"].Value | Should -Be "Processes"
# $ws2.Cells["A1"].Style.Font.Bold | Should -Be $true
# $ws2.Cells["A1"].Style.Font.Size | Should -Be 22
# $ws2.Cells["A1"].Style.Fill.PatternType.tostring() | Should -Be "solid"
# $ws2.Cells["A1"].Style.Fill.BackgroundColor.Rgb | Should -Be "fff0f8ff"
# }
$ptsheet1 = $Excel.Workbook.Worksheets["Pt1"]
$ptsheet2 = $Excel.Workbook.Worksheets["Pt2"]
$PT1 = $ptsheet1.PivotTables[0]
$PT2 = $ptsheet2.PivotTables[0]
$PC1 = $ptsheet1.Drawings[0]
$PC2 = $ptsheet2.Drawings[0]
it "Created the pivot tables linked to the right data. " {
$PT1.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.name|
Should be "All_services"
$PT2.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.name |
Should be "Processes"
}
it "Set the other pivot tables and chart options from the definitions. " {
$pt1.PageFields[0].Name | Should -Be 'StartType'
$pt1.RowFields[0].Name | Should -Be 'Status'
$pt1.DataFields[0].Field.name | Should -Be 'Status'
$pt1.DataFields[0].Function | Should -Be 'Count'
$pt1.ColumGrandTotals | Should -Be $true
$pt1.RowGrandTotals | Should -Be $false
$pt2.ColumGrandTotals | Should -Be $false
$pt2.RowGrandTotals | Should -Be $true
$pc1.ChartType | Should -Be 'BarClustered3D'
$pc1.From.Column | Should -Be 0 #chart 1 at 0,10 chart 2 at 4,0 (default)
$pc2.From.Column | Should -Be 4
$pc1.From.Row | Should -Be 10
$pc2.From.Row | Should -Be 0
$pc1.Legend.Font | Should -BeNullOrEmpty #Best check for legend removed.
$pc2.Legend.Font | Should -Not -BeNullOrEmpty
$pc1.Title.Text | Should -Be 'Services by status'
$pc2.DataLabel.ShowPercent | Should -Be $true
}
}
# $ptsheet1 = $Excel.Workbook.Worksheets["Pt1"]
# $ptsheet2 = $Excel.Workbook.Worksheets["Pt2"]
# $PT1 = $ptsheet1.PivotTables[0]
# $PT2 = $ptsheet2.PivotTables[0]
# $PC1 = $ptsheet1.Drawings[0]
# $PC2 = $ptsheet2.Drawings[0]
# it "Created the pivot tables linked to the right data. " {
# $PT1.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.name |
# Should be "All_services"
# $PT2.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.name |
# Should be "Processes"
# }
# it "Set the other pivot tables and chart options from the definitions. " {
# $pt1.PageFields[0].Name | Should -Be 'StartType'
# $pt1.RowFields[0].Name | Should -Be 'Status'
# $pt1.DataFields[0].Field.name | Should -Be 'Status'
# $pt1.DataFields[0].Function | Should -Be 'Count'
# $pt1.ColumGrandTotals | Should -Be $true
# $pt1.RowGrandTotals | Should -Be $false
# $pt2.ColumGrandTotals | Should -Be $false
# $pt2.RowGrandTotals | Should -Be $true
# $pc1.ChartType | Should -Be 'BarClustered3D'
# $pc1.From.Column | Should -Be 0 #chart 1 at 0,10 chart 2 at 4,0 (default)
# $pc2.From.Column | Should -Be 4
# $pc1.From.Row | Should -Be 10
# $pc2.From.Row | Should -Be 0
# $pc1.Legend.Font | Should -BeNullOrEmpty #Best check for legend removed.
# $pc2.Legend.Font | Should -Not -BeNullOrEmpty
# $pc1.Title.Text | Should -Be 'Services by status'
# $pc2.DataLabel.ShowPercent | Should -Be $true
# }
# }
Context "#Example 13 # Formatting and another way to do a pivot. " {
BeforeAll {
$path = "TestDrive:\test.xlsx"
Remove-Item $path
Remove-Item $path -ErrorAction SilentlyContinue
#Test freezing top row/first column, adding formats and a pivot table - from Add-Pivot table not a specification variable - after the export
$excel = Get-Process | Select-Object -Property Name, Company, Handles, CPU, PM, NPM, WS | Export-Excel -Path $path -ClearSheet -WorkSheetname "Processes" -FreezeTopRowFirstColumn -PassThru
$sheet = $excel.Workbook.Worksheets["Processes"]
if ($isWindows) {$sheet.Column(1) | Set-ExcelRange -Bold -AutoFit }
else {$sheet.Column(1) | Set-ExcelRange -Bold }
if ($isWindows) { $sheet.Column(1) | Set-ExcelRange -Bold -AutoFit }
else { $sheet.Column(1) | Set-ExcelRange -Bold }
$sheet.Column(2) | Set-ExcelRange -Width 29 -WrapText
$sheet.Column(3) | Set-ExcelRange -HorizontalAlignment Right -NFormat "#,###"
Set-ExcelRange -Address $sheet.Cells["E1:H1048576"] -HorizontalAlignment Right -NFormat "#,###"
@@ -740,12 +783,13 @@ Describe ExportExcel {
$rule = Add-ConditionalFormatting -passthru -Address $sheet.cells["C:C"] -RuleType TopPercent -ConditionValue 20 -Bold -StrikeThru
Add-ConditionalFormatting -Worksheet $sheet -Range "G2:G1048576" -RuleType GreaterThan -ConditionValue "104857600" -ForeGroundColor ([System.Drawing.Color]::Red) -Bold -Italic -Underline -BackgroundColor ([System.Drawing.Color]::Beige) -BackgroundPattern LightUp -PatternColor ([System.Drawing.Color]::Gray)
#Test Set-ExcelRange with a column
if ($isWindows) { foreach ($c in 5..9) {Set-ExcelRange $sheet.Column($c) -AutoFit } }
Add-PivotTable -PivotTableName "PT_Procs" -ExcelPackage $excel -SourceWorkSheet 1 -PivotRows Company -PivotData @{'Name' = 'Count'} -IncludePivotChart -ChartType ColumnClustered -NoLegend
if ($isWindows) { foreach ($c in 5..9) { Set-ExcelRange $sheet.Column($c) -AutoFit } }
Add-PivotTable -PivotTableName "PT_Procs" -ExcelPackage $excel -SourceWorkSheet 1 -PivotRows Company -PivotData @{'Name' = 'Count' } -IncludePivotChart -ChartType ColumnClustered -NoLegend
Export-Excel -ExcelPackage $excel -WorksheetName "Processes" -AutoNameRange #Test adding named ranges seperately from adding data.
$excel = Open-ExcelPackage $path
$sheet = $excel.Workbook.Worksheets["Processes"]
}
it "Returned the rule when calling Add-ConditionalFormatting -passthru " {
$rule | Should -Not -BeNullOrEmpty
$rule.getType().fullname | Should -Be "OfficeOpenXml.ConditionalFormatting.ExcelConditionalFormattingTopPercent"
@@ -793,26 +837,28 @@ Describe ExportExcel {
it "Froze the panes " {
$sheet.view.Panes.Count | Should -Be 3
}
$ptsheet1 = $Excel.Workbook.Worksheets["Pt_procs"]
it "Created the pivot table " {
$ptsheet1 = $Excel.Workbook.Worksheets["Pt_procs"]
$ptsheet1 | Should -Not -BeNullOrEmpty
$ptsheet1.PivotTables[0].DataFields[0].Field.Name | Should -Be "Name"
$ptsheet1.PivotTables[0].DataFields[0].Function | Should -Be "Count"
$ptsheet1.PivotTables[0].RowFields[0].Name | Should -Be "Company"
$ptsheet1.PivotTables[0].CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref |
Should be $sheet.Dimension.address
Should -be $sheet.Dimension.address
}
}
Context " # Chart from MultiSeries.ps1 in the Examples\charts Directory" {
BeforeAll {
$path = "TestDrive:\test.xlsx"
Remove-Item -Path $path -ErrorAction SilentlyContinue
#Test we haven't missed any parameters on New-ChartDefinition which are on add chart or vice versa.
}
$ParamChk1 = (Get-command Add-ExcelChart ).Parameters.Keys.where({-not (Get-command New-ExcelChartDefinition).Parameters.ContainsKey($_) }) | Sort-Object
$ParamChk2 = (Get-command New-ExcelChartDefinition).Parameters.Keys.where({-not (Get-command Add-ExcelChart ).Parameters.ContainsKey($_) })
it "Found the same parameters for Add-ExcelChart and New-ExcelChartDefinintion " {
#Test we haven't missed any parameters on New-ChartDefinition which are on add chart or vice versa.
$ParamChk1 = (Get-command Add-ExcelChart ).Parameters.Keys.where( { -not (Get-command New-ExcelChartDefinition).Parameters.ContainsKey($_) }) | Sort-Object
$ParamChk2 = (Get-command New-ExcelChartDefinition).Parameters.Keys.where( { -not (Get-command Add-ExcelChart ).Parameters.ContainsKey($_) })
$ParamChk1.count | Should -Be 3
$ParamChk1[0] | Should -Be "PassThru"
$ParamChk1[1] | Should -Be "PivotTable"
@@ -820,9 +866,9 @@ Describe ExportExcel {
$ParamChk2.count | Should -Be 1
$ParamChk2[0] | Should -Be "Header"
}
it "Used Invoke-Sum to create a data set " {
#Test Invoke-Sum
$data = Invoke-Sum (Get-Process) Company Handles, PM, VirtualMemorySize
it "Used Invoke-Sum to create a data set " {
$data | Should -Not -BeNullOrEmpty
$data.count | Should -BeGreaterThan 1
$data[1].Name | Should -Not -BeNullOrEmpty
@@ -830,9 +876,9 @@ Describe ExportExcel {
$data[1].PM | Should -Not -BeNullOrEmpty
$data[1].VirtualMemorySize | Should -Not -BeNullOrEmpty
}
$c = New-ExcelChartDefinition -Title Stats -ChartType LineMarkersStacked -XRange "Processes[Name]" -YRange "Processes[PM]", "Processes[VirtualMemorySize]" -SeriesHeader 'PM', 'VMSize'
it "Created the Excel chart definition " {
$c = New-ExcelChartDefinition -Title Stats -ChartType LineMarkersStacked -XRange "Processes[Name]" -YRange "Processes[PM]", "Processes[VirtualMemorySize]" -SeriesHeader 'PM', 'VMSize'
$c | Should -Not -BeNullOrEmpty
$c.ChartType.gettype().name | Should -Be "eChartType"
$c.ChartType.tostring() | Should -Be "LineMarkersStacked"
@@ -846,11 +892,13 @@ Describe ExportExcel {
$c.ShowCategory | Should -Not -Be $true
$c.ShowPercent | Should -Not -Be $true
}
it "Used the Excel chart definition with Export-Excel " -Skip {
#Test creating a chart using -ExcelChartDefinition.
$data | Export-Excel $path -AutoSize -TableName Processes -ExcelChartDefinition $c
$excel = Open-ExcelPackage -Path $path
$drawings = $excel.Workbook.Worksheets[1].drawings
it "Used the Excel chart definition with Export-Excel " {
$drawings.count | Should -Be 1
$drawings[0].ChartType | Should -Be "LineMarkersStacked"
$drawings[0].Series.count | Should -Be 2
@@ -859,14 +907,16 @@ Describe ExportExcel {
$drawings[0].Series[1].Series | Should -Be "'Sheet1'!Processes[VirtualMemorySize]"
$drawings[0].Series[1].XSeries | Should -Be "'Sheet1'!Processes[Name]"
$drawings[0].Title.text | Should -Be "Stats"
}
Close-ExcelPackage $excel
}
}
Context " # variation of plot.ps1 from Examples Directory using Add chart outside ExportExcel" {
BeforeAll {
$path = "TestDrive:\test.xlsx"
#Test inserting a fomual
$excel = 0..360 | ForEach-Object {[pscustomobject][ordered]@{x = $_; Sinx = "=Sin(Radians(x)) "}} | Export-Excel -AutoNameRange -Path $path -WorkSheetname SinX -ClearSheet -FreezeFirstColumn -PassThru
$excel = 0..360 | ForEach-Object { [pscustomobject][ordered]@{x = $_; Sinx = "=Sin(Radians(x)) " } } | Export-Excel -AutoNameRange -Path $path -WorkSheetname SinX -ClearSheet -FreezeFirstColumn -PassThru
#Test-Add Excel Chart to existing data. Test add Conditional formatting with a formula
Add-ExcelChart -Worksheet $excel.Workbook.Worksheets["Sinx"] -ChartType line -XRange "X" -YRange "Sinx" -SeriesHeader "Sin(x)" -Title "Graph of Sine X" -TitleBold -TitleSize 14 `
-Column 2 -ColumnOffSetPixels 35 -Width 800 -XAxisTitleText "Degrees" -XAxisTitleBold -XAxisTitleSize 12 -XMajorUnit 30 -XMinorUnit 10 -XMinValue 0 -XMaxValue 361 -XAxisNumberformat "000" `
@@ -875,6 +925,8 @@ Describe ExportExcel {
Add-ConditionalFormatting -Worksheet $excel.Workbook.Worksheets["Sinx"] -Range "B2:B362" -RuleType LessThan -ConditionValue "=B1" -ForeGroundColor ([System.Drawing.Color]::Red)
$ws = $Excel.Workbook.Worksheets["Sinx"]
$d = $ws.Drawings[0]
}
It "Controled the axes and title and legend of the chart " {
$d.XAxis.MaxValue | Should -Be 361
$d.XAxis.MajorUnit | Should -Be 30
@@ -902,17 +954,22 @@ Describe ExportExcel {
It "Appplied conditional formatting to the data " {
$ws.ConditionalFormatting[0].Formula | Should -Be "B1"
}
AfterAll {
Close-ExcelPackage -ExcelPackage $excel -nosave
}
}
Context " # Quick line chart" {
BeforeAll {
$path = "TestDrive:\test.xlsx"
Remove-Item -Path $path -ErrorAction SilentlyContinue
#test drawing a chart when data doesn't have a string
0..360 | ForEach-Object {[pscustomobject][ordered]@{x = $_; Sinx = "=Sin(Radians(x)) "}} | Export-Excel -AutoNameRange -Path $path -LineChart
0..360 | ForEach-Object { [pscustomobject][ordered]@{x = $_; Sinx = "=Sin(Radians(x)) " } } | Export-Excel -AutoNameRange -Path $path -LineChart
$excel = Open-ExcelPackage -Path $path
$ws = $excel.Sheet1
$d = $ws.Drawings[0]
}
it "Created the chart " {
$d.Title.text | Should -BeNullOrEmpty
$d.ChartType | Should -Be "line"
@@ -924,29 +981,36 @@ Describe ExportExcel {
}
Context " # Quick Pie chart and three icon conditional formating" {
BeforeAll {
$path = "TestDrive:\Pie.xlsx"
Remove-Item -Path $path -ErrorAction SilentlyContinue
$range = Get-Process| Group-Object -Property company | Where-Object -Property name |
Select-Object -Property Name, @{n="TotalPm";e={($_.group | Measure-Object -sum -Property pm).sum }} |
$range = Get-Process | Group-Object -Property company | Where-Object -Property name |
Select-Object -Property Name, @{n = "TotalPm"; e = { ($_.group | Measure-Object -sum -Property pm).sum } } |
Export-Excel -NoHeader -AutoNameRange -path $path -ReturnRange -PieChart -ShowPercent
$Cf = New-ConditionalFormattingIconSet -Range ($range -replace "^.*:","B2:") -ConditionalFormat ThreeIconSet -Reverse -IconType Flags
$Cf = New-ConditionalFormattingIconSet -Range ($range -replace "^.*:", "B2:") -ConditionalFormat ThreeIconSet -Reverse -IconType Flags
$ct = New-ConditionalText -Text "Microsoft" -ConditionalTextColor ([System.Drawing.Color]::Red) -BackgroundColor([System.Drawing.Color]::AliceBlue) -ConditionalType ContainsText
}
it "Created the Conditional formatting rules " {
$cf.Formatter | Should -Be "ThreeIconSet"
$cf.IconType | Should -Be "Flags"
$cf.Range | Should -Be ($range -replace "^.*:","B2:")
$cf.Range | Should -Be ($range -replace "^.*:", "B2:")
$cf.Reverse | Should -Be $true
$ct.BackgroundColor.Name | Should -Be "AliceBlue"
$ct.ConditionalTextColor.Name | Should -Be "Red"
$ct.ConditionalType | Should -Be "ContainsText"
$ct.Text | Should -Be "Microsoft"
}
BeforeEach {
#Test -ConditionalFormat & -ConditionalText
Export-Excel -Path $path -ConditionalFormat $cf -ConditionalText $ct
$excel = Open-ExcelPackage -Path $path
$rows = $range -replace "^.*?(\d+)$", '$1'
$chart = $excel.Workbook.Worksheets["sheet1"].Drawings[0]
$cFmt = $excel.Workbook.Worksheets["sheet1"].ConditionalFormatting
}
it "Created the chart with the right series " {
$chart.ChartType | Should -Be "PieExploded3D"
$chart.series.series | Should -Be "'Sheet1'!B1:B$rows" #would be B2 and A2 if we had a header.
@@ -955,12 +1019,13 @@ Describe ExportExcel {
}
it "Created two Conditional formatting rules " {
$cFmt.Count | Should -Be $true
$cFmt.Where({$_.type -eq "ContainsText"}) | Should -Not -BeNullOrEmpty
$cFmt.Where({$_.type -eq "ThreeIconSet"}) | Should -Not -BeNullOrEmpty
$cFmt.Where( { $_.type -eq "ContainsText" }) | Should -Not -BeNullOrEmpty
$cFmt.Where( { $_.type -eq "ThreeIconSet" }) | Should -Not -BeNullOrEmpty
}
}
Context " # Awkward multiple tables" {
BeforeEach {
$path = "TestDrive:\test.xlsx"
#Test creating 3 on overlapping tables on the same page. Create rightmost the left most then middle.
remove-item -Path $path -ErrorAction SilentlyContinue
@@ -973,18 +1038,20 @@ Describe ExportExcel {
$r = Get-ChildItem -path $SystemFolder -File
"Biggest files" | Export-Excel -Path $path -StartRow 1 -StartColumn 7
$r | Sort-Object length -Descending | Select-Object -First 14 Name, @{n="Size";e={$_.Length}} |
$r | Sort-Object length -Descending | Select-Object -First 14 Name, @{n = "Size"; e = { $_.Length } } |
Export-Excel -Path $path -TableName FileSize -StartRow 2 -StartColumn 7 -TableStyle Medium2
$r.extension | Group-Object | Sort-Object -Property count -Descending | Select-Object -First 12 Name, Count |
Export-Excel -Path $path -TableName ExtSize -Title "Frequent Extensions" -TitleSize 11 -BoldTopRow
$r | Group-Object -Property extension | Select-Object Name, @{n="Size"; e={($_.group | Measure-Object -property length -sum).sum}} |
$r | Group-Object -Property extension | Select-Object Name, @{n = "Size"; e = { ($_.group | Measure-Object -property length -sum).sum } } |
Sort-Object -Property size -Descending | Select-Object -First 10 |
Export-Excel -Path $path -TableName ExtCount -Title "Biggest extensions" -TitleSize 11 -StartColumn 4 -AutoSize
$excel = Open-ExcelPackage -Path $path
$ws = $excel.Workbook.Worksheets[1]
}
it "Created 3 tables " {
$ws.tables.count | Should -Be 3
}
@@ -1001,10 +1068,12 @@ Describe ExportExcel {
}
}
Context " # Parameters and ParameterSets" {
Context " # Parameters and ParameterSets" -Skip {
BeforeAll {
$Path = Join-Path (Resolve-Path 'TestDrive:').ProviderPath "test.xlsx"
Remove-Item -Path $Path -ErrorAction SilentlyContinue
$Processes = Get-Process | Select-Object -first 10 -Property Name, cpu, pm, handles, company
}
it "Allows the default parameter set with Path".PadRight(87) {
$ExcelPackage = $Processes | Export-Excel -Path $Path -PassThru
@@ -1017,8 +1086,8 @@ Describe ExportExcel {
}
it "throws when the ExcelPackage is specified with either -path or -Now".PadRight(87) {
$ExcelPackage = Export-Excel -Path $Path -PassThru
{Export-Excel -ExcelPackage $ExcelPackage -Path $Path} | Should -Throw 'Parameter set cannot be resolved using the specified named parameters'
{Export-Excel -ExcelPackage $ExcelPackage -Now} | Should -Throw 'Parameter set cannot be resolved using the specified named parameters'
{ Export-Excel -ExcelPackage $ExcelPackage -Path $Path } | Should -Throw 'Parameter set cannot be resolved using the specified named parameters'
{ Export-Excel -ExcelPackage $ExcelPackage -Now } | Should -Throw 'Parameter set cannot be resolved using the specified named parameters'
$Processes | Export-Excel -ExcelPackage $ExcelPackage
Remove-Item -Path $Path

View File

@@ -1,6 +1,7 @@
Describe "Creating workbook with a single line" {
BeforeAll {
$path = "TestDrive:\test.xlsx"
remove-item -path $path -ErrorAction SilentlyContinue
ConvertFrom-Csv @"
@@ -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]
}
Context "Data Page" {
It "Inserted the data and created the table " {
$ws1.Tables[0] | Should -Not -BeNullOrEmpty

View File

@@ -1,16 +1,14 @@
[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 |
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.
$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

@@ -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'
@@ -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" {
$actual = Import-Excel $xlfileHeaderOnly
$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,41 +1,40 @@
[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"]
@@ -93,20 +92,22 @@ Describe "Join Worksheet part 1" {
}
}
}
$path = "TestDrive:\Test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue
$path = "TestDrive:\Test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue
#switched to CIM objects so test runs on V6
Describe "Join Worksheet part 2" {
BeforeEach {
Get-CimInstance -ClassName win32_logicaldisk |
Select-Object -Property DeviceId,VolumeName, Size,Freespace |
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 |
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"

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,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" {
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" {
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,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 {
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 +227,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
@@ -293,27 +291,27 @@ 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
}
@@ -350,7 +348,7 @@ Sold,ID
}
}
Describe "Table Formatting" {
Describe "Table Formatting" -Skip {
BeforeAll {
#Remove-Item $path
$excel = $data2 | Export-excel -path $path -WorksheetName Hardware -AutoNameRange -AutoSize -BoldTopRow -FreezeTopRow -PassThru

View File

@@ -1,25 +1,21 @@
[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') |
$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