Hi @Anders Sjöqvist,
I'd be happy to help you out with your question. Sorry for the inconvenience caused.
The behavior you're experiencing is due to the default settings of the OLE DB provider, which skips empty rows and columns during data retrieval. However, there is a way to include these empty rows and columns in your query output.
To accomplish this, you need to modify the connection string's Extended Properties. Follow the steps below:
- Open your PowerShell script that performs the OLE DB query on the Excel file.
- Locate the section where the connection string is defined. You should see a line similar to the following:
$builder.Add('Extended Properties', 'Excel 12.0 Xml;HDR=No;IMEX=1')
- Modify the connection string by changing IMEX=1 to IMEX=0. This change forces the provider to include empty cells.
$builder.Add('Extended Properties', 'Excel 12.0 Xml;HDR=No;IMEX=0')
- Save the script with the modifications.
After making these changes, re-run the PowerShell script. The query output will now include all rows and columns, even if they only contain empty cells. This ensures that you can reliably read from the exact cells you need.
Here's the updated code with the modified connection string:
$filename = 'foo.xlsx'
$fullPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($filename)
$builder = New-Object -TypeName System.Data.OleDb.OleDbConnectionStringBuilder
$builder.Add('Provider', 'Microsoft.ACE.OLEDB.12.0')
$builder.Add('Data Source', $fullPath)
$builder.Add('Extended Properties', 'Excel 12.0 Xml;HDR=No;IMEX=0') # Modified: IMEX=0
$conn = New-Object -TypeName System.Data.OleDb.OleDbConnection -ArgumentList $builder.ConnectionString
$conn.Open()
try {
$command = New-Object -TypeName System.Data.OleDb.OleDbCommand -ArgumentList 'SELECT * FROM [Sheet1$]'
$command.Connection = $conn
$adapter = New-Object -TypeName System.Data.OleDb.OleDbDataAdapter -ArgumentList $command
$sheet = New-Object -TypeName System.Data.DataTable
[void]$adapter.Fill($sheet)
} finally {
$conn.Close()
}
$sheet
Please note that using IMEX=0 may have some limitations, particularly when dealing with mixed data types in a column. If you encounter any issues with data type mismatches, you may need to specify specific data types for the columns in your query or adjust the IMEX value accordingly to handle the data appropriately.
If you have any other questions or need assistance with anything, please don't hesitate to let me know. I'm here to help.
If the reply was helpful, please don’t forget to upvote or accept as answer, thank you.