Excel application does not quit after automation from Visual Studio .NET client
-
Here is mycode:
private void NullAndRelease(object runtimeObject) { try { System.Runtime.InteropServices.Marshal.FinalReleaseComObject(runtimeObject); } catch {} finally { runtimeObject = null; } } private void button1_Click(object sender, EventArgs e) { Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application(); object NullParam = System.Reflection.Missing.Value; Workbook Book = ExcelApp.Workbooks.Open(FileName, 0, true, NullParam, NullParam, NullParam, true, NullParam, NullParam, false, false, NullParam, false, true, NullParam); Worksheet Sheet = Book.Worksheets[1] as Worksheet; Range UsedRange = Sheet.UsedRange; Range Cell = null; int RowCount = UsedRange.Rows.Count; for (int i = 2; i <= RowCount; i++) { Cell = UsedRange.Cells[i, 1] as Microsoft.Office.Interop.Excel.Range; Cell = UsedRange.Cells[i, 2] as Microsoft.Office.Interop.Excel.Range; Cell = UsedRange.Cells[i, 3] as Microsoft.Office.Interop.Excel.Range; Cell = UsedRange.Cells[i, 4] as Microsoft.Office.Interop.Excel.Range; Cell = UsedRange.Cells[i, 5] as Microsoft.Office.Interop.Excel.Range; Cell = UsedRange.Cells[i, 6] as Microsoft.Office.Interop.Excel.Range; NullAndRelease(Cell); } NullAndRelease(Cell); NullAndRelease(UsedRange); NullAndRelease(Sheet); if (Book != null) Book.Close(false, NullParam, false); NullAndRelease(Book); ExcelApp.Quit(); NullAndRelease(ExcelApp); GC.Collect(); GC.WaitForPendingFinalizers(); }
These code works well.But when I add the following code in the for loop:Cell = UsedRange.Cells[i, 7] as Microsoft.Office.Interop.Excel.Range;
The server does not shut down. It seems that I can only read not more than 6 cells.That's why?