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

时间:2017-02-22 10:42:48

标签: vb.net excel-interop comexception

我目前正在实施一种生成多张工作表并将其导出为PDF的方法。为此,我使用Microsoft.Office.Interop Library(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仍在运行。

如果我尝试在批处理模式下执行此操作(在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数据,Int32年,String mandantShortName)...

抛出异常的行:

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

对于研究/测试,我在重新进入循环之前进行了调试并杀死了excel-process但没有任何变化。

任何人都遇到过这个问题吗?解决方案/建议?

3 个答案:

答案 0 :(得分:2)

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

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

code所示的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()

您还必须确保以正确的顺序发布并发布所有内容。这通常是向后顺序。因此,在您的情况下,先从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),流程就会关闭。

答案 1 :(得分:0)

我只知道问题导致了什么(自己的Bug)。

但它仍然存在问题,为什么Excel-Proccess无法关闭。

答案 2 :(得分:0)

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