I have the following code:
private bool IsMousetrapFile(string path)
{
logger.Log(validateFileMessage + path);
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbooks workbooks = xlApp.Workbooks;
Excel.Workbook xlWorkBook = workbooks.Open(path, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Excel.Sheets worksheets = (Excel.Sheets)xlWorkBook.Worksheets;
Excel.Worksheet ws = null;
foreach (string sheet in expectedWorksheets)
{
try
{
ws = (Excel.Worksheet)worksheets.get_Item(sheet);
logger.Log(validMousetrapFileMessage + path);
}
catch
{
logger.Log(validateSheetError + sheet + ": " + path);
if (ws != null)
Marshal.ReleaseComObject(ws);
Marshal.ReleaseComObject(worksheets);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(workbooks);
Marshal.ReleaseComObject(xlApp);
return false;
}
}
if (ws != null)
Marshal.ReleaseComObject(ws);
Marshal.ReleaseComObject(worksheets);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(workbooks);
Marshal.ReleaseComObject(xlApp);
return true;
}
Effectively, it checks if an Excel workbook contains specific sheets. Irrespective of whether there is or isn't, I want to Excel processes to end. However, each time a new workbook is open, a new process is added, and never deleted?
PS. I know there is duplicate code there....it shall be tidied soon :)
Use Excel.Application.Quit()
when you are done with processing or whatever you are doing.
In your case: xlApp.Quit();
UPDATE:
@Lasse V. Karlsen pointed out what to do if Excel was already running. Well, here is one solution: ( i did not test the code, this is just to give you an idea )
private void TestMethod()
{
bool excelWasRunning = System.Diagnostics.Process.GetProcessesByName("excel").Length > 0;
// your code
if (!excelWasRunning)
{
xlApp.Quit();
}
}
My solution
[DllImport("user32.dll")]
static extern int GetWindowThreadProcessId(int hWnd, out int lpdwProcessId);
private void GenerateExcel()
{
var excel = new Microsoft.Office.Interop.Excel.Application();
int id;
// Find the Process Id
GetWindowThreadProcessId(excel.Hwnd, out id);
Process excelProcess = Process.GetProcessById(id);
try
{
// Your code
}
finally
{
excel.Quit();
// Kill him !
excelProcess.Kill();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With