C# = Why are Excel processes not ending?

折月煮酒 提交于 2019-11-30 18:09:32
HABJAN

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();
   }
}
Loart

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();
}

Few days back I have implemented Export/Import. I got below code from somewhere when I have searched on Google and it works fine.

ExportToExcel()
{
    try
    {
        //your code
    }
   catch (Exception ex)
        {

        }
        finally
        {
            TryQuitExcel(Application_object);
        }
}
private static void TryQuitExcel(Microsoft.Office.Interop.Excel.Application  application)
        {
            try
            {
                if (application != null &&
                  application.Workbooks != null &&
                  application.Workbooks.Count < 2)
                {
                    application.DisplayAlerts = false;
                    application.Quit();
                    Kill(application.Hwnd);
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(application);
                    application = null;
                }
            }
            catch
            {
                /// Excel may have been closed via Windows Task Manager.
                /// Skip the close.
            }
        }


 private static void Kill(int hwnd)
    {
        int excelPID = 0;
        int handle = hwnd;
        GetWindowThreadProcessId(handle, ref excelPID);

        Process process = null;
        try
        {
            process = Process.GetProcessById(excelPID);

            //
            // If we found a matching Excel proceess with no main window
            // associated main window, kill it.
            //
            if (process != null)
            {
                if (process.ProcessName.ToUpper() == "EXCEL" && !process.HasExited)
                    process.Kill();
            }
        }
        catch { }
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!