Common way to kill the Excel process
The code follows:
Notice:
Why we needn't release the Worksheet and Workbook COM object? That is we release the Worksheets and Workbooks object, who is the collection of Worksheet and Workbook, so the sub object will be release togother.
When we use the Worksheets and Workbooks object, and have not defiend them, the Excel process will not be killed. So before we use the Worksheets and Workbooks must to declare them! The detail code had been belowed.
Good Luck!
1
string path = @"D:\\test.xls";
2
Excel.ApplicationClass app = new Microsoft.Office.Interop.Excel.ApplicationClass();
3
Excel.Workbooks oWorkBooks = app.Workbooks;
4
Excel.Workbook oWorkBook = null;
5![]()
6
oWorkBook = oWorkBooks.Open(path, Type.Missing, (object)false, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
7
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
8![]()
9
Excel.Sheets sheets = oWorkBook.Sheets;
10
Excel.Worksheet oWorkSheet = (Excel.Worksheet)sheets.get_Item(1);
11
oWorkSheet.get_Range("A1", Type.Missing);
12![]()
13
14![]()
15
16
//oWorkBook.Close(Type.Missing, Type.Missing, Type.Missing);
17
18
//oWorkBooks.Close();
19
NAR(oWorkSheet);
20
NAR(sheets);
21
//NAR(oWorkBook);
22
NAR(oWorkBooks);
23
app.Quit();
24
NAR(app);
25
26
GC.Collect();
string path = @"D:\\test.xls";2
Excel.ApplicationClass app = new Microsoft.Office.Interop.Excel.ApplicationClass();3
Excel.Workbooks oWorkBooks = app.Workbooks;4
Excel.Workbook oWorkBook = null;5

6
oWorkBook = oWorkBooks.Open(path, Type.Missing, (object)false, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,7
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); 8

9
Excel.Sheets sheets = oWorkBook.Sheets;10
Excel.Worksheet oWorkSheet = (Excel.Worksheet)sheets.get_Item(1);11
oWorkSheet.get_Range("A1", Type.Missing);12

13
14

15
16
//oWorkBook.Close(Type.Missing, Type.Missing, Type.Missing);17
18
//oWorkBooks.Close();19
NAR(oWorkSheet);20
NAR(sheets);21
//NAR(oWorkBook);22
NAR(oWorkBooks);23
app.Quit();24
NAR(app);25
26
GC.Collect(); 1
public void NAR(object o)
2
{
3
try
4
{
5
System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
6
}
7
catch
8
{
9
}
10
finally
11
{
12
o = null;
13
}
14
}
public void NAR(object o)2
{3
try4
{5
System.Runtime.InteropServices.Marshal.ReleaseComObject(o);6
}7
catch8
{9
}10
finally11
{12
o = null;13
}14
}Notice:
Why we needn't release the Worksheet and Workbook COM object? That is we release the Worksheets and Workbooks object, who is the collection of Worksheet and Workbook, so the sub object will be release togother.
When we use the Worksheets and Workbooks object, and have not defiend them, the Excel process will not be killed. So before we use the Worksheets and Workbooks must to declare them! The detail code had been belowed.
Good Luck!

浙公网安备 33010602011771号