I have some code that opens a spreadsheet, reads some values, and then closes the sheet. I need to do this for multiple files. The problem I\'m having is that the Excel applic
Use Marshal.FinalReleaseComObject() to release the resources
If you read multiple files one after the other then performance wise it is much better to open/close Excel Application only once and move the open/close application part to separate functions
Refactored Code:
static Excel.Application OpenExcel(){
Excel.Application excel = null;
try{
excel = new Excel.Application();
return excel;
}
catch(Exception ex){
log(ex.Message);
return null;
}
}
static void ParseFile(string file)
{
try
{
System.Console.WriteLine("parsing:" + file);
Excel.Workbook wb = excel.Workbooks.Open(file);
Excel.Worksheet ws = wb.Worksheets[1];
for (int i = 2; i < 27; i++)
{
log(ws.Cells[i, 1].Text);
}
wb.Close(false);
}
catch (Exception ex)
{
log(ex.Message);
}
finally{
Marshal.FinalReleaseComObject(ws);
Marshal.FinalReleaseComObject(wb);
ws = null;
wb = null;
}
}
static void CloseExcel(Excel.Application excel){
try{
excel.Quit();
}
catch(Exception ex){
log(ex.Message);
}
finally{
Marshal.FinalReleaseComObject(excel);
excel = null;
}
}
Usage:
Excel.Application excel = OpenExcel();
if(excel != null){
// Parse files in a loop
ParseFile("fileName");
// Close excel after parsing all files
CloseExcel(excel);
}