diff --git a/Examples/Import-ExcelWithHeaderName.ps1 b/Examples/Import-ExcelWithHeaderName.ps1 new file mode 100644 index 00000000..f8e8c4a5 --- /dev/null +++ b/Examples/Import-ExcelWithHeaderName.ps1 @@ -0,0 +1,22 @@ +# Create Test File +$path = "$env:TEMP\Test.xlsx" +Remove-item -Path $path -ErrorAction SilentlyContinue +$processes = Get-Process | Select-Object -First 10 +$Processes | Export-Excel $path + +# Import the file as is. +Import-Excel -Path $path | Format-Table +# Import the file replacing the name of the 2 first headers and discarding the rest. +Import-Excel -Path $path -HeaderName 'NewA', 'NewB' +# Import the file selecting 3 of it's columns by name, renaming 2, changing the order and discarding the rest. +Import-Excel -Path $path -HeaderName ([Ordered]@{Name = 'Process Name' ; StartTime = 'Start'; Path = 'Path'}) +<# Output Example: +Process Name Start Path +------------ ----- ---- +ApplicationFrameHost 07/04/2019 11:02:19 C:\WINDOWS\system32\ApplicationFrameHost.exe +AppVShNotify +audiodg 08/04/2019 19:21:32 +chrome 08/04/2019 16:49:47 C:\Program Files (x86)\Google\Chrome\Application\chrome.exe +chrome 08/04/2019 16:49:27 C:\Program Files (x86)\Google\Chrome\Application\chrome.exe +chrome 08/04/2019 16:49:27 C:\Program Files (x86)\Google\Chrome\Application\chrome.exe +#> \ No newline at end of file diff --git a/ImportExcel.psm1 b/ImportExcel.psm1 index 222b1629..b75cc53d 100644 --- a/ImportExcel.psm1 +++ b/ImportExcel.psm1 @@ -281,7 +281,7 @@ function Import-Excel { [String]$WorksheetName, [Parameter(ParameterSetName = 'PathB' , Mandatory)] [Parameter(ParameterSetName = 'PackageB', Mandatory)] - [String[]]$HeaderName , + $HeaderName , [Parameter(ParameterSetName = 'PathC' , Mandatory)] [Parameter(ParameterSetName = 'PackageC', Mandatory)] [Switch]$NoHeader , @@ -321,7 +321,7 @@ function Import-Excel { $C | Select-Object @{N = 'Column'; E = {$_}}, @{N = 'Value'; E = {'P' + $i}} } } - elseif ($HeaderName) { + elseif ($HeaderName -and $HeaderName -isnot [Collections.Hashtable] -and $HeaderName -isnot [Collections.Specialized.OrderedDictionary]) { $i = 0 foreach ($H in $HeaderName) { $H | Select-Object @{N = 'Column'; E = {$Columns[$i]}}, @{N = 'Value'; E = {$H}} @@ -333,9 +333,18 @@ function Import-Excel { throw 'The top row can never be less than 1 when we need to retrieve headers from the worksheet.' ; return } - foreach ($C in $Columns) { + $PropertyNames = foreach ($C in $Columns) { $Worksheet.Cells[$StartRow, $C] | Where-Object {$_.Value} | Select-Object @{N = 'Column'; E = {$C}}, Value } + + if ($HeaderName) { + foreach ($H in $HeaderName.GetEnumerator()) { + $H | Select-Object @{N = 'Column'; E = {($PropertyNames | Where-Object {$_.Value -eq $H.Name}).Column}}, @{N = 'Value'; E = {$H.Value}} + } + } + else { + $PropertyNames + } } } Catch {