今天在一个项目中使用Dcom的方式获取数据,但是发现Excel进程有时候能杀死,有时候杀不死,导致上传文件时出错的偶发性BUG,经过多次测试,调用API的方式可以彻底杀死Excel进程的方法!

方法体:

  [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
        public static void KillExcel(Excel.Application excel)
        {
            IntPtr t = new IntPtr(excel.Hwnd); //得到这个句柄,具体作用是得到这块内存入口
            int k = 0;
            GetWindowThreadProcessId(t, out k); //得到本进程唯一标志k
            System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用
            p.Kill(); //关闭进程k
        }

方法调用:

 

 Excel.Application app = null;
            Excel.Workbook workBook = null;
            Excel.Worksheet workSheet = null;
            object Missing = Type.Missing;

                app = new Excel.ApplicationClass();
                app.Workbooks.Close();
                app.Workbooks.Open(fileName, Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing,
                    Missing, Missing, Missing, Missing);
                workBook = app.Workbooks[1] as Excel.Workbook;
                workSheet = workBook.Worksheets[1] as Excel.Worksheet;

…………
               workBook.Close(false, fileName, Missing);//关闭worksheet
                app.Workbooks.Close();//关闭workbook
                Marshal.ReleaseComObject(workBook);
                app.Quit();
                KillExcel(app);//彻底杀死Excel进程!

posted on 2012-04-20 23:19  技术绝杀  阅读(955)  评论(0编辑  收藏  举报