Friday, May 4, 2012

How to Release Excel Object in C#. How to kill the COM Excel process:


How to kill the COM Excel process:
Hi friends its very common problem what we face while working with COM object. 
Whenever we try to create/use existing excel spreadsheet using C# Code , we face lot of problem while disposing object. COM objects are beyond the con control of CLR. They need to be disposed externally by the programmer.
This problem was faced many times by developer when many instance of EXCEL.EXE process exist in task manager.
Whenever we create an instance of COM Excel application a new process is created for it.
If we try to perform excel operation again and again without disposing excel object in our code, it cause error so that we can’t create or use excel in our code.
If found following solution to come over this issue:
1.       Create instance of excel object :
Microsoft.Office.Interop.Excel.Application oExcel = new Microsoft.Office.Interop.Excel.Application();
2.       Create Excel book and excel sheet based on you requirements.
3.       After saving excel we need to dispose current excel object by passing excel object to bellow method:
  private void KillExcelProcess( Microsoft.Office.Interop.Excel.Application app)
        {
            try
            {
                if (app != null && !app.Visible)
                {
                    if (app != null)
                    {
                        app.Quit();
                        app = null;
                    }
                    System.Diagnostics.
                    Process[] Processes;
                    Processes = System.Diagnostics.Process.GetProcessesByName("EXCEL");
                    foreach (System.Diagnostics.Process p in Processes)
                    {
                        if (p.MainWindowTitle.Trim() == "")
                            p.Kill();
                    }
                }
            }
            catch (Exception ex)
            {
                            
            }

        }
4.       MainWindowTitle play very important role to find out excel object which is created from code. Excel object which is created from code does not contain any MainWindowTitle.
5.       If you open any document from MS-Excle it has a title. It is very tuff to dispose current excel object using Process id or other attribute of Process class.
6.       Note: its very important to understand if you have more than one windows application that are executing simultaneously and performing Same kind of Excel creation/ Open operation it may cause problem. It will dispose all those objects which are created from code.

F   For any concern feel free to post.
     Happy Coding.......