2011-12-13 23 views
6

Tôi đang tạo một ứng dụng excel với C#. Vì tôi sẽ duy trì tệp excel trong trường hợp khẩn cấp, tôi muốn giữ trình xử lý của nó mở. Tôi muốn giữ id quá trình excel vì vậy tôi sẽ có thể giết nó trong trường hợp hệ thống gặp sự cố.Nhận mã quá trình ứng dụng excel

Làm cách nào để lấy Excel Pid khi tạo?

+0

bạn có thể bắt đầu nói với chúng ta như thế nào bạn tạo/mở excel ? hiển thị một số mã xin vui lòng –

+1

Bạn cần PID để làm gì? bạn có thể tự giải phóng các đối tượng Com – Shai

Trả lời

-2

Dưới đây là một ví dụ về làm thế nào để mở một file Excel sử dụng Excel-Interop, và xử lý đúng thẩm (nguồn: 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

Tại sao bạn lại downvote? Chỉ cần tò mò .. – abhilash

+0

Beats me! ví dụ mã này là 100% làm việc ... – Shai

+0

Có thể bị bỏ phiếu vì nó không trả lời câu hỏi! Nếu Excel đi ra ngoài ăn trưa, mà nó thường làm, giải phóng tất cả các tài liệu tham khảo của bạn với nó sẽ không giết nó. Bạn CẦN ID quá trình. –

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

hoạt động rất tốt cảm ơn bạn! – Belial09

Các vấn đề liên quan