无法 运行 Excel COM 对象作为 SYSTEM

Unable to Run Excel COM Object as SYSTEM

我正在尝试使用带 COM 对象的 PowerShell 打开、写入和保存现有 Excel 文件。我需要使用 COM 对象路由,因为现有 Excel 文件使用 Import/Export-Excel PowerShell 模块不支持的公式。 Excel 2016 已安装在服务器上并且 PowerShell 脚本正在作为 SYSTEM 启动。

我的密码是:

$excel = New-Object -ComObject Excel.Application
$excelWorkbook = $excel.Workbooks.Open($ServerBuildTrackingFilePath)
$excelWorksheet = $excel.WorkSheets.item("VirtualServerBuild")
$excelWorksheet.Activate()
$xlDown = -4121
$xlUp = -4162 
$nextRow = ($excelWorksheet.cells.Range("A1048576").End($xlUp).row) + 1

$excelWorksheet.Cells.Item($nextRow,1) = 'This'
$excelWorksheet.Cells.Item($nextRow,2) = 'is a'
$excelWorksheet.Cells.Item($nextRow,3) = 'Test'

$excelWorkbook.Save()
$excelWorkbook.Close()
$excel.Quit()    
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null

返回的错误是:

Microsoft Excel cannot access the file '\domainfilepath\to\ServerBuildTracking.xlsx'. There 
are several possible reasons:
• The file name or path does not exist.
• The file is being used by another program.
• The workbook you are trying to save has the same name as a currently open workbook.
At line:7 char:1
+ $excelWorkbook = $excel.Workbooks.Open($ServerBuildFilePath ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

官方的回答是,“不,你不能那样做。”

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

-- https://support.microsoft.com/en-us/topic/considerations-for-server-side-automation-of-office-48bcfe93-8a89-47f1-0bce-017433ad79e2

由于 Excel.Application 打开 Excel 的实例进行操作,这意味着您正在尝试的操作明确不受支持。

您可以在网上找到解决方法,使其正常工作,但根据我的经验,它们非常脆弱,并且在更新 Office 或 Windows 时容易崩溃。

我相信官方的解决方案是使用 OpenXML SDK, which is intended for headless operation. However, I've never attempted that (ImportExcel 模块,对我来说效果很好)所以我不知道这有多可行或有多困难。

我对 ImportExcel 模块的评论是,如果您使用 Import-ExcelExport-Excel 命令,或者如果您使用 Open-ExcelPackage 命令。后者是更多类似于 COM 对象的编程操作,但我不确定它是否会破坏您的公式。如果它 确实 破坏了您的公式,我建议您向 ImportExcel 项目提交错误,因为那不应该发生。