如何正确发布Application.Cells?

时间:2017-07-10 01:03:44

标签: c# winforms

我写了一些代码,但我无法正确发布Application.Cells。有没有人可以帮我在任务管理器中发布Excel.exe?

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();
                */
            }                      
    }

我在这里阅读了一些教程How to properly release Excel COM objects

1 个答案:

答案 0 :(得分:1)

这是一场漫长的战斗。我已经为我的应用尝试了一切。没有成功。对于简单的写入函数,使用OpenXML更好。它不会调用excel应用程序只是操作XML格式的excel文件。对于这种特殊情况,您可以使用进程kill来处理所有excel对象。

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

需要定义ExcelProcess.GetExcelProcess方法

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