Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open excel workbook from powershell for automation

I want to open an excel workbook and read out data, do other kinds of operations, etc. I know that I have to add an assembly reference:

 [Reflection.Assembly]::LoadFile("C:\Program Files\Microsoft Office\Office16\ADDINS\Microsoft Power Query for Excel Integrated\bin\Microsoft.Office.Interop.Excel.dll")

And then I need to instantiate an Application object.

$workbook = New-Object -TypeName Microsoft.Office.Interop.Excel.Application

This however returns an error "A constructor was not found" Isn't by the way Microsoft.Office.Interop.Excel.Application an interface actually? I am wondering how it can be instantiated in this scenario.

like image 279
ThomasMX Avatar asked Jun 06 '16 19:06

ThomasMX


People also ask

Can I use power automate to open Excel file?

Power Automate for desktop provides an extensive variety of Microsoft Excel actions to help you read and manipulate Excel files.

Can PowerShell output to Excel?

As of now, there is no built-in command like CSV (Export-CSV) to export output to the excel file but we can use the Out-File command to export data to excel or any other file format. Let's use Out-File to export the output of the Get-Processes command to an excel file.


2 Answers

You need to open it as a ComObject.

$Excel = New-Object -ComObject Excel.Application
$Workbook = $Excel.Workbooks.Open($FilePath)

In that example you would have needed to define $FilePath as the full path to the Excel file that you are trying to open.

like image 195
TheMadTechnician Avatar answered Oct 21 '22 19:10

TheMadTechnician


I've found a nice snippet which also runs a macro here

# start Excel
$excel = New-Object -comobject Excel.Application

#open file
$FilePath = 'C:\temp\Book1.xlsm'
$workbook = $excel.Workbooks.Open($FilePath)

#make it visible (just to check what is happening)
$excel.Visible = $true

#access the Application object and run a macro
$app = $excel.Application
$app.Run("Macro1")
like image 20
ThomasMX Avatar answered Oct 21 '22 19:10

ThomasMX