【问题标题】:Unable to Run Excel COM Object as SYSTEM无法以 SYSTEM 身份运行 Excel COM 对象
【发布时间】:2021-10-21 04:42:20
【问题描述】:

我正在尝试使用带有 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

【问题讨论】:

  • 还要注意,AD servername$ 对象对正在使用的文件具有完全控制访问权限

标签: excel powershell scripting system comobject


【解决方案1】:

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

Microsoft 目前不推荐也不支持任何无人值守、非交互式客户端应用程序或组件(包括 ASP、ASP.NET、DCOM 和 NT 服务)的 Microsoft Office 应用程序自动化,因为 Office 可能表现出不稳定Office 在此环境中运行时的行为和/或死锁。

-- 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,它用于无头操作。但是,我从未尝试过(ImportExcel 模块对我来说效果很好),所以我不知道这有多可行或有多困难。

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

【讨论】:

    猜你喜欢
    • 2018-11-16
    • 2016-01-25
    • 2011-10-03
    • 2016-02-02
    • 2011-03-27
    • 2017-05-19
    • 1970-01-01
    相关资源
    最近更新 更多