zoukankan      html  css  js  c++  java
  • 在ASP.Net中如何彻底杀死Excel进程

    今天在一个项目中使用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进程!

  • 相关阅读:
    做了6年开发,工资涨不上去,怎么办?(安晓辉,循循善诱的分析)
    Hello World
    服务治理框架
    Range锁(也即范围锁)
    C# .NET Socket
    Net Core应用,在CentOS上运行
    分布式锁,进程锁,线程锁
    TEMPDB
    学会Git
    Docker
  • 原文地址:https://www.cnblogs.com/zhangxb/p/2460739.html
Copyright © 2011-2022 走看看