Excel automation: excel process still alive after call quit()!–solved

when use excel automation to edit data probably the process ‘excel.exe’ is still alive and stays in process list.

the reason is some COM objects are still referenced, must release them and process will exit.

and one another reason: in .net must collect the garbages manually!

 

ALL BOLD STATEMENTS ARE REQUIRED!

 

           ExcelApplication excel = new ExcelApplication();
           excel.DisplayAlerts = false;
           Workbook book = excel.Workbooks.Open(xlsxfile,
           Type.Missing, Type.Missing, Type.Missing, Type.Missing,
           Type.Missing, Type.Missing, Type.Missing, Type.Missing,
           Type.Missing, Type.Missing, Type.Missing, Type.Missing,
           Type.Missing, Type.Missing);

           Worksheet sheet1 = (Worksheet)book.Worksheets.get_Item(2);
           string idx = "ABCDEFGHIJKLMN";

           for (int i = 0; i < 10; i++)
           {
               Range rg = ((Range)sheet1.Columns[idx[i].ToString(), Type.Missing]);
               rg.AutoFit();
               Marshal.ReleaseComObject(rg);
           }


           book.Save();
           book.Close();
           excel.Quit();
           Marshal.ReleaseComObject(sheet1);
           Marshal.ReleaseComObject(book);
           Marshal.ReleaseComObject(excel);
           GC.Collect();
           GC.WaitForPendingFinalizers();

posted on 2010-11-26 18:23  无法显示此网页  阅读(247)  评论(0编辑  收藏  举报

导航