发布excel实例创build

我正试图获得一个工作表的副本到另一个工作表,下面是我的代码..我试图释放创build的Excel的实例,但仍然看到它在TaskManager中的一个实例。

C#代码:

try { wBook = xCel.Workbooks.Open(filePath); xCel.Visible = false; this.xCel.DisplayAlerts = false; wBook = (Excel.Worksheet)wBook.Worksheets.get_Item(1); wBook.Copy(Type.Missing, Type.Missing); wBook = (Excel.Worksheet)wBook.Sheets[1]; wBook.SaveAs(strFileCopyPath); } finally { if (wBook != null) { wBook.Close(); Thread.Sleep(500); } Marshal.ReleaseComObject(wBook); Marshal.ReleaseComObject(wBook); } 

请有人告诉我在这里做什么错? 谢谢

你什么都不做是错误的,但是closuresexel的概念是非常无礼的。 那是因为:1:Excel有时会创build中间对象,而这些中间对象对您来说是不可见的,尤其是如果您这样做:DIm bla = excel.worksheet.range(“A1”).value。 然后有excel的中间对象。 2:excel对象必须按照特定的顺序closures。

这段代码应该帮助:

 GC.Collect() GC.WaitForPendingFinalizers() GC.Collect() GC.WaitForPendingFinalizers() 

由于第一遍只标记中间对象,而不会破坏它们,所以这必须是双重的。 这是垃圾收集。

还按以下顺序销毁对象:范围等工作表工作簿APP

喜欢这个:

 System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlSheet) xlsheet = nothing xlBook .Close() System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlBook ) xlbook = nothing xlapp.quit System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlapp) xlapp = nothing 

使用try catch来捕获本节中的错误,如果一个对象是没有的话。

您忘记调用Excel.Application对象的Quit()方法。 通常我使用下面的代码来closuresExcel(VB.Net代码片段):

 xlApp.Quit() System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp) xlApp = Nothing xlBook = Nothing xlSheet = Nothing