PowerShell Script to Write Excel File Easily
$excel = New-Object -ComObject Excel.Application, then create workbook and write cells like $sheet.Cells.Item(1,1) = 'Hello' before saving with $workbook.SaveAs('path.xlsx').Examples
How to Think About It
Algorithm
Code
$excel = New-Object -ComObject Excel.Application $excel.Visible = $false $workbook = $excel.Workbooks.Add() $sheet = $workbook.Sheets.Item(1) $sheet.Cells.Item(1,1) = 'Hello' $workbook.SaveAs("$PWD\hello.xlsx") $workbook.Close() $excel.Quit() Write-Output "Excel file saved as hello.xlsx"
Dry Run
Let's trace writing 'Hello' to cell A1 and saving the file
Create Excel COM object
$excel = New-Object -ComObject Excel.Application (Excel app created)
Add workbook and get sheet
$workbook = $excel.Workbooks.Add() (new workbook) $sheet = $workbook.Sheets.Item(1) (first sheet)
Write 'Hello' to cell A1
$sheet.Cells.Item(1,1) = 'Hello'
Save and close
$workbook.SaveAs("$PWD\hello.xlsx") $workbook.Close() $excel.Quit()
| Step | Action | Value |
|---|---|---|
| 1 | Create Excel COM object | Excel.Application instance |
| 2 | Add workbook and get sheet | Workbook and Sheet objects |
| 3 | Write to cell A1 | 'Hello' |
| 4 | Save and close | File saved as hello.xlsx |
Why This Works
Step 1: Create Excel COM Object
Using New-Object -ComObject Excel.Application starts Excel invisibly so you can control it from PowerShell.
Step 2: Add Workbook and Select Sheet
You add a new workbook and select the first sheet to write data into cells.
Step 3: Write Data to Cells
Assign values to cells by specifying row and column with Cells.Item(row, column).
Step 4: Save and Close
Save the workbook to a file path, then close the workbook and quit Excel to free resources.
Alternative Approaches
Install-Module -Name ImportExcel -Scope CurrentUser
$data = @{
Name = 'John'; Age = 30
}
$data | Export-Excel -Path "$PWD\data.xlsx"$data = @(
@{Name='John'; Age=30},
@{Name='Jane'; Age=25}
)
$data | Export-Csv -Path "$PWD\data.csv" -NoTypeInformationComplexity: O(1) time, O(1) space
Time Complexity
Writing a few cells is constant time since no loops are involved; complexity grows linearly if writing many cells in loops.
Space Complexity
Uses constant extra memory for Excel COM objects; data is stored inside Excel application memory.
Which Approach is Fastest?
Using the ImportExcel module is faster and lighter than COM automation but requires module installation.
| Approach | Time | Space | Best For |
|---|---|---|---|
| COM Automation | O(1) for small writes | O(1) | Full Excel features, requires Excel installed |
| ImportExcel Module | O(1) | O(1) | Quick Excel file creation without Excel installed |
| CSV Export | O(1) | O(1) | Simple data export, no Excel features |
$excel.Quit() to close Excel and avoid hanging processes.