Add example and automatic column arrangement

Add example and automatic column arrangement
This commit is contained in:
muschebubusche
2021-11-07 22:52:54 +01:00
parent 62c8d74a59
commit 8f0fc7397d
3 changed files with 44 additions and 0 deletions

View File

@@ -0,0 +1,9 @@
try {Import-Module $PSScriptRoot\..\..\ImportExcel.psd1} catch {throw ; return}
# Create example file
$xlFile = "$PSScriptRoot\ImportColumns.xlsx"
Get-Process | Export-Excel -Path $xlFile
# -ImportColumns will also arrange columns
Import-Excel -Path $xlFile -ImportColumns @(1,3,2) -NoHeader -StartRow 1
# Get only pm, npm, cpu, id, processname
Import-Excel -Path $xlFile -ImportColumns @(6,7,12,25,46) | Format-Table -AutoSize

View File

@@ -163,6 +163,17 @@
}
else {
if ($ImportColumns) {
# Safe the original array because $ImportColumns needs to be sorted for calculation
$tempArray = $ImportColumns
$ImportColumns = $ImportColumns | Sort-Object
# Check order
if (($tempArray[0] -ne $ImportColumns[0]) -or ($tempArray[$tempArray.Count - 1] -ne $ImportColumns[$ImportColumns.Count - 1])) {
$arrange = $true
} else {
for ($i = 0; $i -lt $ImportColumns.Count; $i++) {
if ($ImportColumns[$i] -ne $tempArray[$i]) { $arrange = $true;break }
}
}
$end = $Worksheet.Dimension.End.Column
if (($StartColumn -ne 1) -or ($EndColumn -ne $end)) { Write-Warning -Message "If ImportColumns is set than individual StartColumn and EndColumn will be ignored." }
# Variable to store all removed columns
@@ -192,6 +203,16 @@
}
$ExcelPackage = Clear-ExcelPackage -Start $start -Count $count
}
# Arrange columns accordingly to $ImportColumns
if ($arrange) {
for ($i = 0; $i -lt $ImportColumns.Count; $i++) {
$srcCol = [array]::IndexOf($ImportColumns,$tempArray[$i]) + 1
$destCol = $ImportColumns.Count + ($i + 1)
$Worksheet.Cells[1,$srcCol,$EndRow,$srcCol].Copy(($Worksheet.Cells[1,$destCol,$EndRow,$destCol]))
}
$ExcelPackage = Clear-ExcelPackage -Start 1 -Count $ImportColumns.Count
Remove-Variable -Name 'tempArray'
}
# Create new array out of the $ImportColumns.Count for the further processing
$columns = 1..$ImportColumns.Count
}

View File

@@ -364,4 +364,18 @@ Describe "Import-Excel on a sheet with no headings" {
$actual[0].E | Should -Be '5'
}
It "Should arrange the columns if -ImportColumns is not in order" {
$actual = @(Import-Excel $xlfileImportColumns -ImportColumns @(5,1,4))
$actualNames = $actual[0].psobject.properties.Name
$actualNames.Count | Should -Be 3
$actualNames[0] | Should -Be 'E'
$actualNames[1] | Should -Be 'A'
$actualNames[2] | Should -Be 'D'
$actual[0].E | Should -Be '5'
$actual[0].A | Should -Be '1'
$actual[0].D | Should -Be '4'
}
}