Is it possible to read only the headers from an Excel file using PowerShell and Import-Excel module?
I've an Excel file with multiple sheets. One of them only contains headers and now data rows.
After some updates I need to write the results to a new Excel file.
Everything works fine for the other sheets but for the one with no data I'm unable to copy the headers to the new file.
$xlsx = Import-Excel 'D:\data.xlsx' -WorksheetName 'events'
Write-Host $xlsx
> WARNING: Worksheet 'events' in workbook 'D:\data.xlsx' contains no data in the rows after top row '1'
$prop = [Collections.Generic.List[Object]]$xlsx[0].psobject.properties.Name
Write-Host $prop
> Cannot index into a null array. At D:\Untitled1.ps1:4 char:1
> + $prop = [Collections.Generic.List[Object]]$xlsx[0].psobject.propertie ...
> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> + CategoryInfo : InvalidOperation: (:) [], RuntimeException
> + FullyQualifiedErrorId : NullArray
Any help much appriciated!
There are 2 options you could use to get the headers of a Spreadsheet with no data:
-NoHeaderswitch then you need to target the.Valueproperty instead of the.Nameproperty:Open-ExcelPackageand get the value of the.Textproperty of each Cell: