常见.NET功能代码汇总 (3) 33,彻底关闭Excel进程

时间:2022-04-28
本文章向大家介绍常见.NET功能代码汇总 (3) 33,彻底关闭Excel进程,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

33,彻底关闭Excel进程

.NET中使用Excel属于使用非托管资源,使用完成后一般都要用GC回收资源,但是,调用GC的位置不正确,Excel进程可能无法彻底关闭,如下面的代码:

static void OpenExcelTest(int j)
        {
            //Application excel = null;
            excel = new Application();
            excel.Visible = true;
            excel.Workbooks.Open("d:\A1000.xla");
            Workbook wb = excel.Application.Workbooks.Open("d:\Book1.xlsx");
            Worksheet sh = wb.Worksheets.Item["Sheet1"];
            object[,] ssss = sh.Range[sh.Cells[1.1], sh.Cells[3, 1]].Value2;
            Console.WriteLine("opened excel no. {0}", j);
            Console.ReadLine();

            try
            {
                //尝试程序关闭Excel进程
                wb.Close(false);
                sh = null;
                wb = null;
                excel.Quit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("用户已经手工结束了Excel进程,内部错误消息:{0}",ex.Message );
            }
            
            int generation = System.GC.GetGeneration(excel);

            //No.1
            //System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
            //System.Runtime.InteropServices.Marshal.ReleaseComObject(sh);
            //System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
          
            excel = null;
            //No.2
            //GC.Collect(generation);

            Console.WriteLine("close excel no. {0}", j);
            Console.ReadLine();
        }

在上面的代码中,如果取消 No.1,No.2位置处的注释,方法结束后,Excel进程是无法结束的,解决办法,只需要把 GC.Collect(); 这行代码写到方法之外即可。

Application excel = null; 这个Excel应用程序对象定义在方法内或者外都是可以的,哪怕定义一个静态变量,结果都没有影响。