Search notes:

Powershell + Microsoft.Office.Interop.Excel

Example

This is a simple example that is supposed to demonstrate how Microsoft.Office.Interop.Excel can be used in PowerShell:
set-strictMode -version latest

  $null = [Reflection.Assembly]::LoadWithPartialName(                      "Microsoft.Office.InterOp.Excel"   )
# add-type -path      'C:\Program Files (x86)\Microsoft Office\Office16\DCF\Microsoft.Office.Interop.Excel.dll'
# add-type -path 'C:\Program Files (x86)\Microsoft Office\root\Office16\DCF\Microsoft.Office.Interop.Excel.dll'


$xls = new-object Microsoft.Office.Interop.Excel.ApplicationClass

$xls.Visible = $true

$wb = $xls.Workbooks.Add()
$sh = $wb.Worksheets(1)

$sh.Name = "foo bar baz"

$sh.Cells(1,1) = "Hello world"

$wb.SaveAs("$env:temp\excel-test.xlsx")
$xls.Quit()
Github repository .NET-API, path: /Microsoft/Office/Interop/Excel/PowerShell/simple.ps1

Error message: Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type 'Microsoft.Office.Interop.Excel._Application'

On a company-laptop, I encountered the following error message:
Exception setting "Visible": "Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type 'Microsoft.Office.Interop.Excel._Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208D5-0000-0000-C000-000000000046}' failed due to the following error: Element not found. (Exception from HRESULT: 0x8002802B (TYPE_E_ELEMENTNOTFOUND)).
Some solutions to this problems are found in this stackoverflow question.

See also

This Stackoveflow answer has some ideas that outline the necessary steps to have the Excel process stopped that is spawned when using Interop Excel. Basically, it boils down to put all interop stuff into a function and after calling the function to execute the following two statements outside of the function
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
The Microsoft.Office.Interop.Excel namespace.

Index