Creating Excel Reports (Part 3 – Individually Accessing Workbook)

by Aug 18, 2017

Sometimes you may want to create irregularly shaped reports, that is reports in a non-table design.

For this, PowerShell lets you connect to the Excel object model. This way, you can access individual cells, read and write their content, and even format them. This gives you maximum flexibility. However, the drawback is that it requires a lot of code since you have to manually set up every single workbook cell. Also, accessing COM objects via .NET is relatively slow.

Here is the code that gets you started. It shows you how to connect to Excel, access individual cells, and even apply formatting:

#requires -Version 2.0
Add-Type -AssemblyName System.Drawing

# accessing excel via COM
$excel = New-Object -ComObject Excel.Application
# make it visible (for debugging only, can be set to $false later in production)
$excel.Visible = $true

# add workbook
$workbook = $excel.Workbooks.Add()

# access workbook cells
$workbook.ActiveSheet.Cells.Item(1,1) = 'Hey!'

# formatting cell
$workbook.ActiveSheet.Cells.Item(1,1).Font.Size = 20

$r = 200
$g = 100
$b = 255
$workbook.ActiveSheet.Cells.Item(1,1).Font.Color = $r + ($g * 256) + ($b * 256 * 256)

# saving workbook to file
$Path = "$env:temp\excel.xlsx"

Twitter This Tip! ReTweet this Tip!