.net 如何从 powershell 打开 Excel 工作簿以实现自动化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37665118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to open excel workbook from powershell for automation
提问by ThomasMX
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:
我想打开一个excel工作簿并读出数据,做其他类型的操作等等。我知道我必须添加一个程序集引用:
[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.
然后我需要实例化一个 Application 对象。
$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 thisscenario.
然而,这会返回一个错误“找不到构造函数” 顺便说一下,Microsoft.Office.Interop.Excel.Application 实际上不是一个接口吗?我想知道如何在这种情况下实例化它。
回答by TheMadTechnician
You need to open it as a ComObject.
您需要将其作为 ComObject 打开。
$Excel = New-Object -ComObject Excel.Application
$Workbook = $Excel.Workbooks.Open($FilePath)
In that example you would have needed to define $FilePathas the full path to the Excel file that you are trying to open.
在该示例中,您需要定义$FilePath为您尝试打开的 Excel 文件的完整路径。
回答by ThomasMX
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")
回答by ChrisF
Just let Windows take care of the hard part for you:
只需让 Windows 为您处理困难的部分:
explorer.exe $filename
explorer.exe $文件名
Simples :)
简单:)

