How to properly close Excel when finished?

D

David Berman

Hi, I've written an application to do a while bunch of Excel automation.
I open a file, scan through all the worksheets, extract data, and then I
try to close Excel. However, I can see that I'm not doing it
effectively. If I am debugging my app, and I kill the app before my app
exits, but after the call that should close excel, I still have an
excell process sitting around. After about 20 + of those stack up, you
start to feel it.
If I quit all the way out of my app, somehow Excel DOES get cleaned up
and the instance / process is closed.

So, how do I properly close an instance of excel?

Thank you!


Currently doing it this way:

public void ExtractDataFromExcel(string fileName)
{

// Instantiate an Excel control object
ExcelObj = new Excel.Application();

// Disable alert messages
ExcelObj.DisplayAlerts = false;

// See if the Excel Application Object was successfully constructed
if (ExcelObj == null)
{
MessageBox.Show("ERROR: EXCEL couldn't be started!");
System.Windows.Forms.Application.Exit();
}

theWorkbook = ExcelObj.Workbooks.Open(
fileName, // Filename
0, // Update links
true, // Read only
5, // Format
"", // Password
"", // Write res password
true, // Ignore read-only recommend
Excel.XlPlatform.xlWindows, // Origin
"\t", // Delimiter (\t = tab delimited)
false, // Editable
false, // Notify
0, // Converter
false, // AddToMru
0, // Local
true // Corrupt load
);

// get the collection of sheets in the workbook
sheets = theWorkbook.Worksheets;


{ ... do some work ... }

// Close Excel workbook
theWorkbook.Close(false, fileName, 0);

object saveChanges = Missing.Value;
object originalFormat = Missing.Value;
object routeDocument = Missing.Value;

ExcelObj.Quit(); // ref saveChanges, ref originalFormat, ref
routeDocument);


} // end of method


Meet people for friendship, contacts,
or romance using free instant messaging software! See a picture you
like? Click once for a private conversation with that person!

www.SOCIALNETWORK.com
 
D

David Berman

Thanks for the link, but it's specifically for a Java solution. Does
anyone have an equivalent for C#?

David




Meet people for friendship, contacts,
or romance using free instant messaging software! See a picture you
like? Click once for a private conversation with that person!

www.SEN.us
 
R

Ron Allen

David,
Make sure you call Marshal.ReleaseComObject on each Excel object you
reference in your code and set them all to null/Nothing afterwards.

Ron Allen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top