Releasing Excel After Using Interop

Releasing Excel After Using Interop
After using Excel Object Model (using Microsoft.Office.Interop.Excel) to connect, read and write excel file, it’s important to release created objects.
For releasing you can create a simple overloaded method. So you can call this method, after you finished your work with excel file.

Method codes are as fallows;

 

     public void releaseObjects(Excel.Application xlapp, Excel.Workbook xlwb, Excel._Worksheet xlws, Excel.Range xlrng)  
     {  
       xlwb.Save(); // saves changes done.  
       xlwb.Close(); // closes workbook.  
       xlapp.Quit(); // quits from application.  
       //releasing objects and setting values to null  
       System.Runtime.InteropServices.Marshal.ReleaseComObject(xlrng);  
       xlrng = null;  
       System.Runtime.InteropServices.Marshal.ReleaseComObject(xlws);  
       xlws = null;  
       System.Runtime.InteropServices.Marshal.ReleaseComObject(xlwb);  
       xlwb = null;  
       System.Runtime.InteropServices.Marshal.ReleaseComObject(xlapp);  
       xlapp = null;  
     }  

Calling method;

     public void excelProcess(string file_destination)  
     {  
       //creating excel application, workbook and worksheets  
       Excel.Application xlapp = new Excel.Application();  
       Excel.Workbook xlwb = xlapp.Workbooks.Open(@file_destination);  
       Excel.Worksheet xlws = xlwb.Sheets[1];  
       Excel.Range xlrng = xlws.UsedRange;  
       //excel process here  
       //excel process here  
       //excel process here  
       //after process finishes, releasing objects by calling method  
       releaseObjects(xlapp, xlwb, xlws, xlrng);  
     }  

Source:

http://www.codeproject.com/Tips/170865/Releasing-Excel-after-using-Interop

İlk yorum yapan olun

Bir yanıt bırakın

E-posta hesabınız yayımlanmayacak.


*