用户打开Excel文件进​​行数据input后,在Windows中closuresExcel进程

程序打开Excels,读取工作表并填充每张工作表的数据。 对于打开的每个Excel来获取input数据,Windows进程列表中将会有一个Excel进程。 如果用户在运行期间随着时间的推移打开了许多Excels,将会有许多Excel进程在Windows中运行。

问题是,如果你去到一个文件夹,并试图打开一个以编程方式打开的Excel,它将只能被读取,因为在Windows中运行的Excel进程保留着它。 Windows中的每个Excel进程都需要终止才能释放每个以编程方式打开的Excal。

Imports Excel = Microsoft.Office.Interop.Excel ' Create new Application. Dim rXL As New Excel.Application Dim rWB As Excel.Workbook ' Dim rSheet As Excel.Worksheet Dim rRng As Excel.Range Dim buffmatrix(,) As Object rWB = rXL.Workbooks.Open(filename) Dim sheet As Excel.Worksheet For i = 1 To rWB.Sheets.Count To 1 Step -1 ' Get sheet. sheet = rWB.Sheets(i) ' Get range. Dim r As Excel.Range = sheet.UsedRange If r.Rows.Count = 0 Then Exit For ' Load all cells into 2d array. Dim eCellArray As System.Array = r.Value ' eCellArray is used for processing here Marshal.ReleaseComObject(Sheet) rRng = Nothing Next rWB = Nothing rXL = Nothing 

上面循环中的Marshal.ReleaseComObject(Sheet)命令不起作用,也就是说,它不会终止Windows中的Excel进程。

我解决了使用这个代码

  WorkBook As Microsoft.Office.Interop.Excel.Workbook WorkBook ExcelInstance As Microsoft.Office.Interop.Excel.ApplicationClass WorkBook.Close(_missing, _missing, _missing) System.Runtime.InteropServices.Marshal.FinalReleaseComObject(WorkBook) ExcelInstance.Quit() ExcelInstance.Application.Quit() System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ExcelInstance) GC.Collect() GC.WaitForPendingFinalizers()