.Net Interop Excel ExportAsFixedFormat() 异常 HResult:0x800A03EC

.Net Interop Excel ExportAsFixedFormat() Exception HResult: 0x800A03EC

我目前正在实施一种生成多张工作表并将其导出为 PDF 的方法。为此,我将 Microsoft.Office.Interop 库 (v14.0.0.0) 与 .NET 4.5.2 一起使用。 运行办公室是2016年

我的代码:

Dim excel As New Application()
excel.Visible = False
excel.DisplayAlerts = False
Dim workbooks As Workbooks
workbooks = excel.Workbooks
Dim workbook As Workbook = workbooks.Add(Type.Missing)

[...]

workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, String.Format(<a Path>)
ReleaseComObject(workSheet)
workbook.Close()
ReleaseComObject(workbook)
excel.Quit()
ReleaseComObject(excel)

ReleaseComObject() 看起来像这样(根据 Microsoft Support):

Private Sub ReleaseComObject(objectToRelease As Object)
        While System.Runtime.InteropServices.Marshal.ReleaseComObject(objectToRelease) > 0
        End While
        objectToRelease = Nothing
End Sub

如果我 运行 将此代码迭代一次 但是 我注意到 EXCEL-Process 仍然是 运行ning .

如果我尝试在批处理模式下执行此操作(在 for 循环的意义上),我会在进入第二次交互时得到一个异常:

System.Runtime.InteropServices.COMException (0x800A03EC): Ausnahme von HRESULT: 0x800A03EC bei Microsoft.Office.Interop.Excel.WorkbookClass.ExportAsFixedFormat(XlFixedFormatType Type, Object Filename, Object Quality, Object IncludeDocProperties, Object IgnorePrintAreas, Object From, Object To, Object OpenAfterPublish, Object FixedFormatExtClassPtr) bei Controller.CreateListing(DataTable data, Int32 year, String mandantShortName) in ...

抛出异常的行:

workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, String.Format(<a Path>)

对于 reseach/testing 我在重新进入循环之前进行了调试并终止了 excel-process 但 w/o 任何更改。

有人也遇到过这个问题吗? Solutions/Suggestions?

我刚刚弄清楚是什么问题导致的(自己的Bug)。

但这仍然悬而未决,为什么 Excel-进程没有关闭。

为了解决 Excel 没有正确关闭的问题替换:

Private Sub ReleaseComObject(objectToRelease As Object)
    While System.Runtime.InteropServices.Marshal.ReleaseComObject(objectToRelease) > 0
    End While
    objectToRelease = Nothing
End Sub

加上code as illustrated by Siddharth Rout的这一点:

Private Sub ReleaseObject(ByVal obj As Object)
    Try
        Dim intRel As Integer = 0
        Do
            intRel = System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
        Loop While intRel > 0
        obj = Nothing
    Catch ex As Exception
        obj = Nothing
    Finally
        GC.Collect()
    End Try
End Sub

您可以使用 While 语句代替 Do 语句,但我觉得这样读起来更好。这里重要的一点是 GC.Collect().

您还必须确保以正确的顺序发布并发布一切。这通常是 backwards 顺序。因此,在您的情况下,从 workSheet 开始,然后是 workbook,然后是 workbooks,最后是 excel:

ReleaseObject(workSheet)
workbook.Close()
ReleaseObject(workbook)
ReleaseObject(workbooks)
excel.Quit()
ReleaseObject(excel)

这是我放在一起测试的代码:

Dim app As New Excel.Application()
app.Visible = False
app.DisplayAlerts = False

Dim wbs As Excel.Workbooks = app.Workbooks
Dim wb As Excel.Workbook = wbs.Add()
Dim ws As Excel.Worksheet = CType(wb.Sheets(1), Excel.Worksheet)

ReleaseObject(ws)
wb.Close()
ReleaseObject(wb)
ReleaseObject(wbs)
app.Quit()
ReleaseObject(app)

进程启动,一旦 ReleaseObject(app) 被调用,进程就会关闭。

尝试运行应用程序或服务作为管理帐户。这解决了我的问题。