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  
       xlrng = null;  
       xlws = null;  
       xlwb = null;  
       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);  


Bir cevap yazın

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