2017-07-10 3 views
-2

Ich habe einen Code geschrieben, aber ich kann Application.Cells nicht korrekt freigeben. Kann mir jemand helfen, Excel.exe im Taskmanager freizugeben?Wie man Application.Cells richtig freigibt?

using Excel = Microsoft.Office.Interop.Excel; 

Excel.Application app = null; 
Excel.Workbooks books = null; 
Excel.Workbook book = null; 
Excel.Sheets sheets = null; 

    for (int a = 0; a < dgrviRoute.RowCount; a++) 
    { 
     for (int b = 0; b < dgrviRoute.ColumnCount; b++) 
      { 
       DataGridViewRow row = dgrviRoute.Rows[a];          
       DataGridViewCell cell = row.Cells[b];          
       var value = cell.Value;                  
       app.Cells[a + 2, b + 1] = value; 
       /* 
       I still see the Excel.exe process in the Windows Task Managers’ 
       list of background processes. 

       This strange phenomenon occurs because in the above code, 
       Iam not releasing any COM objects and we’re also “chaining” 
       object references by using app.Cells[a + 2, b + 1]. 
       */ 

       /* 
       if (app.Cells[a + 2, b + 1] != null) Marshal.FinalReleaseComObject(app.Cells[a + 2, b + 1]); 
       GC.Collect(); 
       GC.WaitForPendingFinalizers(); 
       GC.Collect(); 
       GC.WaitForPendingFinalizers(); 
       */ 
      }      
    } 

Ich las bei hier einige Tutorial How to properly release Excel COM objects

Antwort

1

Dies ist ein langer Kampf. Ich habe alles für meine Apps ausprobiert. Es hat nicht geklappt. Die Verwendung von OpenXML ist besser für einfache Schreibfunktionen. Es ruft keine Excel-Anwendung auf, sondern manipuliert nur die Excel-Datei im XML-Format. In dieser speziellen Situation können Sie einen Prozess-Kill verwenden, um alle Excel-Objekte zu entfernen.

System.Diagnostics.Process pro = ExcelProcess.GetExcelProcess(app); 
pro.Kill(); 

Need ExcelProcess.GetExcelProcess Methode

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

    public static System.Diagnostics.Process GetExcelProcess(oExcel.Application excelApp) 
    { 
     int id; 
     GetWindowThreadProcessId(excelApp.Hwnd, out id); 
     return System.Diagnostics.Process.GetProcessById(id); 
    } 
} 
zu definieren,