dfinke / ImportExcel

PowerShell module to import/export Excel spreadsheets, without Excel
https://www.powershellgallery.com/packages/ImportExcel/
Apache License 2.0
2.48k stars 400 forks source link

Set-excelrange after export-excel with '-append' results in exception #1588

Closed TWalijew closed 7 months ago

TWalijew commented 7 months ago

Hello, this one drove me nuts: Every 15 minutes I scan the results of a REST call with Powershell and append it to a Excel sheet to get some stats data. Now I was so daring to add borders around the table; on a new table it works perfect, the following runs result in an exception. I stripped down and simplified this script to make it easier to read: [execute it several times, the 1st time it works well, then it will fail]

# create test data
$a=[pscustomobject]@{
    a="aaa"
    b="bbb"
    c="ccc"
}
$xl=open-excelpackage -path ".\test.xlsx" -create 
# export the data with -append
$xl=$a|export-excel -excelpackage $xl -tablestyle medium16 -passthru -append
#this is more or less taken from the 3rd example of set-excelrange
set-excelrange $xl.workbook.worksheets[1].tables[0] -italic
Close-ExcelPackage $xl

Now for the workaround, which works over and over again:

$a=[pscustomobject]@{
    a="aaa"
    b="bbb"
    c="ccc"
}
$xl=open-excelpackage -path ".\batz.xlsx" -create 
$xl=$a|export-excel -excelpackage $xl -tablestyle medium16 -passthru -append
$address=$xl.workbook.worksheets[1].tables[0].address
$range=$xl.workbook.worksheets[1].cells[$address.address]
set-excelrange -range $range -italic
Close-ExcelPackage $xl

Now the downer: The last line of the table is not included in the range, i.e. the table dimension are not updated after the export. And finally the upper that I found a minute ago: On exporting name the range ("-rangename") and use the name to set the range for set-excelrange:

$xl=$a,$a,$a|export-excel -excelpackage $xl -worksheetname "aaa" -TableName "abc" -rangename "Rangename" -tablestyle medium16 -passthru -append
$range=$xl.workbook.worksheets["aaa"].cells["Rangename"]
set-excelrange -range $range -italic -FontColor green

Best Thomas