为什么Excel资源的发布不会终止进程?

时间:2016-10-24 10:33:36

标签: c# excel com

我需要以xlsx格式创建报告。创建报告并保存文件后,我将释放资源,但进程不会从任务管理器中消失。这是我的方法。

            excelApplication = new Excel.Application();
            wBooks = excelApplication.Workbooks;
            wBook = wBooks.Add(Excel.XlSheetType.xlWorksheet);
            sheet = (Excel.Worksheet)excelApplication.ActiveSheet;

            for (int j = 0; j < outDistribution.Count; j++)
            {
                var sh = (Excel.Range)sheet.Cells[j + 1];
                sh.Value2 = outDistribution[j];
                Marshal.ReleaseComObject(sh);
            }

            SaveFile(wBook);
        }
        catch (Exception ex)
        {

        }
        finally
        {
            Helper.ReleaseCOMObject(sheet);
            Helper.ReleaseCOMObject(wBook);
            Helper.ReleaseCOMObject(wBooks);
            Helper.ReleaseCOMObject(excelApplication);
        }

ReleaseCOMObject方法:

public void ReleaseCOMObject(object obj)
    {            
        if (obj is Excel.Worksheet)
        {
            Marshal.FinalReleaseComObject(((Excel.Worksheet)obj).Cells);
            Marshal.ReleaseComObject(obj);
            obj = null;
        }

        if (obj is Excel.Workbook)
        {
            ((Excel.Workbook)obj).Close(false);
            Marshal.ReleaseComObject(obj);
            obj = null;
        }

        if (obj is Excel.Workbooks)
        {
            ((Excel.Workbooks)obj).Close();
            Marshal.ReleaseComObject(obj);
            obj = null;
        }

        if (obj is Excel.Application)
        {
            ((Excel.Application)obj).Quit();
            Marshal.ReleaseComObject(obj);
            obj = null;
        }
    }

我已经在这个资源和其他人上发布了很多帖子,但对我来说没什么用。

0 个答案:

没有答案