c#Interop Excel关闭实例

时间:2017-08-04 09:54:25

标签: c# excel interop comobject

我有一段代码打开一个excel应用程序转储范围然后尝试关闭它。

无论我做什么都试图成为一个有效的词我无法让excel实例关闭 - 据我所知,我遵循1点而不是2点规则可以帮助我找不到的东西。

    Excel.Application excelApp = new Excel.Application();

    Excel.Workbooks wbks = excelApp.Workbooks;
    Excel.Workbook currentWorkbook = wbks.Add();
    Excel.Worksheet newWks = new Excel.Worksheet();

    try
    {
        newWks = currentWorkbook.Sheets["Sheet2"];
        newWks.Delete();
        newWks = currentWorkbook.Sheets["Sheet3"];
        newWks.Delete();
        newWks=currentWorkbook.Sheets["Sheet1"];

        for (int col = 0; col < dt.Columns.Count; col++)
        {
            newWks.Cells[1, col + 1] = dt.Columns[col].ColumnName;
        }
        string[,] arr = new string[dt.Rows.Count, dt.Columns.Count];

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                arr[i, j] = dt.Rows[i][j].ToString();
            }
        }

        Excel.Range startCell = newWks.Cells[2, 1];
        Excel.Range endCell = newWks.Cells[dt.Rows.Count + 1, dt.Columns.Count];
        Excel.Range writeRange = newWks.Range[startCell, endCell];
        writeRange.Value2 = arr;

        Excel.Application cwa = currentWorkbook.Application;
        cwa.DisplayAlerts = false;

        Global.CheckDirectory(path);

        currentWorkbook.SaveAs(path + @"//filepath", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV, Missing.Value,
            Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
            Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true,
            Missing.Value, Missing.Value, Missing.Value);

        cwa.Quit();
        Marshal.ReleaseComObject(cwa);
        Marshal.ReleaseComObject(startCell);
        Marshal.ReleaseComObject(endCell);
        Marshal.ReleaseComObject(writeRange);
    }
    catch (Exception ex)
    {
       //err handler
    }
    finally
    {

        wbks.Close();
        excelApp.Quit();

        Marshal.ReleaseComObject(newWks);
        Marshal.ReleaseComObject(currentWorkbook);
        Marshal.ReleaseComObject(wbks);
        Marshal.ReleaseComObject(excelApp);

        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }

1 个答案:

答案 0 :(得分:1)

您好,

尝试按此顺序关闭并释放所有内容。

Marshal.ReleaseComObject(Range);
Marshal.ReleaseComObject(Worksheet);
//WRITE close and release
WWorkbook.Close();
Marshal.ReleaseComObject(Workbook);
//!WRITE quit and release
App.Quit();
Marshal.ReleaseComObject(App);
//cleanup
GC.Collect();
GC.WaitForPendingFinalizers();