我正在使用以下方式从Winform中打开一个excel文件:
Dim xlsApp3 As Excel.Application
Dim xlsWB3 As Excel.Workbook
xlsApp3 = CreateObject("Excel.Application")
xlsApp3.Visible = True
xlsWB3 = xlsApp3.Workbooks.Open("C:\myfile.xlsm")
Try
Marshal.ReleaseComObject(xlsWB3)
Marshal.ReleaseComObject(xlsApp3)
xlsWB3 = Nothing
xlsApp3 = Nothing
Catch ex As Exception
xlsWB3 = Nothing
xlsApp3 = Nothing
Finally
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
End Try
当我查看任务管理器时,它会关闭过程,但是一旦我关闭打开的excel应用程序窗口,过程又回来了吗?如果我关闭了整个winform应用程序,那就是excel进程关闭时。应用程序是否在内存中保留该进程?
答案 0 :(得分:1)
添加以下几行:
xlsWB3.Close(True, Type.Missing, Type.Missing)
xlsApp3.Quit
答案 1 :(得分:0)
请勿像访问
那样访问带有两个点的非托管内容xlsApp3.Workbooks.Open
Workbooks对象在后台打开,但是.NET不知道它,因此无法正确清理它。
相反,您需要对Workbooks进行.NET引用,GC会为您清理所有内容。您的整个代码段都可以减少为此
Dim xlApp = New Excel.Application()
Dim xlBooks = xlApp.Workbooks
Dim xlBook = xlBooks.Open("C:\myfile.xlsm")
xlApp.Visible = True