Excel对象使用后进程不能退出的完美解决办法

主要原因是:程序并没有完全释放掉使用的资源,虽然程序正常关闭,程序本身也可以自动释放原来使用的资源,但Excel进程并不能判断到,只要Excel使用的资源有没有释放的,Excel进程就不会关闭。
解决办法:使用完Excel.Application对象后,关闭所有使用资源。如:app._Workbools / Sheets / _Workbook 等,最后 app.Quit()。

以下是我写的一个分析指定 Excel 文件子表名列表的方法,供参考:

       ///
        /// 获得指定 xls 文件中 Sheet 子表名的列表
        ///
        ///
        ///
        public static string[] GetSheetList(string xlsFile)
        {
            if (!File.Exists(xlsFile))
            {
                return null;
            }

            // 初始化 Excel 组件变量
            object opt = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Excel.Application app = null;
            _Workbook book = null;
            Sheets sheets = null;
            _Worksheet[] wsArray = null;

            app = new Microsoft.Office.Interop.Excel.Application();
            book = app.Workbooks.Open(xlsFile, opt, true, opt, opt, opt, true, opt, opt, opt, false, opt, opt, opt, opt);    // 只读,不可编辑;
            sheets = book.Worksheets;

            // 列举出所有表
            wsArray = new _Worksheet[sheets.Count];
            string[] sheetNames = new string[sheets.Count];
            for (int i = 0; i < sheets.Count; i++)
            {
                wsArray[i] = (_Worksheet)sheets.get_Item(i + 1);         // 从 1 开始索引
                sheetNames[i] = wsArray[i].Name;
            }

            app.Workbooks.Close();          // 关闭所有工作 Book
            app.Quit();

            // 强制回收 Excel 进程
            int geneID = System.GC.GetGeneration(app);
            wsArray = null;
            sheets = null;
            book = null;
            app = null;
            System.GC.Collect(geneID);

            return sheetNames;
        }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值