dfinke / ImportExcel

PowerShell module to import/export Excel spreadsheets, without Excel

Home Page:https://www.powershellgallery.com/packages/ImportExcel/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Export-Excel's -CellStyleSB switch doesn't seem to parse dimensions.address correctly for use with Set-CellStyle

matt555 opened this issue · comments

https://github.com/dfinke/ImportExcel/blob/61744012cdb84a8bc79be2bab8f8db2a6df37af1/Public/Export-Excel.ps1#L666C63-L666C63

Using the example i was able to get it to work with a minor tweak to the regex.

I would add a pull request but i'm not sure of the history here... im guessing dimensions.address had a former format?

$xlSourcefile = "$env:TEMP\ImportExcelExample.xlsx"
Write-Verbose -Verbose -Message  "Save location: $xlSourcefile"
Remove-Item $xlSourcefile -ErrorAction Ignore

Get-Process |
    Select-Object -First 20 -Property Company,Handles,PM, NPM|
    Export-Excel $xlSourcefile  -Show  -AutoSize -CellStyleSB {
        param(
            $workSheet,
            $totalRows,
            $lastColumn
        )

        $lastColumn = $workSheet.Dimension.Address -replace "^.*:([A-Z|a-z]*)\d+$", '$1'   # <-- modified $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
        }
    }

Example of regex update:

> $worksheet.Dimension.Address
A1:P21
> $worksheet.Dimension.Address -replace "^.*:(\w*)\d+$" , '$1'
P2
> $worksheet.Dimension.Address -replace "^.*:([A-Z|a-z]*)\d+$" , '$1'
P
# verified double letter columns works:
>  'AA1:BB300' -replace "^.*:([A-Z|a-z]*)\d+$" , '$1'
BB

I just remembered, this could work as well:

$(Get-ExcelColumnName -ColumnNumber $worksheet.Dimension.Columns).ColumnName

Thanks for checking that out. CellStyleSB was an experimental concept. Happy to look at a PR and discuss.