tags:

views:

300

answers:

3

Hi!

I got the same problem. I read the whole thread and tried the examples given. I added these lines to the sample code:

xlRange = (Excel.Range)xlWorkSheet.get_Range("B1", "C1");
xlRange.Merge(Type.Missing);
xlRange = (Excel.Range)xlWorkSheet.get_Range("H5", "M5"); 
xlRange.Merge(Type.Missing);
xlRange = (Excel.Range)xlWorkSheet.get_Range("N5", "V5");
xlRange.Merge(Type.Missing);
xlRange = (Excel.Range)xlWorkSheet.get_Range("W5", "Z5");
xlRange.Merge(Type.Missing);   // up to here everything seems fine

///////////////////////////////////////////////////////////
// if I add these lines below, the process just hanged until
// I manually close the form
xlRange = (Excel.Range)xlWorkSheet.get_Range("AA5", "AB5"); 
xlRange.Merge(Type.Missing); 
xlBorder.Borders.Weight = Excel.XlBorderWeight.xlThin;
///////////////////////////////////////////////////////////

I also added this, before releasing the excelsheet object: Marshal.ReleaseComObject(xlRange);

Please tell me how should I go about this as I am almost giving up on this. Your response is greatly appreciated. FYI, I'm a newbie and I am looking forward to your reply.

Thanks, george

+1  A: 

Excel is a COM Automation Server.

Even though you call Application.Quit() and you Release the Reference to the COM object, the exe itself will not end. You will still be able to see it in task manager. Making further calls to Excel will use the running instance.

The Excel instance will exit after your application closes.

Ever get "RPC server not found/running" type COM errors? Now you know why.

+1  A: 

Hi,

I use this:

private void DoSomeStuff()
{
    var application = new Microsoft.Office.Interop.Excel.Application();
    // Do stuff ...
    CloseExcel(application);
}

private static void CloseExcel(Microsoft.Office.Interop.Excel.Application excel)
{
    while (Marshal.ReleaseComObject(excel) != 0) { }

    excel = null;
    GC.Collect();
    GC.WaitForPendingFinalizers();
}

Works like a charm :)

Vladimir Georgiev
I tried this but it's not working for me.
george
+1  A: 

i've found this method to be most useful:

How to properly cleanup Excel interop objects in c#

keep in mind that you'll need to customize the code for your particular situation. i.e. if you create and hold a reference to the application, a workbook, and three range objects, you'll need to:

  1. Call GC.Collect()
  2. Call GC.WaitForPendingFinalizers()
  3. Call Marshal.FinalReleaseComObject for each of the range objects
  4. Close() the workbook
  5. Call Marshal.FinalReleaseComObject for the book object
  6. Close the application instance
  7. Call Marshal.FinalReleaseComObject for the application object

if you have seven range objects, or hold references to any other objects then you'll need to call Marshal.FinalReleaseComObject for each of those as well. the order in which you release everything is also very important.