您的位置:首页 > 其它

Common way to kill the Excel process

2007-04-12 16:32 357 查看
The code follows:

1string 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();

1public 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 }

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!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: