mirror of
https://github.com/dfinke/ImportExcel.git
synced 2025-12-06 00:23:20 +00:00
More tests; More parameters in Join Worksheet
This commit is contained in:
43
Examples/Join-Worksheet/Join-Worksheet.sample.ps1
Normal file
43
Examples/Join-Worksheet/Join-Worksheet.sample.ps1
Normal file
@@ -0,0 +1,43 @@
|
||||
#Get rid of pre-exisiting sheet
|
||||
$path = "$Env:TEMP\test.xlsx"
|
||||
remove-item -Path $path -ErrorAction SilentlyContinue
|
||||
|
||||
#Create simple pages for 3 stores with product ID, Product Name, quanity price and total
|
||||
|
||||
@"
|
||||
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
|
||||
"@ | ConvertFrom-Csv| Export-Excel -Path $path -WorkSheetname Oxford
|
||||
|
||||
@"
|
||||
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
|
||||
"@ | ConvertFrom-Csv| Export-Excel -Path $path -WorkSheetname Abingdon
|
||||
|
||||
|
||||
@"
|
||||
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
|
||||
"@ | ConvertFrom-Csv| Export-Excel -Path $path -WorkSheetname Banbury
|
||||
|
||||
#define a pivot table with a chart to show a sales by store, broken down by product
|
||||
$ptdef = New-PivotTableDefinition -PivotTableName "Summary" -PivotRows "Store" -PivotColumns "Product" -PivotData @{"Total"="SUM"} -IncludePivotChart -ChartTitle "Sales Breakdown" -ChartType ColumnStacked -ChartColumn 10
|
||||
|
||||
#Join the 3 worksheets.
|
||||
#Name the combined page "Total" and Name the column with the sheet names "store" (as the sheets 'Oxford','Abingdon' and 'Banbury' are the names of the stores
|
||||
#Format the data as a table named "Summary", using the style "Light1", put the column headers in bold
|
||||
#Put in a title and freeze to top of the sheet including title and colmun headings
|
||||
#Add the Pivot table.
|
||||
#Show the result
|
||||
Join-Worksheet -Path $path -WorkSheetName "Total" -Clearsheet -FromLabel "Store" -TableName "Summary" -TableStyle Light1 -AutoSize -BoldTopRow -FreezePane 2,1 -Title "Store Sales Summary" -TitleBold -TitleSize 14 -PivotTableDefinition $ptdef -show
|
||||
@@ -1,620 +0,0 @@
|
||||
#Requires -Modules Pester
|
||||
|
||||
# $here = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
# Import-Module $here -Force -Verbose
|
||||
Import-Module $PSScriptRoot\..\ImportExcel.psd1 -Force
|
||||
|
||||
if (Get-process -Name Excel,xlim -ErrorAction SilentlyContinue) { Write-Warning -Message "You need to close Excel before running the tests." ; return}
|
||||
Describe ExportExcel {
|
||||
|
||||
Context "#Example 1 # Creates and opens a file with the right number of rows and columns" {
|
||||
$path = "$env:TEMP\Test.xlsx"
|
||||
Remove-item -Path $path -ErrorAction SilentlyContinue
|
||||
$processes = Get-Process
|
||||
$propertyNames = $Processes[0].psobject.properties.name
|
||||
$rowcount = $Processes.Count
|
||||
$Processes | Export-Excel $path -show
|
||||
|
||||
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 -Skip "Killed Excel when Open-Excelpackage was told to " {
|
||||
Get-process -Name Excel,xlim -ErrorAction SilentlyContinue | should benullorempty
|
||||
}
|
||||
|
||||
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 $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
|
||||
}
|
||||
}
|
||||
|
||||
it "Formatted the process StartTime field as 'local short date' " {
|
||||
$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]
|
||||
$IDCell = $IDHeader.Address -replace '1$','2'
|
||||
$ws.cells[$IDcell].Style.Numberformat.NumFmtID | should be 0
|
||||
}
|
||||
}
|
||||
|
||||
Context " # NoAliasOrScriptPropeties -ExcludeProperty and -DisplayPropertySet work" {
|
||||
$path = "$env:TEMP\Test.xlsx"
|
||||
Remove-item -Path $path -ErrorAction SilentlyContinue
|
||||
$processes = Get-Process
|
||||
$propertyNames = $Processes[0].psobject.properties.where( {$_.MemberType -eq 'Property'}).name
|
||||
$rowcount = $Processes.Count
|
||||
#TestCreating a range with a name which needs illegal chars removing
|
||||
$warnVar = $null
|
||||
$Processes | Export-Excel $path -NoAliasOrScriptPropeties -RangeName "No Spaces" -WarningVariable warnvar -WarningAction SilentlyContinue
|
||||
|
||||
$Excel = Open-ExcelPackage -Path $path
|
||||
$ws = $Excel.Workbook.Worksheets[1]
|
||||
it "Created a new file with alias & Script Properties removed. " {
|
||||
$ws.Name | should be "sheet1"
|
||||
$ws.Dimension.Columns | should be $propertyNames.Count
|
||||
$ws.Dimension.Rows | should be ($rowcount + 1 ) # +1 for the header.
|
||||
}
|
||||
it "Created a Range - even though the name given was invalid. " {
|
||||
$ws.Names["No_spaces"] | should not beNullOrEmpty
|
||||
$ws.Names["No_spaces"].End.Column | should be $propertyNames.Count
|
||||
$ws.names["No_spaces"].End.Row | should be ($rowcount + 1 ) # +1 for the header.
|
||||
$warnVar.Count | should be 1
|
||||
}
|
||||
#This time use clearsheet instead of deleting the file
|
||||
$Processes | Export-Excel $path -NoAliasOrScriptPropeties -ExcludeProperty SafeHandle, modules, MainModule, StartTime, Threads -ClearSheet
|
||||
|
||||
$Excel = Open-ExcelPackage -Path $path
|
||||
$ws = $Excel.Workbook.Worksheets[1]
|
||||
it "Created a new file with a further 5 properties excluded and cleared the old sheet " {
|
||||
$ws.Name | should be "sheet1"
|
||||
$ws.Dimension.Columns | should be ($propertyNames.Count - 5)
|
||||
$ws.Dimension.Rows | should be ($rowcount + 1) # +1 for the header
|
||||
}
|
||||
|
||||
$propertyNames = $Processes[0].psStandardmembers.DefaultDisplayPropertySet.ReferencedPropertyNames
|
||||
Remove-item -Path $path -ErrorAction SilentlyContinue
|
||||
$Processes | Export-Excel $path -DisplayPropertySet
|
||||
|
||||
$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)
|
||||
}
|
||||
}
|
||||
|
||||
Context "#Example 2 # Exports a list of numbers and applies number format " {
|
||||
|
||||
$path = "$env:TEMP\Test.xlsx"
|
||||
Remove-item -Path $path -ErrorAction SilentlyContinue
|
||||
#testing -ReturnRange switch
|
||||
$returnedRange = Write-Output -1 668 34 777 860 -0.5 119 -0.1 234 788 | 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:A10"
|
||||
}
|
||||
|
||||
$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 1
|
||||
$ws.Dimension.Rows | should be 10
|
||||
}
|
||||
|
||||
it "Set the default style for the sheet as expected " {
|
||||
$ws.cells.Style.Numberformat.Format | should be '[Blue]$#,##0.00;[Red]-$#,##0.00'
|
||||
}
|
||||
|
||||
it "Set the default style and value for Cell A1 as expected " {
|
||||
$ws.cells[1,1].Style.Numberformat.Format | should be '[Blue]$#,##0.00;[Red]-$#,##0.00'
|
||||
$ws.cells[1,1].Value | should be -1
|
||||
}
|
||||
}
|
||||
|
||||
Context "#Examples 3 & 4 # Setting cells for different data types Also added test for URI type" {
|
||||
|
||||
$path = "$env:TEMP\Test.xlsx"
|
||||
Remove-item -Path $path -ErrorAction SilentlyContinue
|
||||
[PSCustOmobject][Ordered]@{
|
||||
Date = Get-Date
|
||||
Formula1 = '=SUM(F2:G2)'
|
||||
String1 = 'My String'
|
||||
String2 = 'a'
|
||||
IPAddress = '10.10.25.5'
|
||||
Number1 = '07670'
|
||||
Number2 = '0,26'
|
||||
Number3 = '1.555,83'
|
||||
Number4 = '1.2'
|
||||
Number5 = '-31'
|
||||
PhoneNr1 = '+32 44'
|
||||
PhoneNr2 = '+32 4 4444 444'
|
||||
PhoneNr3 = '+3244444444'
|
||||
Link = [uri]"https://github.com/dfinke/ImportExcel"
|
||||
} | Export-Excel -NoNumberConversion IPAddress, Number1 -Path $path
|
||||
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
|
||||
$ws.Dimension.Rows | should be 2
|
||||
}
|
||||
|
||||
it "Set a date in Cell A2 " {
|
||||
$ws.Cells[2,1].Value.Gettype().name | should be 'DateTime'
|
||||
}
|
||||
|
||||
it "Set a formula in Cell B2 " {
|
||||
$ws.Cells[2,2].Formula | should be '=SUM(F2:G2)'
|
||||
}
|
||||
|
||||
it "Set strings in Cells E2 and F2 " {
|
||||
$ws.Cells[2,5].Value.GetType().name | should be 'String'
|
||||
$ws.Cells[2,6].Value.GetType().name | should be 'String'
|
||||
}
|
||||
|
||||
it "Set a number in Cell I2 " {
|
||||
($ws.Cells[2,9].Value -is [valuetype] ) | should be $true
|
||||
}
|
||||
|
||||
it "Set a hyperlink in Cell N2 " {
|
||||
$ws.Cells[2,14].Hyperlink | should be "https://github.com/dfinke/ImportExcel"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Context "# # Setting cells for different data types with -noHeader" {
|
||||
|
||||
$path = "$env:TEMP\Test.xlsx"
|
||||
Remove-item -Path $path -ErrorAction SilentlyContinue
|
||||
[PSCustOmobject][Ordered]@{
|
||||
Date = Get-Date
|
||||
Formula1 = '=SUM(F1:G1)'
|
||||
String1 = 'My String'
|
||||
String2 = 'a'
|
||||
IPAddress = '10.10.25.5'
|
||||
Number1 = '07670'
|
||||
Number2 = '0,26'
|
||||
Number3 = '1.555,83'
|
||||
Number4 = '1.2'
|
||||
Number5 = '-31'
|
||||
PhoneNr1 = '+32 44'
|
||||
PhoneNr2 = '+32 4 4444 444'
|
||||
PhoneNr3 = '+3244444444'
|
||||
Link = [uri]"https://github.com/dfinke/ImportExcel"
|
||||
} | Export-Excel -NoNumberConversion IPAddress, Number1 -Path $path -NoHeader
|
||||
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
|
||||
$ws.Dimension.Rows | should be 1
|
||||
}
|
||||
|
||||
it "Set a date in Cell A1 " {
|
||||
$ws.Cells[1,1].Value.Gettype().name | should be 'DateTime'
|
||||
}
|
||||
|
||||
it "Set a formula in Cell B1 " {
|
||||
$ws.Cells[1,2].Formula | should be '=SUM(F1:G1)'
|
||||
}
|
||||
|
||||
it "Set strings in Cells E1 and F1 " {
|
||||
$ws.Cells[1,5].Value.GetType().name | should be 'String'
|
||||
$ws.Cells[1,6].Value.GetType().name | should be 'String'
|
||||
}
|
||||
|
||||
it "Set a number in Cell I1 " {
|
||||
($ws.Cells[1,9].Value -is [valuetype] ) | should be $true
|
||||
}
|
||||
|
||||
it "Set a hyperlink in Cell N1 " {
|
||||
$ws.Cells[1,14].Hyperlink | should be "https://github.com/dfinke/ImportExcel"
|
||||
}
|
||||
}
|
||||
|
||||
Context "#Example 5 # Adding a single conditional format " {
|
||||
### TODO New-ConditionalText doesn't a lot of options in Add-ConditionalFormat.
|
||||
# It would be good to pull the logic out of Export-Excel and have EE call Add-ConditionalFormat.
|
||||
$ct = New-ConditionalText -ConditionalType GreaterThan 525 -ConditionalTextColor DarkRed -BackgroundColor LightPink
|
||||
it "Created a Conditional format description " {
|
||||
$ct.BackgroundColor -is [System.Drawing.Color] | should be $true
|
||||
$ct.ConditionalTextColor -is [System.Drawing.Color] | should be $true
|
||||
$ct.ConditionalType -in [enum]::GetNames( [OfficeOpenXml.ConditionalFormatting.eExcelConditionalFormattingRuleType] ) |
|
||||
should be $true
|
||||
}
|
||||
|
||||
$path = "$env:TEMP\Test.xlsx"
|
||||
Remove-item -Path $path -ErrorAction SilentlyContinue
|
||||
Write-Output 489 668 299 777 860 151 119 497 234 788 | Export-Excel -Path $path -ConditionalText $ct
|
||||
|
||||
it "Created a new file " {
|
||||
Test-Path -Path $path -ErrorAction SilentlyContinue | should be $true
|
||||
}
|
||||
|
||||
#ToDo need to test applying conitional formatting to a pre-existing worksheet
|
||||
$Excel = Open-ExcelPackage -Path $path
|
||||
$ws = $Excel.Workbook.Worksheets[1]
|
||||
|
||||
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
|
||||
#$cf.Style.Fill.BackgroundColor | should be $ct.BackgroundColor
|
||||
# $cf.Style.Font.Color | should be $ct.ConditionalTextColor - have to compare r.g.b
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
Context "#Example 6 # Adding multiple conditional formats using short form syntax. " {
|
||||
#this is a test of adding more than one conditional block and using the minimal syntax for new-ConditionalText =
|
||||
$path = "$env:TEMP\Test.xlsx"
|
||||
Remove-item -Path $path -ErrorAction SilentlyContinue
|
||||
|
||||
#Testing -Passthrough
|
||||
$Excel = Get-Service | Select-Object Name, Status, DisplayName, ServiceName |
|
||||
Export-Excel $path -PassThru -ConditionalText $(
|
||||
New-ConditionalText Stop DarkRed LightPink
|
||||
New-ConditionalText Running Blue Cyan
|
||||
)
|
||||
$ws = $Excel.Workbook.Worksheets[1]
|
||||
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)
|
||||
$ws.ConditionalFormatting[1].Address | should be ($ws.Dimension.Address)
|
||||
}
|
||||
it "Set the conditional formatting properties correctly " {
|
||||
$ws.ConditionalFormatting[0].Text | should be "Stop"
|
||||
$ws.ConditionalFormatting[1].Text | should be "Running"
|
||||
$ws.ConditionalFormatting[0].Type | should be "ContainsText"
|
||||
$ws.ConditionalFormatting[1].Type | should be "ContainsText"
|
||||
#Add RGB Comparison
|
||||
}
|
||||
Close-ExcelPackage -ExcelPackage $Excel
|
||||
}
|
||||
|
||||
context "#Example 7 # Update-FirstObjectProperties works "{
|
||||
$Array = @()
|
||||
|
||||
$Obj1 = [PSCustomObject]@{
|
||||
Member1 = 'First'
|
||||
Member2 = 'Second'
|
||||
}
|
||||
|
||||
$Obj2 = [PSCustomObject]@{
|
||||
Member1 = 'First'
|
||||
Member2 = 'Second'
|
||||
Member3 = 'Third'
|
||||
}
|
||||
|
||||
$Obj3 = [PSCustomObject]@{
|
||||
Member1 = 'First'
|
||||
Member2 = 'Second'
|
||||
Member3 = 'Third'
|
||||
Member4 = 'Fourth'
|
||||
}
|
||||
|
||||
$Array = $Obj1, $Obj2, $Obj3
|
||||
$newarray = $Array | Update-FirstObjectProperties
|
||||
it "Outputs as many objects as it input " {
|
||||
$newarray.Count | should be $Array.Count
|
||||
}
|
||||
it "Added properties to item 0 " {
|
||||
$newarray[0].psobject.Properties.name.Count | should be 4
|
||||
$newarray[0].Member1 | should be 'First'
|
||||
$newarray[0].Member2 | should be 'Second'
|
||||
$newarray[0].Member3 | should beNullOrEmpty
|
||||
$newarray[0].Member4 | should beNullOrEmpty
|
||||
}
|
||||
}
|
||||
|
||||
Context "#Examples 8 & 9 # Adding Pivot tables and charts from parameters" {
|
||||
$path = "$env:TEMP\Test.xlsx"
|
||||
#This time we are not deleting the XLSX file so this should create a new, named, sheet.
|
||||
$Excel = Get-Process | Select-Object -first 50 -Property Name,cpu,pm,handles,company | Export-Excel $path -WorkSheetname Processes -PassThru
|
||||
#Testing -passthru and adding the Pivot as a second step. Want to save and re-open it ...
|
||||
Export-Excel -ExcelPackage $Excel -WorkSheetname Processes -IncludePivotTable -PivotRows Company -PivotData PM
|
||||
|
||||
$Excel = Open-ExcelPackage $path
|
||||
$PTws = $Excel.Workbook.Worksheets["ProcessesPivotTable"]
|
||||
$wCount = $Excel.Workbook.Worksheets.Count
|
||||
it "Added the named sheet and pivot table to the workbook " {
|
||||
$PTws | should not beNullOrEmpty
|
||||
$PTws.PivotTables.Count | should be 1
|
||||
$Excel.Workbook.Worksheets["Processes"] | should not beNullOrEmpty
|
||||
$Excel.Workbook.Worksheets.Count | should beGreaterThan 2
|
||||
$excel.Workbook.Worksheets["Processes"].Dimension.rows | should be 51 #50 data + 1 header
|
||||
}
|
||||
$pt = $PTws.PivotTables[0]
|
||||
it "Built the expected Pivot table " {
|
||||
$pt.RowFields.Count | should be 1
|
||||
$pt.RowFields[0].Name | should be "Company"
|
||||
$pt.DataFields.Count | should be 1
|
||||
$pt.DataFields[0].Function | should be "Count"
|
||||
$pt.DataFields[0].Field.Name | should be "PM"
|
||||
$PTws.Drawings.Count | should be 0
|
||||
}
|
||||
#using the already open sheet add the pivot chart
|
||||
$warnvar = $null
|
||||
Export-Excel -ExcelPackage $Excel -WorkSheetname Processes -IncludePivotTable -PivotRows Company -PivotData PM -IncludePivotChart -ChartType PieExploded3D -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
|
||||
$ws.Drawings.count | should be 1
|
||||
$ws.Drawings[0].ChartType.ToString() | should be "PieExploded3D"
|
||||
}
|
||||
it "Generated a message on re-processing the Pivot table " {
|
||||
$warnVar | Should not beNullOrEmpty
|
||||
}
|
||||
$warnVar = $null
|
||||
Get-Process | Select-Object -Last 50 -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 101 #appended 50 rows to the previous total
|
||||
$pt.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref |
|
||||
should be "A1:E101"
|
||||
}
|
||||
it "Generated a message on extending the Pivot table " {
|
||||
$warnVar | Should not beNullOrEmpty
|
||||
}
|
||||
}
|
||||
|
||||
Context " # Add-Worksheet inserted sheets, moved them correctly, and copied a sheet" {
|
||||
$path = "$env:TEMP\Test.xlsx"
|
||||
|
||||
$Excel = Open-ExcelPackage $path
|
||||
#At this point Sheets should be in the order Sheet1, Processes, ProcessesPivotTable
|
||||
$null = Add-WorkSheet -ExcelPackage $Excel -WorkSheetname "Processes" -MoveToEnd # order now Sheet1, ProcessesPivotTable, Processes
|
||||
$null = Add-WorkSheet -ExcelPackage $Excel -WorkSheetname "NewSheet" -MoveAfter "*" -CopySource ($excel.Workbook.Worksheets["Sheet1"]) # Now its NewSheet, Sheet1, ProcessesPivotTable, Processes
|
||||
$null = Add-WorkSheet -ExcelPackage $Excel -WorkSheetname "Sheet1" -MoveAfter "*" # Now its NewSheet, ProcessesPivotTable, Processes, Sheet1
|
||||
$null = Add-WorkSheet -ExcelPackage $Excel -WorkSheetname "Another" -MoveToStart # Now its Another, NewSheet, ProcessesPivotTable, Processes, Sheet1
|
||||
$null = Add-WorkSheet -ExcelPackage $Excel -WorkSheetname "OneLast" -MoveBefore "ProcessesPivotTable" # Now its Another, NewSheet, Onelast, ProcessesPivotTable, Processes, Sheet1
|
||||
Close-ExcelPackage $Excel
|
||||
|
||||
$Excel = Open-ExcelPackage $path
|
||||
|
||||
it "Got the Sheets in the right order " {
|
||||
$excel.Workbook.Worksheets[1].Name | should be "Another"
|
||||
$excel.Workbook.Worksheets[2].Name | should be "NewSheet"
|
||||
$excel.Workbook.Worksheets[3].Name | should be "Onelast"
|
||||
$excel.Workbook.Worksheets[4].Name | should be "ProcessesPivotTable"
|
||||
$excel.Workbook.Worksheets[5].Name | should be "Processes"
|
||||
$excel.Workbook.Worksheets[6].Name | should be "Sheet1"
|
||||
}
|
||||
|
||||
it "Cloned 'Sheet1' to 'NewSheet' "{
|
||||
$newWs = $excel.Workbook.Worksheets["NewSheet"]
|
||||
$newWs.Dimension.Address | should be ($excel.Workbook.Worksheets["Sheet1"].Dimension.Address)
|
||||
$newWs.ConditionalFormatting.Count | should be ($excel.Workbook.Worksheets["Sheet1"].ConditionalFormatting.Count)
|
||||
$newWs.ConditionalFormatting[0].Address.Address | should be ($excel.Workbook.Worksheets["Sheet1"].ConditionalFormatting[0].Address.Address)
|
||||
$newWs.ConditionalFormatting[0].Formula | should be ($excel.Workbook.Worksheets["Sheet1"].ConditionalFormatting[0].Formula)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Context " # Create and append with Start row and Start Column, inc ranges and Pivot table" {
|
||||
$path = "$env:TEMP\Test.xlsx"
|
||||
#Catch warning
|
||||
$warnVar = $null
|
||||
#Test Append with no existing sheet. Test adding a named pivot table from a command line parameter
|
||||
get-process | Select-Object -first 10 -Property Name,cpu,pm,handles,company | export-excel -StartRow 3 -StartColumn 3 -AutoFilter -AutoNameRange -BoldTopRow -IncludePivotTable -PivotRows Company -PivotData PM -PivotTableName 'PTOffset' -Path $path -WorkSheetname withOffset -append
|
||||
get-process | Select-Object -last 10 -Property Name,cpu,pm,handles,company | export-excel -StartRow 3 -StartColumn 3 -AutoFilter -AutoNameRange -BoldTopRow -IncludePivotTable -PivotRows Company -PivotData PM -PivotTableName 'PTOffset' -Path $path -WorkSheetname withOffset -append -WarningAction SilentlyContinue -WarningVariable warnvar
|
||||
$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
|
||||
$dataWs.Cells[3,3].Value | Should not beNullOrEmpty
|
||||
$dataWs.Cells[3,3].Style.Font.Bold | Should be $true
|
||||
$dataWs.Dimension.End.Row | Should be 23
|
||||
$dataWs.names[0].end.row | Should be 23
|
||||
$dataWs.names[0].name | Should be 'Name'
|
||||
$dataWs.names.Count | Should be 6
|
||||
$dataWs.cells[$dataws.Dimension].AutoFilter | Should be true
|
||||
$pt.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref |
|
||||
Should be "C3:G23"
|
||||
}
|
||||
it "Generated a message on extending the Pivot table " {
|
||||
$warnVar | Should not beNullOrEmpty
|
||||
}
|
||||
}
|
||||
|
||||
Context "#Example 11 # Create and append with title, inc ranges and Pivot table" {
|
||||
$path = "$env:TEMP\Test.xlsx"
|
||||
$ptDef = [ordered]@{}
|
||||
$ptDef += New-PivotTableDefinition -PivotTableName "PT1" -SourceWorkSheet 'Sheet1' -PivotRows "Status" -PivotData @{'Status' = 'Count'} -PivotFilter "StartType" -IncludePivotChart -ChartType BarClustered3D -ChartTitle "Services by status" -ChartHeight 512 -ChartWidth 768 -ChartRow 10 -ChartColumn 0 -NoLegend
|
||||
$ptDef += New-PivotTableDefinition -PivotTableName "PT2" -SourceWorkSheet 'Sheet2' -PivotRows "Company" -PivotData @{'Company' = 'Count'} -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'
|
||||
}
|
||||
Remove-Item -Path $path
|
||||
#Catch warning
|
||||
$warnvar = $null
|
||||
Get-Service | Select-Object -Property Status, Name, DisplayName, StartType | Export-Excel -Path $path -AutoSize -TableName "All Services" -TableStyle Medium1 -WarningAction SilentlyContinue -WarningVariable warnvar
|
||||
Get-Process | Select-Object -Property Name, Company, Handles, CPU, VM | Export-Excel -Path $path -AutoSize -WorkSheetname 'sheet2' -TableName "Processes" -TableStyle Light1 -Title "Processes" -TitleFillPattern Solid -TitleBackgroundColor AliceBlue -TitleBold -TitleSize 22 -PivotTableDefinition $ptDef
|
||||
$Excel = Open-ExcelPackage $path
|
||||
$ws1 = $Excel.Workbook.Worksheets["Sheet1"]
|
||||
$ws2 = $Excel.Workbook.Worksheets["Sheet2"]
|
||||
|
||||
|
||||
it "Set Column widths (with autosize) " {
|
||||
$ws1.Column(2).Width | Should not be $ws1.DefaultColWidth
|
||||
$ws2.Column(1).width | Should not be $ws2.DefaultColWidth
|
||||
}
|
||||
|
||||
it "Added tables to both sheets (handling illegal chars) and a title in sheet 2 " {
|
||||
$warnvar.count | Should be 1
|
||||
$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 correct pivot tables and charts from the definitions. " {
|
||||
|
||||
$PT1.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref |
|
||||
Should be ("A1:" + $ws1.Dimension.End.Address)
|
||||
$PT2.CacheDefinition.CacheDefinitionXml.pivotCacheDefinition.cacheSource.worksheetSource.ref |
|
||||
Should be ("A2:" + $ws2.Dimension.End.Address) #Title in row 1
|
||||
|
||||
$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'
|
||||
$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. " {
|
||||
$path = "$env:TEMP\Test.xlsx"
|
||||
Remove-Item $path
|
||||
$excel = Get-Process | Select-Object -Property Name,Company,Handles,CPU,PM,NPM,WS | Export-Excel -Path $path -ClearSheet -WorkSheetname "Processes" -FreezeTopRowFirstColumn -PassThru
|
||||
$sheet = $excel.Workbook.Worksheets["Processes"]
|
||||
$sheet.Column(1) | Set-Format -Bold -AutoFit
|
||||
$sheet.Column(2) | Set-Format -Width 29 -WrapText
|
||||
$sheet.Column(3) | Set-Format -HorizontalAlignment Right -NFormat "#,###"
|
||||
Set-Format -Address $sheet.Cells["E1:H1048576"] -HorizontalAlignment Right -NFormat "#,###"
|
||||
Set-Format -Address $sheet.Column(4) -HorizontalAlignment Right -NFormat "#,##0.0" -Bold
|
||||
Set-Format -Address $sheet.Row(1) -Bold -HorizontalAlignment Center
|
||||
Add-ConditionalFormatting -WorkSheet $sheet -Range "D2:D1048576" -DataBarColor Red
|
||||
Add-ConditionalFormatting -WorkSheet $sheet -Range "G2:G1048576" -RuleType GreaterThan -ConditionValue "104857600" -ForeGroundColor Red
|
||||
foreach ($c in 5..9) {Set-Format $sheet.Column($c) -AutoFit }
|
||||
Add-PivotTable -PivotTableName "PT_Procs" -ExcelPackage $excel -SourceWorkSheet "Processes" -PivotRows Company -PivotData @{'Name'='Count'} -IncludePivotChart -ChartType ColumnClustered -NoLegend
|
||||
Close-ExcelPackage $excel
|
||||
|
||||
$excel = Open-ExcelPackage $path
|
||||
$sheet = $excel.Workbook.Worksheets["Processes"]
|
||||
|
||||
it "Applied the formating" {
|
||||
$sheet | should not beNullOrEmpty
|
||||
$sheet.Column(1).wdith | should not be $sheet.DefaultColWidth
|
||||
$sheet.Column(7).wdith | should not be $sheet.DefaultColWidth
|
||||
$sheet.Column(1).style.font.bold | should be $true
|
||||
$sheet.Column(2).style.wraptext | should be $true
|
||||
$sheet.Column(2).width | should be 29
|
||||
$sheet.Column(3).style.horizontalalignment | should be 'right'
|
||||
$sheet.Column(4).style.horizontalalignment | should be 'right'
|
||||
$sheet.Cells["A1"].Style.HorizontalAlignment | should be 'Center'
|
||||
$sheet.Cells['E2'].Style.HorizontalAlignment | should be 'right'
|
||||
$sheet.Cells['A1'].Style.Font.Bold | should be $true
|
||||
$sheet.Cells['D2'].Style.Font.Bold | should be $true
|
||||
$sheet.Cells['E2'].style.numberformat.format | should be '#,###'
|
||||
$sheet.Column(3).style.numberformat.format | should be '#,###'
|
||||
$sheet.Column(4).style.numberformat.format | should be '#,##0.0'
|
||||
$sheet.ConditionalFormatting.Count | should be 2
|
||||
$sheet.ConditionalFormatting[0].type | should be 'Databar'
|
||||
$sheet.ConditionalFormatting[0].Color.name | should be 'ffff0000'
|
||||
$sheet.ConditionalFormatting[0].Address.Address | should be 'D2:D1048576'
|
||||
$sheet.ConditionalFormatting[1].type | should be 'GreaterThan'
|
||||
$sheet.ConditionalFormatting[1].Formula | should be '104857600'
|
||||
$sheet.ConditionalFormatting[1].Style.Font.Color.Color.Name | should be 'ffff0000'
|
||||
}
|
||||
it "Froze the panes" {
|
||||
$sheet.view.Panes.Count | should be 3
|
||||
}
|
||||
$ptsheet1 = $Excel.Workbook.Worksheets["Pt_procs"]
|
||||
|
||||
it "Created the pivot table" {
|
||||
$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
|
||||
}
|
||||
}
|
||||
|
||||
## To do
|
||||
## More pivot options & other FreezePanes settings ?
|
||||
## Charts
|
||||
## Style script block
|
||||
## Rezip ?
|
||||
|
||||
}
|
||||
@@ -465,7 +465,7 @@
|
||||
#Write-Verbose "Cell '$Row`:$ColumnIndex' header '$Name' add value '$_' as formula"
|
||||
break
|
||||
}
|
||||
{ $_ -is [Uri] } {
|
||||
{ [System.Uri]::IsWellFormedUriString($_ , [System.UriKind]::Absolute) } {
|
||||
# Save a hyperlink
|
||||
$TargetCell.Value = $_.AbsoluteUri
|
||||
$TargetCell.HyperLink = $_
|
||||
@@ -484,7 +484,8 @@
|
||||
Default {
|
||||
#Save a value as a number if possible
|
||||
$number = $null
|
||||
if ( [Double]::TryParse([String]$_, [System.Globalization.NumberStyles]::Any, [System.Globalization.NumberFormatInfo]::CurrentInfo, [Ref]$number)) {
|
||||
if (($NoNumberConversion -NotContains $Name) -and ($NoNumberConversion -ne '*') -and
|
||||
[Double]::TryParse([String]$_, [System.Globalization.NumberStyles]::Any, [System.Globalization.NumberFormatInfo]::CurrentInfo, [Ref]$number)) {
|
||||
# as simpler version using [Double]::TryParse( $_ , [ref]$number)) was found to cause problems reverted back to the longer version
|
||||
$TargetCell.Value = $number
|
||||
if ($setNumformat) {$targetCell.Style.Numberformat.Format = $Numberformat }
|
||||
@@ -708,7 +709,7 @@
|
||||
#if the table exists, update it.
|
||||
if ($ws.Tables[$TableName]) {
|
||||
$ws.Tables[$TableName].TableXml.table.ref = $dataRange
|
||||
$ws.Tables[$TableName].TableStyle = $TableStyle
|
||||
$ws.Tables[$TableName].TableStyle = $TableStyle
|
||||
}
|
||||
else {
|
||||
$tbl = $ws.Tables.Add($ws.Cells[$dataRange], $TableName)
|
||||
@@ -743,36 +744,35 @@
|
||||
$params = @{
|
||||
"SourceRange" = $dataRange
|
||||
}
|
||||
if ($PivotTableName) {$params.PivotTableName = $PivotTableName}
|
||||
else {$params.PivotTableName = $WorkSheetname + 'PivotTable'}
|
||||
if ($PivotFilter) {$params.PivotFilter = $PivotFilter}
|
||||
if ($PivotRows) {$params.PivotRows = $PivotRows}
|
||||
if ($PivotColumns) {$Params.PivotColumns = $PivotColumns}
|
||||
if ($PivotData) {$Params.PivotData = $PivotData}
|
||||
if ($NoTotalsInPivot) {$params.NoTotalsInPivot = $true}
|
||||
if ($PivotTableName) {$params.PivotTableName = $PivotTableName}
|
||||
else {$params.PivotTableName = $WorkSheetname + 'PivotTable'}
|
||||
if ($PivotFilter) {$params.PivotFilter = $PivotFilter}
|
||||
if ($PivotRows) {$params.PivotRows = $PivotRows}
|
||||
if ($PivotColumns) {$Params.PivotColumns = $PivotColumns}
|
||||
if ($PivotData) {$Params.PivotData = $PivotData}
|
||||
if ($NoTotalsInPivot) {$params.NoTotalsInPivot = $true}
|
||||
if ($PivotDataToColumn) {$params.PivotDataToColumn = $true}
|
||||
if ($IncludePivotChart) {
|
||||
$params.IncludePivotChart = $true
|
||||
$Params.ChartType = $ChartType
|
||||
if ($ShowCategory) {$params.ShowCategory = $true}
|
||||
if ($ShowPercent) {$params.ShowPercent = $true}
|
||||
if ($NoLegend) {$params.NoLegend = $true}
|
||||
$params.IncludePivotChart = $true
|
||||
$Params.ChartType = $ChartType
|
||||
if ($ShowCategory) {$params.ShowCategory = $true}
|
||||
if ($ShowPercent) {$params.ShowPercent = $true}
|
||||
if ($NoLegend) {$params.NoLegend = $true}
|
||||
}
|
||||
Add-PivotTable -ExcelPackage $pkg -SourceWorkSheet $ws @params
|
||||
}
|
||||
|
||||
try {
|
||||
if ($FreezeTopRow) {
|
||||
$ws.View.FreezePanes(2, 1)
|
||||
Write-Verbose -Message "Froze top row"
|
||||
}
|
||||
|
||||
if ($FreezeTopRowFirstColumn) {
|
||||
#Allow single switch or two seperate ones.
|
||||
if ($FreezeTopRowFirstColumn -or ($FreezeTopRow -and $FreezeFirstColumn)) {
|
||||
$ws.View.FreezePanes(2, 2)
|
||||
Write-Verbose -Message "Froze top row and first column"
|
||||
}
|
||||
|
||||
if ($FreezeFirstColumn) {
|
||||
elseif ($FreezeTopRow) {
|
||||
$ws.View.FreezePanes(2, 1)
|
||||
Write-Verbose -Message "Froze top row"
|
||||
}
|
||||
elseif ($FreezeFirstColumn) {
|
||||
$ws.View.FreezePanes(1, 2)
|
||||
Write-Verbose -Message "Froze first column"
|
||||
}
|
||||
@@ -791,8 +791,8 @@
|
||||
}
|
||||
catch {Write-Warning -Message "Failed adding Freezing the panes in worksheet '$WorkSheetname': $_"}
|
||||
|
||||
if ($BoldTopRow) {
|
||||
try {
|
||||
if ($BoldTopRow) { #it sets bold as far as there are populated cells: for whole row could do $ws.row($x).style.font.bold = $true
|
||||
try {
|
||||
if ($Title) {
|
||||
$range = $ws.Dimension.Address -replace '\d+', ($StartRow + 1)
|
||||
}
|
||||
@@ -859,7 +859,7 @@
|
||||
|
||||
if ($PassThru) { $pkg }
|
||||
else {
|
||||
if ($ReturnRange) {$ws.Dimension.Address }
|
||||
if ($ReturnRange) {$dataRange }
|
||||
|
||||
$pkg.Save()
|
||||
Write-Verbose -Message "Saved workbook $($pkg.File)"
|
||||
|
||||
@@ -37,9 +37,11 @@
|
||||
param (
|
||||
# Path to a new or existing .XLSX file.
|
||||
[Parameter(ParameterSetName = "Default", Position = 0)]
|
||||
[Parameter(ParameterSetName = "Table" , Position = 0)]
|
||||
[String]$Path ,
|
||||
# An object representing an Excel Package - usually this is returned by specifying -Passthru allowing multiple commands to work on the same Workbook without saving and reloading each time.
|
||||
[Parameter(Mandatory = $true, ParameterSetName = "Package")]
|
||||
[Parameter(Mandatory = $true, ParameterSetName = "PackageDefault")]
|
||||
[Parameter(Mandatory = $true, ParameterSetName = "PackageTable")]
|
||||
[OfficeOpenXml.ExcelPackage]$ExcelPackage,
|
||||
# The name of a sheet within the workbook where the other sheets will be joined together - "Combined" by default.
|
||||
$WorkSheetName = 'Combined',
|
||||
@@ -62,6 +64,8 @@
|
||||
# Freezes panes at specified coordinates (in the form RowNumber , ColumnNumber).
|
||||
[Int[]]$FreezePane,
|
||||
#Enables the 'Filter' in Excel on the complete header row. So users can easily sort, filter and/or search the data in the select column from within Excel.
|
||||
[Parameter(ParameterSetName = 'Default')]
|
||||
[Parameter(ParameterSetName = 'PackageDefault')]
|
||||
[Switch]$AutoFilter,
|
||||
#Makes the top Row boldface.
|
||||
[Switch]$BoldTopRow,
|
||||
@@ -77,10 +81,36 @@
|
||||
[Switch]$TitleBold,
|
||||
#Sets the point size for the title.
|
||||
[Int]$TitleSize = 22,
|
||||
# Hashtable(s) with Sheet PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values to specify a definition for one or more pivot table(s).
|
||||
#Hashtable(s) with Sheet PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values to specify a definition for one or more pivot table(s).
|
||||
[Hashtable]$PivotTableDefinition,
|
||||
# A hashtable containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-pivot] charts.
|
||||
#A hashtable containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-pivot] charts.
|
||||
[Object[]]$ExcelChartDefinition,
|
||||
[Object[]]$ConditionalFormat,
|
||||
#Applies a 'Conditional formatting rule' in Excel on all the cells. When specific conditions are met a rule is triggered.
|
||||
[Object[]]$ConditionalText,
|
||||
#Makes each column a named range.
|
||||
[switch]$AutoNameRange,
|
||||
#Makes the data in the worksheet a named range.
|
||||
[ValidateScript( {
|
||||
if (-not $_) { throw 'RangeName is null or empty.' }
|
||||
elseif ($_[0] -notmatch '[a-z]') { throw 'RangeName starts with an invalid character.' }
|
||||
else { $true }
|
||||
})]
|
||||
[String]$RangeName,
|
||||
[ValidateScript( {
|
||||
if (-not $_) { throw 'Tablename is null or empty.' }
|
||||
elseif ($_[0] -notmatch '[a-z]') { throw 'Tablename starts with an invalid character.' }
|
||||
else { $true }
|
||||
})]
|
||||
[Parameter(ParameterSetName = 'Table' , Mandatory = $true)]
|
||||
[Parameter(ParameterSetName = 'PackageTable' , Mandatory = $true)]
|
||||
# Makes the data in the worksheet a table with a name applies a style to it. Name must not contain spaces.
|
||||
[String]$TableName,
|
||||
[Parameter(ParameterSetName = 'Table')]
|
||||
[Parameter(ParameterSetName = 'PackageTable')]
|
||||
[OfficeOpenXml.Table.TableStyles]$TableStyle = 'Medium6',
|
||||
#Selects the style for the named table - defaults to 'Medium6'.
|
||||
[switch]$ReturnRange,
|
||||
#Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first.
|
||||
[switch]$Show,
|
||||
#If specified, an object representing the unsaved Excel package will be returned, it then needs to be saved.
|
||||
@@ -89,6 +119,7 @@
|
||||
#region get target worksheet, select it and move it to the end.
|
||||
if ($Path -and -not $ExcelPackage) {$ExcelPackage = Open-ExcelPackage -path $Path }
|
||||
$destinationSheet = Add-WorkSheet -ExcelPackage $ExcelPackage -WorkSheetname $WorkSheetName -ClearSheet:$Clearsheet
|
||||
foreach ($w in $ExcelPackage.Workbook.Worksheets) {$w.view.TabSelected = $false}
|
||||
$destinationSheet.View.TabSelected = $true
|
||||
$ExcelPackage.Workbook.Worksheets.MoveToEnd($WorkSheetName)
|
||||
#row to insert at will be 1 on a blank sheet and lastrow + 1 on populated one
|
||||
@@ -152,9 +183,10 @@
|
||||
'Path', 'Clearsheet', 'NoHeader', 'FromLabel', 'LabelBlocks', 'HideSource',
|
||||
'Title', 'TitleFillPattern', 'TitleBackgroundColor', 'TitleBold', 'TitleSize' | ForEach-Object {[void]$params.Remove($_)}
|
||||
if ($params.Keys.Count) {
|
||||
if ($Title) { $params.StartRow = 2}
|
||||
$params.WorkSheetName = $WorkSheetName
|
||||
$params.ExcelPackage = $ExcelPackage
|
||||
Export-Excel @Params
|
||||
Export-Excel @Params
|
||||
}
|
||||
else {
|
||||
Close-ExcelPackage -ExcelPackage $ExcelPackage
|
||||
|
||||
846
README.md
846
README.md
@@ -1,4 +1,3 @@
|
||||
<<<<<<< HEAD
|
||||
PowerShell Import-Excel
|
||||
-
|
||||
|
||||
@@ -32,16 +31,17 @@ To install to your personal modules folder (e.g. ~\Documents\WindowsPowerShell\M
|
||||
iex (new-object System.Net.WebClient).DownloadString('https://raw.github.com/dfinke/ImportExcel/master/Install.ps1')
|
||||
```
|
||||
|
||||
# What's new to 5th July 18
|
||||
- Moved chart creatation into its own function (Add-Excel chart) within Export-Excel.ps1. Renamed New-Excelchart to New-ExcelChartDefinition to make it clearer that it is not making anything in the workbook (but for compatiblity put an alias of New-ExcelChart in so existing code does not break). Found -Header does nothing, so removed it.
|
||||
- Added paramters for managing Axes and legend
|
||||
# What's new to 6th July 18
|
||||
- Moved chart creatation into its own function (Add-Excel chart) within Export-Excel.ps1. Renamed New-Excelchart to New-ExcelChartDefinition to make it clearer that it is not making anything in the workbook (but for compatiblity put an alias of New-ExcelChart in so existing code does not break). Found that -Header does nothing, so it isn't Add-Excel chart and there is a message that does nothing in New-ExcelChartDefinition .
|
||||
- Added paramters for managing Axes and legend (these are currently in Add-ExcelChart but not new-ExcelChartDefinition)
|
||||
- Fixed a bug introduced into Compare-Worksheet by the change descibed in the June changes below, this meant the font color was only being set in one sheet, when a row was changed. Also found that the PowerShell ISE and shell return Compare-Object resuls in different sequences which broke some tests. Applied a sort to ensure things are in a predictable order. (#375)
|
||||
- Fixed some bad code which had been checked-in in-error and caused adding charts to break. (This was not seen outside Github #377)
|
||||
- Added chart tests to Export-Excel.tests.ps1.
|
||||
- Removed (2) calls to Get-ExcelColumnName
|
||||
- Fixed an issue in Export-Excel where formulas were inserted as strings if "NoNumberConversion" is applied (#374), and made sure formatting is applied to formula cells
|
||||
- Reverted the [double]::tryParse in export excel to the previous way, as the shorter way, although quicker was not behaving correctly with with the number formats in certain regions. (also #374)
|
||||
- Changed Table, Range and AutoRangeNames to apply to whole data area if no data has been inserted OR to inserted data only if it has. (#376)
|
||||
- Reverted the [double]::tryParse in export excel to the previous way, as the shorter way was not behaving correctly with with the number formats in certain regions. (also #374)
|
||||
- Changed Table, Range and AutoRangeNames to apply to whole data area if no data has been inserted OR to inserted data only if it has.(#376) This means that if there are multiple inserts only inserted data is touched, rather than going as far down and/or right as the furthest used cell. Added a test for this.
|
||||
- Added more of the Parameters from Export-Excel to Join-worksheet, join just calls export with these parameters so there is no code behind them (#383)
|
||||
|
||||
# New in June 18
|
||||
- New commands - Diff , Merge and Join
|
||||
@@ -841,837 +841,3 @@ You can also find EPPLus on [Nuget](https://www.nuget.org/packages/EPPlus/).
|
||||
* Using `-IncludePivotTable`, if that pivot table name exists, you'll get an error.
|
||||
* Investigating a solution
|
||||
* *Workaround* delete the Excel file first, then do the export
|
||||
=======
|
||||
PowerShell Import-Excel
|
||||
-
|
||||
|
||||
Install from the [PowerShell Gallery](https://www.powershellgallery.com/packages/ImportExcel/).
|
||||
|
||||
This PowerShell Module allows you to read and write Excel files without installing Microsoft Excel on your system. No need to bother with the cumbersome Excel COM-object. Creating Tables, Pivot Tables, Charts and much more has just become a lot easier.
|
||||
|
||||

|
||||
|
||||
# How to Vidoes
|
||||
* [PowerShell Excel Module - ImportExcel](https://www.youtube.com/watch?v=U3Ne_yX4tYo&list=PL5uoqS92stXioZw-u-ze_NtvSo0k0K0kq)
|
||||
|
||||
Installation
|
||||
-
|
||||
#### [PowerShell V5](https://www.microsoft.com/en-us/download/details.aspx?id=50395) and Later
|
||||
You can install the `ImportExcel` module directly from the PowerShell Gallery
|
||||
|
||||
* [Recommended] Install to your personal PowerShell Modules folder
|
||||
```PowerShell
|
||||
Install-Module ImportExcel -scope CurrentUser
|
||||
```
|
||||
* [Requires Elevation] Install for Everyone (computer PowerShell Modules folder)
|
||||
```PowerShell
|
||||
Install-Module ImportExcel
|
||||
```
|
||||
|
||||
#### PowerShell V4 and Earlier
|
||||
To install to your personal modules folder (e.g. ~\Documents\WindowsPowerShell\Modules), run:
|
||||
|
||||
```PowerShell
|
||||
iex (new-object System.Net.WebClient).DownloadString('https://raw.github.com/dfinke/ImportExcel/master/Install.ps1')
|
||||
```
|
||||
|
||||
# What's new
|
||||
|
||||
- New commands - Diff , Merge and Join
|
||||
- `Compare-Worksheet` (introduced in 5.0) uses the built in `Compare-object` command, to output a command-line DIFF and/or colour the worksheet to show differences. For example, if my sheets are Windows services the *extra* rows or rows where the startup status has changed get highlighted
|
||||
- `Merge-Worksheet` (also introduced in 5.0) joins two lumps, side by highlighting the differences. So now I can have server A's services and Server Bs Services on the same page. I figured out a way to do multiple sheets. So I can have Server A,B,C,D on one page :-) that is `Merge-MultpleSheets`
|
||||
For this release I've fixed heaven only knows how many typos and proof reading errors in the help for these two, but the code is unchanged - although correcting the spelling of Merge-MultipleSheets is potentially a breaking change (and it is still plural!)
|
||||
also fixed a bug in compare worksheet where color might not be applied correctly when the worksheets came from different files and had different name.
|
||||
- `Join-Worksheet` is **new** for ths release. At it's simplest it copies all the data in Worksheet A to the end of Worksheet B
|
||||
- Add-Worksheet
|
||||
- I have moved this from ImportExcel.psm1 to ExportExcel.ps1 and it now can move a new worksheet to the right place, and can copy an existing worksheet (from the same or a different workbook) to a new one, and I set the Set return-type to aid intellisense
|
||||
- New-PivotTableDefinition
|
||||
- Now Supports `-PivotFilter` and `-PivotDataToColumn`, `-ChartHeight/width` `-ChartRow/Column`, `-ChartRow/ColumnPixelOffset` parameters
|
||||
- Set-Format
|
||||
- Fixed a bug where the `-address` parameter had to be named, although the examples in `export-excel` help showed it working by position (which works now. )
|
||||
- Export-Excel
|
||||
- I've done some re-factoring
|
||||
1. I "flattened out" small "called-once" functions , add-title, convert-toNumber and Stop-ExcelProcess.
|
||||
2. It now uses Add-Worksheet, Open-ExcelPackage and Add-ConditionalFormat instead of duplicating their functionality.
|
||||
3. I've moved the PivotTable functionality (which was doubled up) out to a new function "Add-PivotTable" which supports some extra parameters PivotFilter and PivotDataToColumn, ChartHeight/width ChartRow/Column, ChartRow/ColumnPixelOffsets.
|
||||
4. I've made the try{} catch{} blocks cover smaller blocks of code to give a better idea where a failure happend, some of these now Warn instead of throwing - I'd rather save the data with warnings than throw it away because we can't add a chart. Along with this I've added some extra write-verbose messages
|
||||
- Bad column-names specified for Pivots now generate warnings instead of throwing.
|
||||
- Fixed issues when pivottables / charts already exist and an export tries to create them again.
|
||||
- Fixed issue where AutoNamedRange, NamedRange, and TableName do not work when appending to a sheet which already contains the range(s) / table
|
||||
- Fixed issue where AutoNamedRange may try to create ranges with an illegal name.
|
||||
- Added check for illegal characters in RangeName or Table Name (replace them with "_"), changed tablename validation to allow spaces and applied same validation to RangeName
|
||||
- Fixed a bug where BoldTopRow is always bolds row 1 even if the export is told to start at a lower row.
|
||||
- Fixed a bug where titles throw pivot table creation out of alignment.
|
||||
- Fixed a bug where Append can overwrite the last rows of data if the initial export had blank rows at the top of the sheet.
|
||||
- Removed the need to specify a fill type when specifying a title background color
|
||||
- Added MoveToStart, MoveToEnd, MoveBefore and MoveAfter Parameters - these go straight through to Add worksheet
|
||||
- Added "NoScriptOrAliasProperties" "DisplayPropertySet" switches (names subject to change) - combined with ExcludeProperty these are a quick way to reduce the data exported (and speed things up)
|
||||
- Added PivotTableName Switch (in line with 5.0.1 release)
|
||||
- Add-CellValue now understands URI item properties. If a property is of type URI it is created as a hyperlink to speed up Add-CellValue
|
||||
- Commented out the write verbose statements even if verbose is silenced they cause a significiant performance impact and if it's on they will cause a flood of messages.
|
||||
- Re-ordered the choices in the switch and added an option to say "If it is numeric already post it as is"
|
||||
- Added an option to only set the number format if doesn't match the default for the sheet.
|
||||
-Export-Excel Pester Tests
|
||||
- I have converted examples 1-9, 11 and 13 from Export-Excel help into tests and have added some additional tests, and extra parameters to the example command to ge better test coverage. The test so far has 184 "should" conditions grouped as 58 "IT" statements; but is still a work in progress.
|
||||
-Compare-Worksheet pester tests
|
||||
|
||||
---
|
||||
|
||||
|
||||
- [James O'Neill](https://twitter.com/jamesoneill) added `Compare-Worksheet`
|
||||
- Compares two worksheets with the same name in different files.
|
||||
|
||||
#### 4/22/2018
|
||||
Thanks to the community yet again
|
||||
- [ili101](https://github.com/ili101) for fixes and features
|
||||
- Removed `[PSPlot]` as OutputType. Fixes it throwing an error
|
||||
- [Nasir Zubair](https://github.com/nzubair) added `ConvertEmptyStringsToNull` to the function `ConvertFrom-ExcelToSQLInsert`
|
||||
- If specified, cells without any data are replaced with NULL, instead of an empty string. This is to address behviors in certain DBMS where an empty string is insert as 0 for INT column, instead of a NULL value.
|
||||
|
||||
|
||||
#### 4/10/2018
|
||||
-New parameter `-ReZip`. It ReZips the xlsx so it can be imported to PowerBI
|
||||
|
||||
Thanks to [Justin Grote](https://github.com/JustinGrote) for finding and fixing the error that Excel files created do not import to PowerBI online. Plus, thank you to [CrashM](https://github.com/CrashM) for confirming the fix.
|
||||
|
||||
Super helpful!
|
||||
|
||||
#### 3/31/2018
|
||||
- Updated `Set-Format`
|
||||
* Added parameters to set borders for cells, including top, bottm, left and right
|
||||
* Added parameters to set `value` and `formula`
|
||||
|
||||
```powershell
|
||||
$data = @"
|
||||
From,To,RDollars,RPercent,MDollars,MPercent,Revenue,Margin
|
||||
Atlanta,New York,3602000,.0809,955000,.09,245,65
|
||||
New York,Washington,4674000,.105,336000,.03,222,16
|
||||
Chicago,New York,4674000,.0804,1536000,.14,550,43
|
||||
New York,Philadelphia,12180000,.1427,-716000,-.07,321,-25
|
||||
New York,San Francisco,3221000,.0629,1088000,.04,436,21
|
||||
New York,Phoneix,2782000,.0723,467000,.10,674,33
|
||||
"@
|
||||
```
|
||||
|
||||

|
||||
|
||||
|
||||
- Added `-PivotFilter` parameter, allows you to set up a filter so you can drill down into a subset of the overall dataset.
|
||||
|
||||
```powershell
|
||||
$data =@"
|
||||
Region,Area,Product,Units,Cost
|
||||
North,A1,Apple,100,.5
|
||||
South,A2,Pear,120,1.5
|
||||
East,A3,Grape,140,2.5
|
||||
West,A4,Banana,160,3.5
|
||||
North,A1,Pear,120,1.5
|
||||
North,A1,Grape,140,2.5
|
||||
"@
|
||||
```
|
||||
|
||||

|
||||
|
||||
|
||||
#### 3/14/2018
|
||||
- Thank you to [James O'Neill](https://twitter.com/jamesoneill), fixed bugs with ChangeDatabase parameter which would prevent it working
|
||||
|
||||
####
|
||||
* Added -Force to New-Alias
|
||||
* Add example to set the background color of a column
|
||||
* Supports excluding Row Grand Totals for PivotTables
|
||||
* Allow xlsm files to be read
|
||||
* Fix `Set-Column.ps1`, `Set-Row.ps1`, `SetFormat.ps1`, `formatting.ps1` **$falsee** and **$BorderRound**
|
||||
#### 1/1/2018
|
||||
* Added switch `[Switch]$NoTotalsInPivot`. Allows hiding of the row totals in the pivot table.
|
||||
Thanks you to [jameseholt](https://github.com/jameseholt) for the request.
|
||||
|
||||
```powershell
|
||||
get-process | where Company | select Company, Handles, WorkingSet |
|
||||
export-excel C:\temp\testColumnGrand.xlsx `
|
||||
-Show -ClearSheet -KillExcel `
|
||||
-IncludePivotTable -PivotRows Company -PivotData @{"Handles"="average"} -NoTotalsInPivot
|
||||
```
|
||||
|
||||
* Fixed when using certain a `ChartType` for the Pivot Table Chart, would throw an error
|
||||
* Fixed - when you specify a file, and the directory does not exit, it now creates it
|
||||
|
||||
#### 11/23/2017
|
||||
More great additions and thanks to [James O'Neill](https://twitter.com/jamesoneill)
|
||||
|
||||
* Added `Convert-XlRangeToImage` Gets the specified part of an Excel file and exports it as an image
|
||||
* Fixed a typo in the message at line 373.
|
||||
* Now catch an attempt to both clear the sheet and append to it.
|
||||
* Fixed some issues when appending to sheets where the header isn't in row 1 or the data doesn't start in column 1.
|
||||
* Added support for more settings when creating a pivot chart.
|
||||
* Corrected a typo PivotTableName was PivtoTableName in definition of New-PivotTableDefinition
|
||||
* Add-ConditionalFormat and Set-Format added to the parameters so each has the choice of working more like the other.
|
||||
* Added Set-Row and Set-Column - fill a formula down or across.
|
||||
* Added Send-SQLDataToExcel. Insert a rowset and then call Export-Excel for ranges, charts, pivots etc
|
||||
|
||||
#### 10/30/2017
|
||||
Huge thanks to [James O'Neill](https://twitter.com/jamesoneill). PowerShell aficionado. He always brings a flare when working with PowerShell. This is no exception.
|
||||
|
||||
(Check out the examples `help Export-Excel -Examples`)
|
||||
|
||||
* New parameter `Package` allows an ExcelPackage object returned by `-passThru` to be passed in
|
||||
* New parameter `ExcludeProperty` to remove unwanted properties without needing to go through `select-object`
|
||||
* New parameter `Append` code to read the existing headers and move the insertion point below the current data
|
||||
* New parameter `ClearSheet` which removes the worksheet and any past data
|
||||
|
||||
* Remove any existing Pivot table before trying to [re]create it
|
||||
* Check for inserting a pivot table so if `-InsertPivotChart` is specified it implies `-InsertPivotTable`
|
||||
|
||||
(Check out the examples `help Export-Excel -Examples`)
|
||||
|
||||
* New function `Export-Charts` (requires Excel to be installed) - Export Excel charts out as JPG files
|
||||
* New function `Add-ConditionalFormatting` Adds contitional formatting to worksheet
|
||||
* New function `Set-Format` Applies Number, font, alignment and colour formatting to a range of Excel Cells
|
||||
* `ColorCompletion` an argument completer for `Colors` for params across functions
|
||||
|
||||
I also worked out the parameters so you can do this, which is the same as passing `-Now`. It creates an Excel file name for you, does an auto fit and sets up filters.
|
||||
|
||||
`ps | select Company, Handles | Export-Excel`
|
||||
|
||||
#### 10/13/2017
|
||||
Added `New-PivotTableDefinition`. You can create and wire up a PivotTable to a WorkSheet. You can also create as many PivotTable Worksheets to point a one Worksheet. Or, you create many Worksheets and many corresponding PivotTable Worksheets.
|
||||
|
||||
Here you can create a WorkSheet with the data from `Get-Service`. Then create four PivotTables, pointing to the data each pivoting on a differnt dimension and showing a differnet chart
|
||||
|
||||
```powershell
|
||||
$base = @{
|
||||
SourceWorkSheet = 'gsv'
|
||||
PivotData = @{'Status' = 'count'}
|
||||
IncludePivotChart = $true
|
||||
}
|
||||
|
||||
$ptd = [ordered]@{}
|
||||
|
||||
$ptd += New-PivotTableDefinition @base servicetype -PivotRows servicetype -ChartType Area3D
|
||||
$ptd += New-PivotTableDefinition @base status -PivotRows status -ChartType PieExploded3D
|
||||
$ptd += New-PivotTableDefinition @base starttype -PivotRows starttype -ChartType BarClustered3D
|
||||
$ptd += New-PivotTableDefinition @base canstop -PivotRows canstop -ChartType ConeColStacked
|
||||
|
||||
Get-Service | Export-Excel -path $file -WorkSheetname gsv -Show -PivotTableDefinition $ptd
|
||||
```
|
||||
|
||||
#### 10/4/2017
|
||||
Thanks to https://github.com/ili101 :
|
||||
- Fix Bug, Unable to find type [PSPlot]
|
||||
- Fix Bug, AutoFilter with TableName create corrupted Excel file.
|
||||
|
||||
#### 10/2/2017
|
||||
Thanks to [Jeremy Brun](https://github.com/jeremytbrun)
|
||||
Fixed issues related to use of -Title parameter combined with column formatting parameters.
|
||||
- [Issue #182](https://github.com/dfinke/ImportExcel/issues/182)
|
||||
- [Issue #89](https://github.com/dfinke/ImportExcel/issues/89)
|
||||
|
||||
#### 9/28/2017 (Version 4.0.1)
|
||||
- Added a new parameter called `Password` to import password protected files
|
||||
- Added even more `Pester` tests for a more robust and bug free module
|
||||
- Renamed parameter 'TopRow' to 'StartRow'
|
||||
This allows us to be more concise when new parameters ('StartColumn', ..) will be added in the future Your code will not break after the update, because we added an alias for backward compatibility
|
||||
|
||||
Special thanks to [robinmalik](https://github.com/robinmalik) for providing us with [the code](https://github.com/dfinke/ImportExcel/issues/174) to implement this new feature. A high five to [DarkLite1](https://github.com/DarkLite1) for the implementation.
|
||||
|
||||
#### 9/12/2017 (Version 4.0.0)
|
||||
|
||||
Super thanks and hat tip to [DarkLite1](https://github.com/DarkLite1). There is now a new and improved `Import-Excel`, not only in functionality, but also improved readability, examples and more. Not only that, he's been running it in production in his company for a number of weeks!
|
||||
|
||||
*Added* `Update-FirstObjectProperties` Updates the first object to contain all the properties of the object with the most properties in the array. Check out the help.
|
||||
|
||||
|
||||
***Breaking Changes***: Due to a big portion of the code that is rewritten some slightly different behavior can be expected from the `Import-Excel` function. This is especially true for importing empty Excel files with or without using the `TopRow` parameter. To make sure that your code is still valid, please check the examples in the help or the accompanying `Pester` test file.
|
||||
|
||||
|
||||
Moving forward, we are planning to include automatic testing with the help of `Pester`, `Appveyor` and `Travis`. From now on any changes in the module will have to be accompanied by the corresponding `Pester` tests to avoid breakages of code and functionality. This is in preparation for new features coming down the road.
|
||||
|
||||
#### 7/3/2017
|
||||
Thanks to [Mikkel Nordberg](https://www.linkedin.com/in/mikkelnordberg). He contributed a `ConvertTo-ExcelXlsx`. To use it, Excel needs to be installed. The function converts the older Excel file format ending in `.xls` to the new format ending in `.xlsx`.
|
||||
|
||||
#### 6/15/2017
|
||||
Huge thank you to [DarkLite1](https://github.com/DarkLite1)! Refactoring of code, adding help, adding features, fixing bugs. Specifically this long outstanding one:
|
||||
|
||||
[Export-Excel: Numeric values not correct](https://github.com/dfinke/ImportExcel/issues/168)
|
||||
|
||||
It is fantastic to work with people like `DarkLite1` in the community, to help make the module so much better. A hat to you.
|
||||
|
||||
Another shout out to [Damian Reeves](https://twitter.com/DamReev)! His questions turn into great features. He asked if it was possible to import an Excel worksheet and transform the data into SQL `INSERT` statements. We can now answer that question with a big YES!
|
||||
|
||||
```PowerShell
|
||||
ConvertFrom-ExcelToSQLInsert People .\testSQLGen.xlsx
|
||||
```
|
||||
|
||||
```
|
||||
INSERT INTO People ('First', 'Last', 'The Zip') Values('John', 'Doe', '12345');
|
||||
INSERT INTO People ('First', 'Last', 'The Zip') Values('Jim', 'Doe', '12345');
|
||||
INSERT INTO People ('First', 'Last', 'The Zip') Values('Tom', 'Doe', '12345');
|
||||
INSERT INTO People ('First', 'Last', 'The Zip') Values('Harry', 'Doe', '12345');
|
||||
INSERT INTO People ('First', 'Last', 'The Zip') Values('Jane', 'Doe', '12345');
|
||||
```
|
||||
## Bonus Points
|
||||
Use the underlying `ConvertFrom-ExcelData` function and you can use a scriptblock to format the data however you want.
|
||||
|
||||
```PowerShell
|
||||
ConvertFrom-ExcelData .\testSQLGen.xlsx {
|
||||
param($propertyNames, $record)
|
||||
|
||||
$reportRecord = @()
|
||||
foreach ($pn in $propertyNames) {
|
||||
$reportRecord += "{0}: {1}" -f $pn, $record.$pn
|
||||
}
|
||||
$reportRecord +=""
|
||||
$reportRecord -join "`r`n"
|
||||
}
|
||||
```
|
||||
Generates
|
||||
|
||||
```
|
||||
First: John
|
||||
Last: Doe
|
||||
The Zip: 12345
|
||||
|
||||
First: Jim
|
||||
Last: Doe
|
||||
The Zip: 12345
|
||||
|
||||
First: Tom
|
||||
Last: Doe
|
||||
The Zip: 12345
|
||||
|
||||
First: Harry
|
||||
Last: Doe
|
||||
The Zip: 12345
|
||||
|
||||
First: Jane
|
||||
Last: Doe
|
||||
The Zip: 12345
|
||||
```
|
||||
|
||||
#### 2/2/2017
|
||||
Thank you to [DarkLite1](https://github.com/DarkLite1) for more updates
|
||||
* TableName with parameter validation, throws an error when the TableName:
|
||||
- Starts with something else then a letter
|
||||
- Is NULL or empty
|
||||
- Contains spaces
|
||||
- Numeric parsing now uses `CurrentInfo` to use the system settings
|
||||
|
||||
#### 2/14/2017
|
||||
Big thanks to [DarkLite1](https://github.com/DarkLite1) for some great updates
|
||||
* `-DataOnly` switch added to `Import-Excel`. When used it will only generate objects for rows that contain text values, not for empty rows or columns.
|
||||
|
||||
* `Get-ExcelWorkBookInfo` - retrieves information of an Excel workbook.
|
||||
```
|
||||
Get-ExcelWorkbookInfo .\Test.xlsx
|
||||
|
||||
CorePropertiesXml : #document
|
||||
Title :
|
||||
Subject :
|
||||
Author : Konica Minolta User
|
||||
Comments :
|
||||
Keywords :
|
||||
LastModifiedBy : Bond, James (London) GBR
|
||||
LastPrinted : 2017-01-21T12:36:11Z
|
||||
Created : 17/01/2017 13:51:32
|
||||
Category :
|
||||
Status :
|
||||
ExtendedPropertiesXml : #document
|
||||
Application : Microsoft Excel
|
||||
HyperlinkBase :
|
||||
AppVersion : 14.0300
|
||||
Company : Secret Service
|
||||
Manager :
|
||||
Modified : 10/02/2017 12:45:37
|
||||
CustomPropertiesXml : #document
|
||||
```
|
||||
|
||||
#### 12/22/2016
|
||||
- Added `-Now` switch. This short cuts the process, automatically creating a temp file and enables the `-Show`, `-AutoFilter`, `-AutoSize` switches.
|
||||
|
||||
```PowerShell
|
||||
Get-Process | Select Company, Handles | Export-Excel -Now
|
||||
```
|
||||
|
||||
- Added ScriptBlocks for coloring cells. Check out [Examples](https://github.com/dfinke/ImportExcel/tree/master/Examples/FormatCellStyles)
|
||||
|
||||
```PowerShell
|
||||
Get-Process |
|
||||
Select-Object Company,Handles,PM, NPM|
|
||||
Export-Excel $xlfile -Show -AutoSize -CellStyleSB {
|
||||
param(
|
||||
$workSheet,
|
||||
$totalRows,
|
||||
$lastColumn
|
||||
)
|
||||
|
||||
Set-CellStyle $workSheet 1 $LastColumn Solid Cyan
|
||||
|
||||
foreach($row in (2..$totalRows | Where-Object {$_ % 2 -eq 0})) {
|
||||
Set-CellStyle $workSheet $row $LastColumn Solid Gray
|
||||
}
|
||||
|
||||
foreach($row in (2..$totalRows | Where-Object {$_ % 2 -eq 1})) {
|
||||
Set-CellStyle $workSheet $row $LastColumn Solid LightGray
|
||||
}
|
||||
}
|
||||
```
|
||||

|
||||
|
||||
#### 9/28/2016
|
||||
[Fixed](https://github.com/dfinke/ImportExcel/pull/126) PowerShell 3.0 compatibility. Thanks to [headsphere](https://github.com/headsphere). He used `$obj.PSObject.Methods[$target]` snytax to make it backward compatible. PS v4.0 and later allow `$obj.$target`.
|
||||
|
||||
Thank you to [xelsirko](https://github.com/xelsirko) for fixing - *Import-module importexcel gives version warning if started inside background job*
|
||||
|
||||
#### 8/12/2016
|
||||
[Fixed](https://github.com/dfinke/ImportExcel/issues/115) reading the headers from cells, moved from using `Text` property to `Value` property.
|
||||
|
||||
#### 7/30/2016
|
||||
* Added `Copy-ExcelWorksheet`. Let's you copy a work sheet from one Excel workbook to another.
|
||||
|
||||
#### 7/21/2016
|
||||
* Fixes `Import-Excel` #68
|
||||
|
||||
#### 7/7/2016
|
||||
[Attila Mihalicz](https://github.com/attilamihalicz) fixed two issues
|
||||
|
||||
* Removing extra spaces after the backtick
|
||||
* Uninitialized variable $idx leaks into the pipeline when `-TableName` parameter is used
|
||||
|
||||
Thanks Attila.
|
||||
|
||||
|
||||
#### 7/1/2016
|
||||
* Pushed 2.2.7 fixed resolve path in Get-ExcelSheetInfo
|
||||
* Fixed [Casting Error in Export-Excel](https://github.com/dfinke/ImportExcel/issues/108)
|
||||
* For `Import-Excel` change Resolve-Path to return ProviderPath for use with UNC
|
||||
|
||||
#### 6/01/2016
|
||||
* Added -UseDefaultCredentials to both `Import-Html` and `Get-HtmlTable`
|
||||
* New functions, `Import-UPS` and `Import-USPS`. Pass in a valid tracking # and it scrapes the page for the delivery details
|
||||
|
||||

|
||||
|
||||
#### 4/30/2016
|
||||
Huge thank you to [Willie Möller](https://github.com/W1M0R)
|
||||
|
||||
* He added a version check so the PowerShell Classes don't cause issues for downlevel version of PowerShell
|
||||
* He also contributed the first Pester tests for the module. Super! Check them out, they'll be the way tests will be implemented going forward
|
||||
|
||||
#### 4/18/2016
|
||||
Thanks to [Paul Williams](https://github.com/pauldalewilliams) for this feature. Now data can be transposed to columns for better charting.
|
||||
|
||||
```PowerShell
|
||||
$file = "C:\Temp\ps.xlsx"
|
||||
rm $file -ErrorAction Ignore
|
||||
|
||||
ps |
|
||||
where company |
|
||||
select Company,PagedMemorySize,PeakPagedMemorySize |
|
||||
Export-Excel $file -Show -AutoSize `
|
||||
-IncludePivotTable `
|
||||
-IncludePivotChart `
|
||||
-ChartType ColumnClustered `
|
||||
-PivotRows Company `
|
||||
-PivotData @{PagedMemorySize='sum';PeakPagedMemorySize='sum'}
|
||||
```
|
||||

|
||||
|
||||
|
||||
Add `-PivotDataToColumn`
|
||||
|
||||
```PowerShell
|
||||
$file = "C:\Temp\ps.xlsx"
|
||||
rm $file -ErrorAction Ignore
|
||||
|
||||
ps |
|
||||
where company |
|
||||
select Company,PagedMemorySize,PeakPagedMemorySize |
|
||||
Export-Excel $file -Show -AutoSize `
|
||||
-IncludePivotTable `
|
||||
-IncludePivotChart `
|
||||
-ChartType ColumnClustered `
|
||||
-PivotRows Company `
|
||||
-PivotData @{PagedMemorySize='sum';PeakPagedMemorySize='sum'} `
|
||||
-PivotDataToColumn
|
||||
```
|
||||
And here is the new chart view
|
||||

|
||||
#### 4/7/2016
|
||||
Made more methods fluent
|
||||
```
|
||||
$t=Get-Range 0 5 .2
|
||||
|
||||
$t2=$t|%{$_*$_}
|
||||
$t3=$t|%{$_*$_*$_}
|
||||
|
||||
(New-Plot).
|
||||
Plot($t,$t, $t,$t2, $t,$t3).
|
||||
SetChartPosition("i").
|
||||
SetChartSize(500,500).
|
||||
Title("Hello World").
|
||||
Show()
|
||||
```
|
||||
#### 3/31/2016
|
||||
* Thanks to [redoz](https://github.com/redoz) Multi Series Charts are now working
|
||||
|
||||
Also check out how you can create a table and then with Excel notation, index into the data for charting `"Impressions[A]"`
|
||||
|
||||
```
|
||||
$data = @"
|
||||
A,B,C,Date
|
||||
2,1,1,2016-03-29
|
||||
5,10,1,2016-03-29
|
||||
"@ | ConvertFrom-Csv
|
||||
|
||||
$c = New-ExcelChart -Title Impressions `
|
||||
-ChartType Line -Header "Something" `
|
||||
-XRange "Impressions[Date]" `
|
||||
-YRange @("Impressions[B]","Impressions[A]")
|
||||
|
||||
$data |
|
||||
Export-Excel temp.xlsx -AutoSize -TableName Impressions -Show -ExcelChartDefinition $c
|
||||
```
|
||||

|
||||
|
||||
#### 3/26/2016
|
||||
* Added `NumberFormat` parameter
|
||||
|
||||
```
|
||||
$data |
|
||||
Export-Excel -Path $file -Show -NumberFormat '[Blue]$#,##0.00;[Red]-$#,##0.00'
|
||||
```
|
||||

|
||||
|
||||
|
||||
#### 3/18/2016
|
||||
* Added `Get-Range`, `New-Plot` and Plot Cos example
|
||||
* Updated EPPlus DLL. Allows markers to be changed and colored
|
||||
* Handles and warns if auto name range names are also valid Excel ranges
|
||||
|
||||

|
||||
|
||||
#### 3/7/2016
|
||||
* Added `Header` and `FirstDataRow` for `Import-Html`
|
||||
|
||||
#### 3/2/2016
|
||||
* Added `GreaterThan`, `GreaterThanOrEqual`, `LessThan`, `LessThanOrEqual` to `New-ConditionalText`
|
||||
|
||||
```PowerShell
|
||||
echo 489 668 299 777 860 151 119 497 234 788 |
|
||||
Export-Excel c:\temp\test.xlsx -Show `
|
||||
-ConditionalText (New-ConditionalText -ConditionalType GreaterThan 525)
|
||||
```
|
||||

|
||||
|
||||
#### 2/22/2016
|
||||
* `Import-Html` using Lee Holmes [Extracting Tables from PowerShell’s Invoke-WebRequest](http://www.leeholmes.com/blog/2015/01/05/extracting-tables-from-PowerShells-invoke-webrequest/)
|
||||
|
||||

|
||||
|
||||
#### 2/17/2016
|
||||
* Added Conditional Text types of `Equal` and `NotEqual`
|
||||
* Phone #'s like '+33 011 234 34' will be now be handled correctly
|
||||
|
||||
## Try *PassThru*
|
||||
|
||||
```PowerShell
|
||||
$file = "C:\Temp\passthru.xlsx"
|
||||
rm $file -ErrorAction Ignore
|
||||
|
||||
$xlPkg = $(
|
||||
New-PSItem north 10
|
||||
New-PSItem east 20
|
||||
New-PSItem west 30
|
||||
New-PSItem south 40
|
||||
) | Export-Excel $file -PassThru
|
||||
|
||||
$ws=$xlPkg.Workbook.Worksheets[1]
|
||||
|
||||
$ws.Cells["A3"].Value = "Hello World"
|
||||
$ws.Cells["B3"].Value = "Updating cells"
|
||||
$ws.Cells["D1:D5"].Value = "Data"
|
||||
|
||||
$ws.Cells.AutoFitColumns()
|
||||
|
||||
$xlPkg.Save()
|
||||
$xlPkg.Dispose()
|
||||
|
||||
Invoke-Item $file
|
||||
```
|
||||
|
||||
## Result
|
||||

|
||||
|
||||
#### 1/18/2016
|
||||
|
||||
* Added `Conditional Text Formatting`. [Boe Prox](https://twitter.com/proxb) posted about [HTML Reporting, Part 2: Take Your Reporting a Step Further](https://mcpmag.com/articles/2016/01/14/html-reporting-part-2.aspx) and colorized cells. Great idea, now part of the PowerShell Excel module.
|
||||
|
||||

|
||||
|
||||
#### 1/7/2016
|
||||
* Added `Get-ExcelSheetInfo` - Great contribution from *Johan Åkerström* check him out on [GitHub](https://github.com/CosmosKey) and [Twitter](https://twitter.com/neptune443)
|
||||
|
||||

|
||||
|
||||
#### 12/26/2015
|
||||
|
||||
* Added `NoLegend`, `Show-Category`, `ShowPercent` for all charts including Pivot Charts
|
||||
* Updated PieChart, BarChart, ColumnChart and Line chart to work with the pipeline and added `NoLegend`, `Show-Category`, `ShowPercent`
|
||||
|
||||
#### 12/17/2015
|
||||
|
||||
These new features open the door for really sophisticated work sheet creation.
|
||||
|
||||
Stay tuned for a [blog post](http://www.dougfinke.com/blog/) and examples.
|
||||
|
||||
***Quick List***
|
||||
* StartRow, StartColumn for placing data anywhere in a sheet
|
||||
* New-ExcelChart - Add charts to a sheet, multiple series for a chart, locate the chart anywhere on the sheet
|
||||
* AutoNameRange, Use functions and/or calculations in a cell
|
||||
* Quick charting using PieChart, BarChart, ColumnChart and more
|
||||
|
||||

|
||||
|
||||
#### 10/20/2015
|
||||
|
||||
Big bug fix for version 3.0 PowerShell folks!
|
||||
|
||||
This technique fails in 3.0 and works in 4.0 and later.
|
||||
```PowerShell
|
||||
$m="substring"
|
||||
"hello".$m(2,1)
|
||||
```
|
||||
|
||||
Adding `.invoke` works in 3.0 and later.
|
||||
|
||||
```PowerShell
|
||||
$m="substring"
|
||||
"hello".$m.invoke(2,1)
|
||||
```
|
||||
|
||||
A ***big thank you*** to [DarkLite1](https://github.com/DarkLite1) for adding the help to Export-Excel.
|
||||
|
||||
Added `-HeaderRow` parameter. Sometimes the heading does not start in Row 1.
|
||||
|
||||
|
||||
#### 10/16/2015
|
||||
|
||||
Fixes [Export-Excel generates corrupt Excel file](https://github.com/dfinke/ImportExcel/issues/46)
|
||||
|
||||
#### 10/15/2015
|
||||
|
||||
`Import-Excel` has a new parameter `NoHeader`. If data in the sheet does not have headers and you don't want to supply your own, `Import-Excel` will generate the property name.
|
||||
|
||||
`Import-Excel` now returns `.Value` rather than `.Text`
|
||||
|
||||
|
||||
#### 10/1/2015
|
||||
|
||||
Merged ValidateSet for Encoding and Extension. Thank you [Irwin Strachan](https://github.com/irwins).
|
||||
|
||||
#### 9/30/2015
|
||||
|
||||
Export-Excel can now handle data that is **not** an object
|
||||
|
||||
echo a b c 1 $true 2.1 1/1/2015 | Export-Excel c:\temp\test.xlsx -Show
|
||||
Or
|
||||
|
||||
dir -Name | Export-Excel c:\temp\test.xlsx -Show
|
||||
|
||||
#### 9/25/2015
|
||||
|
||||
**Hide worksheets**
|
||||
Got a great request from [forensicsguy20012004](https://github.com/forensicsguy20012004) to hide worksheets. You create a few pivotables, generate charts and then pivotable worksheets don't need to be visible.
|
||||
|
||||
`Export-Excel` now has a `-HideSheet` parameter that takes and array of worksheet names and hides them.
|
||||
|
||||
##### Example
|
||||
Here, you create four worksheets named `PM`,`Handles`,`Services` and `Files`.
|
||||
|
||||
The last line creates the `Files` sheet and then hides the `Handles`,`Services` sheets.
|
||||
|
||||
$p = Get-Process
|
||||
|
||||
$p|select company, pm | Export-Excel $xlFile -WorkSheetname PM
|
||||
$p|select company, handles| Export-Excel $xlFile -WorkSheetname Handles
|
||||
Get-Service| Export-Excel $xlFile -WorkSheetname Services
|
||||
|
||||
dir -File | Export-Excel $xlFile -WorkSheetname Files -Show -HideSheet Handles, Services
|
||||
|
||||
|
||||
**Note** There is a bug in EPPlus that does not let you hide the first worksheet created. Hopefully it'll resolved soon.
|
||||
|
||||
#### 9/11/2015
|
||||
|
||||
Added Conditional formatting. See [TryConditional.ps1](https://github.com/dfinke/ImportExcel/blob/master/TryConditional.ps1) as an example.
|
||||
|
||||
Or, check out the short ***"How To"*** video.
|
||||
|
||||
[](http://www.dougfinke.com/videos/excelpsmodule/excelpsmodule.mp4)
|
||||
|
||||
|
||||
#### 8/21/2015
|
||||
* Now import Excel sheets even if the file is open in Excel. Thank you [Francois Lachance-Guillemette](https://github.com/francoislg)
|
||||
|
||||
#### 7/09/2015
|
||||
* For -PivotRows you can pass a `hashtable` with the name of the property and the type of calculation. `Sum`, `Average`, `Max`, `Min`, `Product`, `StdDev`, `StdDevp`, `Var`, `Varp`
|
||||
|
||||
```PowerShell
|
||||
Get-Service |
|
||||
Export-Excel "c:\temp\test.xlsx" `
|
||||
-Show `
|
||||
-IncludePivotTable `
|
||||
-PivotRows status `
|
||||
-PivotData @{status='count'}
|
||||
```
|
||||
|
||||
#### 6/16/2015 (Thanks [Justin](https://github.com/zippy1981))
|
||||
* Improvements to PivotTable overwriting
|
||||
* Added two parameters to Export-Excel
|
||||
* RangeName - Turns the data piped to Export-Excel into a named range.
|
||||
* TableName - Turns the data piped to Export-Excel into an excel table.
|
||||
|
||||
Examples
|
||||
|
||||
Get-Process|Export-Excel foo.xlsx -Verbose -IncludePivotTable -TableName "Processes" -Show
|
||||
Get-Process|Export-Excel foo.xlsx -Verbose -IncludePivotTable -RangeName "Processes" -Show
|
||||
|
||||
|
||||
#### 5/25/2015
|
||||
* Fixed null header problem
|
||||
|
||||
#### 5/17/2015
|
||||
* Added three parameters:
|
||||
* FreezeTopRow - Freezes the first row of the data
|
||||
* AutoFilter - Enables filtering for the data in the sheet
|
||||
* BoldTopRow - Bolds the top row of data, the column headers
|
||||
|
||||
Example
|
||||
|
||||
Get-CimInstance win32_service |
|
||||
select state, accept*, start*, caption |
|
||||
Export-Excel test.xlsx -Show -BoldTopRow -AutoFilter -FreezeTopRow -AutoSize
|
||||
|
||||

|
||||
|
||||
|
||||
#### 5/4/2015
|
||||
* Published to PowerShell Gallery. In PowerShell v5 use `Find-Module importexcel` then `Find-Module importexcel | Install-Module`
|
||||
|
||||
|
||||
#### 4/27/2015
|
||||
* datetime properties were displaying as ints, now are formatted
|
||||
|
||||
#### 4/25/2015
|
||||
* Now you can create multiple Pivot tables in one pass
|
||||
* Thanks to [pscookiemonster](https://twitter.com/pscookiemonster), he submitted a repro case to the EPPlus CodePlex project and got it fixed
|
||||
|
||||
#### Example
|
||||
|
||||
$ps = ps
|
||||
|
||||
$ps |
|
||||
Export-Excel .\testExport.xlsx -WorkSheetname memory `
|
||||
-IncludePivotTable -PivotRows Company -PivotData PM `
|
||||
-IncludePivotChart -ChartType PieExploded3D
|
||||
$ps |
|
||||
Export-Excel .\testExport.xlsx -WorkSheetname handles `
|
||||
-IncludePivotTable -PivotRows Company -PivotData Handles `
|
||||
-IncludePivotChart -ChartType PieExploded3D -Show
|
||||
|
||||

|
||||
|
||||
#### 4/20/2015
|
||||
* Included and embellished [Claus Nielsen](https://github.com/Claustn) function to take all sheets in an Excel file workbook and create a text file for each `ConvertFrom-ExcelSheet`
|
||||
* Renamed `Export-MultipleExcelSheets` to `ConvertFrom-ExcelSheet`
|
||||
|
||||
#### 4/13/2015
|
||||
* You can add a title to the Excel "Report" `Title`, `TitleFillPattern`, `TitleBold`, `TitleSize`, `TitleBackgroundColor`
|
||||
* Thanks to [Irwin Strachan](http://pshirwin.wordpress.com) for this and other great suggestions, testing and more
|
||||
|
||||
|
||||
#### 4/10/2015
|
||||
* Renamed `AutoFitColumns` to `AutoSize`
|
||||
* Implemented `Export-MultipleExcelSheets`
|
||||
* Implemented `-Password` for a worksheet
|
||||
* Replaced `-Force` switch with `-NoClobber` switch
|
||||
* Added examples for `Get-Help`
|
||||
* If Pivot table is requested, that sheet becomes the tab selected
|
||||
|
||||
#### 4/8/2015
|
||||
* Implemented exporting data to **named sheets** via the -WorkSheetname parameter.
|
||||
|
||||
Examples
|
||||
-
|
||||
`gsv | Export-Excel .\test.xlsx -WorkSheetname Services`
|
||||
|
||||
`dir -file | Export-Excel .\test.xlsx -WorkSheetname Files`
|
||||
|
||||
`ps | Export-Excel .\test.xlsx -WorkSheetname Processes -IncludePivotTable -Show -PivotRows Company -PivotData PM`
|
||||
|
||||
#### Convert (All or Some) Excel Sheets to Text files
|
||||
|
||||
Reads each sheet in TestSheets.xlsx and outputs it to the data directory as the sheet name with the extension .txt
|
||||
|
||||
ConvertFrom-ExcelSheet .\TestSheets.xlsx .\data
|
||||
|
||||
Reads and outputs sheets like Sheet10 and Sheet20 form TestSheets.xlsx and outputs it to the data directory as the sheet name with the extension .txt
|
||||
|
||||
ConvertFrom-ExcelSheet .\TestSheets.xlsx .\data sheet?0
|
||||
|
||||
#### Example Adding a Title
|
||||
You can set the pattern, size and of if the title is bold.
|
||||
|
||||
$p=@{
|
||||
Title = "Process Report as of $(Get-Date)"
|
||||
TitleFillPattern = "LightTrellis"
|
||||
TitleSize = 18
|
||||
TitleBold = $true
|
||||
|
||||
Path = "$pwd\testExport.xlsx"
|
||||
Show = $true
|
||||
AutoSize = $true
|
||||
}
|
||||
|
||||
Get-Process |
|
||||
Where Company | Select Company, PM |
|
||||
Export-Excel @p
|
||||
|
||||

|
||||
|
||||
#### Example Export-MultipleExcelSheets
|
||||

|
||||
|
||||
$p = Get-Process
|
||||
|
||||
$DataToGather = @{
|
||||
PM = {$p|select company, pm}
|
||||
Handles = {$p|select company, handles}
|
||||
Services = {gsv}
|
||||
Files = {dir -File}
|
||||
Albums = {(Invoke-RestMethod http://www.dougfinke.com/PowerShellfordevelopers/albums.js)}
|
||||
}
|
||||
|
||||
Export-MultipleExcelSheets -Show -AutoSize .\testExport.xlsx $DataToGather
|
||||
|
||||
|
||||
|
||||
***NOTE*** If the sheet exists when using *-WorkSheetname* parameter, it will be deleted and then added with the new data.
|
||||
|
||||
## Get-Process Exported to Excel
|
||||
|
||||
### Total Physical Memory Grouped By Company
|
||||

|
||||
|
||||
## Importing data from an Excel spreadsheet
|
||||
|
||||

|
||||
|
||||
You can also find EPPLus on [Nuget](https://www.nuget.org/packages/EPPlus/).
|
||||
|
||||
## Known Issues
|
||||
|
||||
* Using `-IncludePivotTable`, if that pivot table name exists, you'll get an error.
|
||||
* Investigating a solution
|
||||
* *Workaround* delete the Excel file first, then do the export
|
||||
>>>>>>> 9f7884f991c80448091ef56853027f64d98b6cc7
|
||||
|
||||
3
ToDo.md
3
ToDo.md
@@ -1 +1,4 @@
|
||||
- [ ] Create an autocomplete for WorkSheetName param on ImportExcel
|
||||
- [ ] Add help text for parmaters which don't have it in Export Excel
|
||||
- [ ] Add checks for valid worksheet names (also check pivot names, range names and table names are valid)
|
||||
- [ ] Investigate regional support for number conversion
|
||||
@@ -5,7 +5,7 @@
|
||||
Import-Module $PSScriptRoot\..\ImportExcel.psd1 -Force
|
||||
|
||||
if (Get-process -Name Excel,xlim -ErrorAction SilentlyContinue) { Write-Warning -Message "You need to close Excel before running the tests." ; return}
|
||||
Describe ExportExcel {
|
||||
#53Describe ExportExcel {
|
||||
|
||||
Context "#Example 1 # Creates and opens a file with the right number of rows and columns" {
|
||||
$path = "$env:TEMP\Test.xlsx"
|
||||
@@ -685,6 +685,43 @@ Describe ExportExcel {
|
||||
}
|
||||
Close-ExcelPackage -ExcelPackage $excel -nosave
|
||||
}
|
||||
describe "foo" {
|
||||
Context " # Awkward multiple tables" {
|
||||
$path = "$Env:TEMP\test.xlsx"
|
||||
remove-item -Path $path -ErrorAction SilentlyContinue
|
||||
$r = Get-ChildItem -path C:\WINDOWS\system32 -File
|
||||
|
||||
"Biggest files" | Export-Excel -Path $path -StartRow 1 -StartColumn 7
|
||||
$r | Sort-Object length -Descending | Select -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
|
||||
|
||||
$r | Group-Object -Property extension | Select-Object Name, @{n="Size"; e={($_.group | measure -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
|
||||
}
|
||||
it "Created the FileSize table in the right places with the right size " {
|
||||
$ws.Tables["FileSize"].Address.Address | should be "G2:H16" #Insert at row 2, Column 7, 14 rows x 2 columns of data
|
||||
$ws.Tables["FileSize"].StyleName | should be "TableStyleMedium2"
|
||||
}
|
||||
it "Created the ExtSize table in the right places with the right size " {
|
||||
$ws.Tables["ExtSize"].Address.Address | should be "A2:B14" #tile, then 12 rows x 2 columns of data
|
||||
$ws.Tables["ExtSize"].TableStyle.tostring() | should be "medium6"
|
||||
}
|
||||
it "Created the ExtSize table in the right places with the right size " {
|
||||
$ws.Tables["ExtSize"].Address.Address | should be "A2:B14" #tile, then 12 rows x 2 columns of data
|
||||
$ws.Tables["ExtSize"].TableStyle.tostring() | should be "medium6"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
## To do
|
||||
## More Charts , pivot options & other FreezePanes settings ?
|
||||
|
||||
Reference in New Issue
Block a user