获得excel应用程序进程ID

yoa*_*vba 9 c# excel-interop

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

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

Nic*_*zer 33

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Sha*_*hai -1

以下是如何使用 Excel-Interop 打开 Excel 文件并正确处置实例的示例(来源: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();
    }
Run Code Online (Sandbox Code Playgroud)

  • 是的你是。通过 COM 启动的 Excel 进程不是您的进程的子进程,它们是 svchost.exe 的子进程。如果 Excel 正在执行阻塞操作(例如 QueryTable.Refresh()),并且您的进程退出,excel.exe 将不会终止。如果您在线程或子进程中进行这些刷新(您可能需要终止这些刷新),那么您注定会积累僵尸 Excel 进程,除非您可以跟踪它们的进程 ID 并杀死它们。 (5认同)