获得excel应用程序进程ID

时间:2011-12-13 14:08:22

标签: c# excel-interop

我正在用c#创建一个excel应用程序。 由于我将紧急维护excel文件,我想保持其处理程序打开。 我想保留excel进程ID,以便在系统崩溃时能够终止它。

如何在创建Excel Pid时获取它?

2 个答案:

答案 0 :(得分:29)

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

答案 1 :(得分:-1)

以下是如何使用Excel-Interop打开Excel文件并正确处理实例的示例 (来源:谷歌)

    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();
    }
相关问题