PowerShell Script to Read Excel File Easily
$excel = New-Object -ComObject Excel.Application to open Excel, then $workbook = $excel.Workbooks.Open('path_to_file.xlsx') to load the file, and finally read cells with $worksheet.Cells.Item(row, column).Text.Examples
How to Think About It
Algorithm
Code
$excel = New-Object -ComObject Excel.Application $excel.Visible = $false $workbook = $excel.Workbooks.Open('C:\temp\sample.xlsx') $worksheet = $workbook.Sheets.Item(1) $value1 = $worksheet.Cells.Item(1,1).Text $value2 = $worksheet.Cells.Item(1,2).Text Write-Output "$value1 $value2" $workbook.Close($false) $excel.Quit()
Dry Run
Let's trace reading cells A1 and B1 from the Excel file 'sample.xlsx'.
Create Excel COM object
$excel = Excel.Application COM object created
Open workbook
$workbook = sample.xlsx opened
Read cells
Read A1='Hello', B1='World'
| Cell | Value |
|---|---|
| A1 | Hello |
| B1 | World |
Why This Works
Step 1: Create Excel COM object
The New-Object -ComObject Excel.Application command starts Excel invisibly so PowerShell can control it.
Step 2: Open Excel file
The Workbooks.Open method loads the Excel file so you can access its sheets and cells.
Step 3: Read cell values
Accessing Cells.Item(row, column).Text gets the text content of each cell.
Step 4: Clean up
Closing the workbook and quitting Excel frees resources and avoids leaving Excel running.
Alternative Approaches
Import-Module ImportExcel $data = Import-Excel -Path 'C:\temp\sample.xlsx' $data | ForEach-Object { "$($_.Column1) $($_.Column2)" }
Convert Excel to CSV manually, then use: $data = Import-Csv -Path 'C:\temp\sample.csv' $data | ForEach-Object { "$($_.Column1) $($_.Column2)" }
Complexity: O(n) time, O(n) space
Time Complexity
Reading cells is linear in the number of cells accessed, so O(n) where n is the number of cells read.
Space Complexity
Memory usage grows with the number of cell values stored in variables, also O(n).
Which Approach is Fastest?
Using the ImportExcel module is faster and uses less memory than COM automation, which is slower and heavier.
| Approach | Time | Space | Best For |
|---|---|---|---|
| COM Object Automation | O(n) | O(n) | Full Excel features, no extra installs |
| ImportExcel Module | O(n) | O(n) | Simple, fast, requires module install |
| CSV Import | O(n) | O(n) | Simple data, no Excel needed |
$excel.Quit() to prevent Excel processes from lingering.