title: Saving and Closing an Excel File Created in C# .Net Using Excel Office Interop dll
body: <p>I'm having a really hard time finding good documentation on how to properly close and save an Excel file using the Exce; Office Interop dll.</p>
  
  <p>Basically, I have everything working with regards to creating a new Excel workbook and filling the first worksheet with data from a list (when I set the visible property to true on the application object I can watch the Excel file open and fill the worksheet exactly the way I want it to.)</p>
  
  <p>I just need to know how to properly close the Excel file and save it to a location of my choice.  I want to make sure I kill Excel completely when the code is done -- don't want it to continue to hold memory when I'm finished.</p>
  
  <p>Right now I am doing the following after filling the worksheet with the data I want:</p>
  
  <pre><code>workbook.Save();
  workbook.Close(Type.Missing, Type.Missing, Type.Missing);
  application.Quit();
  </code></pre>
  
  <p><strong>UPDATE:</strong> I am now able to save the Excel file to the location I want.  I simply removed the Save() call and changed the Close call to (true, filePath, Type.Missing) and it is now putting the file in the desired location.</p>
  
  <p>Only issue to resolve is properly closing the COM object. </p>
  
  <p><strong>POSSIBLE SOLUTION</strong> At least this seems to remove Excel from the task manager every time the code finishes executing.</p>
  
  <pre><code>// Close the workbook, tell it to save and give the path.
  workbook.Close(true, workbookPath, Type.Missing);
  
  // Now quit the application.
  application.Quit();
  
  // Call the garbage collector to collect and wait for finalizers to finish.
  GC.Collect();
  GC.WaitForPendingFinalizers();
  
  // Release the COM objects that have been instantiated.
  Marshal.FinalReleaseComObject(workbook);
  Marshal.FinalReleaseComObject(worksheet);
  Marshal.FinalReleaseComObject(workrange);
  Marshal.FinalReleaseComObject(application);
  </code></pre>
  
  <p>I believe this will work.  I think the problem was that I wasn't releasing everything that had been instantiated and I think forcing the GC to collect was the final missing piece. I ran this 20 times and every time Task Manager would show Excel and then remove it once the code finished.</p>
  
  <p><strong>FINAL UPDATE:</strong>  The code above is definitely disposing of all the COM objects and everything is working properly. </p>