And finally, kill Excel...

Posted by Ryan Baxter Thu, 15 Jan 2009 04:07:00 GMT

Everyone who’s worked with Excel on the Microsoft .NET framework has dealt with the problem of hanging Excel processes. The C# solution below is not very elegant, but it stops those pesky Excel processes from hanging around.

using System.Diagnostics;
using System.Runtime.InteropServices;

[DllImport("user32.dll")]
private static extern
    int GetWindowThreadProcessId(int hWnd, out int processId);

private static void CreateSpreadsheet()
{
    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

    try
    {
      // Create Excel spreadsheet.
    }
    catch (Exception ex)
    {
      // Do something with the exception.
    }
    finally
    {
      KillExcel(excel.hWnd);
    }
}

private static void KillExcel(int hWnd)
{
    int processId;
    int threadProcessId = GetWindowThreadProcessId(hWnd, out processId);

    Process.GetProcessById(processId).Kill();
}
Comments

Leave a response

Avatar
Alex Comment_bubble about 1 month later:
Brilliant, thank you!
Avatar
Ryan Baxter Comment_bubble about 1 month later:
Thanks! My solution will only work with Excel 2003 and above. Check out 50 Ways to Kill Excel for a more detailed process.