2011-12-13 18 views
6

Estoy creando una aplicación de Excel con C#. Como mantendré el archivo excel en urgencia, quiero mantener abierto su controlador. Quiero mantener el ID del proceso de Excel, así podré eliminarlo en caso de que el sistema falle.Getting excel application process id

¿Cómo puedo obtener el Excel Pid al crearlo?

+0

se puede empezar a decirnos cómo crear/abrir excel ? muestra un código, por favor –

+1

¿Para qué necesitas el PID? puede liberar los objetos Com usted mismo – Shai

Respuesta

-2

Aquí hay un ejemplo de cómo abrir un archivo de Excel utilizando Excel-Interop, y disponer adecuadamente la instancia (Fuente: 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(); 
    } 
+0

¿Por qué el voto a favor? Sólo curiosidad ... – abhilash

+0

Me late! este ejemplo de código está funcionando al 100% ... – Shai

+0

Probablemente haya votado negativamente porque no responde la pregunta. Si Excel sale a almorzar, lo que a menudo sucede, liberar todas sus referencias no lo va a matar. NECESITA la identificación del proceso. –

22
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); 
    } 
} 
+0

funciona muy bien ¡gracias! – Belial09