Getting excel application process id

2019-01-24 12:18发布

问题:

I am creating an excel application with c#. Since I will maintain the excel file in urgency I want to keep its handler open. I want to keep the excel process id so I will be able to kill it in case the system crashs.

How can I get the Excel Pid when creating it?

回答1:

using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Diagnostics;

class Sample
{
    [DllImport("user32.dll")]
    static extern int GetWindowThreadProcessId(int hWnd, out int lpdwProcessId);

    Process GetExcelProcess(Excel.Application excelApp)
    {
        int id;
        GetWindowThreadProcessId(excelApp.Hwnd, out id);
        return Process.GetProcessById(id);
    }
}


回答2:

Here's an example of how to open an Excel file using Excel-Interop, and properly disposing the instance (source: google)

    Application ExcelObj = new Application();
    Workbook WB = ExcelObj.Workbooks.Open(fileName,
        0, true, 5, "", "", true, XlPlatform.xlWindows, "\t",
        false, false, 0, true, false, false);
    Sheets sheets = WB.Worksheets;
    Worksheet WS = (Worksheet)sheets.get_Item(1);
    Range excelRange = WS.UsedRange;

        ... (DO STUFF?)

        // Get rid of everything - close Excel
        while (Marshal.ReleaseComObject(WB) > 0) { }
        WB = null;
        while (Marshal.ReleaseComObject(sheets) > 0) { }
        sheets = null;
        while (Marshal.ReleaseComObject(WS) > 0) { }
        WS = null;
        while (Marshal.ReleaseComObject(excelRange) > 0) { }
        excelRange = null;
        GC();
        ExcelObj.Quit();
        while (Marshal.ReleaseComObject(ExcelObj) > 0) { }
        ExcelObj = null;
        GC();

    public static void GC()
    {
        System.GC.Collect();
        System.GC.WaitForPendingFinalizers();
        System.GC.Collect();
        System.GC.WaitForPendingFinalizers();
    }