无法释放Excel互操作COM对象

时间:2014-02-25 12:53:24

标签: c# excel office-interop excel-interop comobject

这是我的代码:

        Application app = null; //release this object
        Workbook wrkbuk = null;//release this object
        Worksheet wrksheet = null;//release this object
        object misval = System.Reflection.Missing.Value;
        app = new Application();
        app.Visible = false;
        string sPath = Server.MapPath("sample");
        var workbukObj = app.Workbooks; //release this object
        wrkbuk = workbukObj.Open(sPath + "\\TotalDistance.xlsx", misval, misval, misval, misval, misval, misval, misval, misval, misval, misval, misval, misval, misval, misval);// releaase this object
        wrksheet = ((Worksheet)wrkbuk.Worksheets[1]); //release this object
        Range cells = ((Worksheet)wrkbuk.Worksheets[1]).Cells; //release this
        int row = 2;
        int column = 2;
        wrksheet.Cells[row, column] = Convert.ToDateTime(txtFromDate.Text).ToString("dd-MM-yyyy") + " " + txtFromTime.Text;
        row++;
        wrksheet.Cells[row, column] = Convert.ToDateTime(txtToDate.Text).ToString("dd-MM-yyyy") + " " + txtToTime.Text;
        row = 5;
        column = 1;
        for (int k = 0; k < finalPack.Count; k++)
        {
            wrksheet.Cells[row, column] = finalPack[k].vehicleNumber;
            column++;
            //wrksheet.Cells[row, column] = finalPack[k].driverName;
            //column++;
            //wrksheet.Cells[row, column] = finalPack[k].driverNumber;
            //column++;
            //wrksheet.Cells[row, column] = finalPack[k].driverAddress;
            //column++;
            if (finalPack[k].distanceTravelled == .001)
            {
                wrksheet.Cells[row, column] = "";
            }
            else
            {
                wrksheet.Cells[row, column] = Convert.ToDateTime(finalPack[k].frmTime).ToString("dd-MM-yyyy");

            }
            column++;
            wrksheet.Cells[row, column] = finalPack[k].startAddress;
            column++;
            wrksheet.Cells[row, column] = finalPack[k].endAddress;
            column++;
            if (finalPack[k].distanceTravelled != .001)
            {
                wrksheet.Cells[row, column] = finalPack[k].distanceTravelled;
            }
            else
            {
                wrksheet.Cells[row, column] = "";

            }
            column++;
            if (finalPack[k].tempDist != 0.0)
            {
                wrksheet.Cells[row, column] = finalPack[k].tempDist;
            }
            else
            {
                wrksheet.Cells[row, column] = "";

            }
            column++;
            if (finalPack[k].totalDistance != 0.0)
            {
                wrksheet.Cells[row, column] = finalPack[k].totalDistance;
            }
            else
            {
                wrksheet.Cells[row, column] = "";

            }
            column = 1;
            row++;

        }

        string filePath = Server.MapPath("DistanceReports") + "\\" + DateTime.Now.ToString("dd_MMM_yyyy HH_mm_ss") + ".xlsx";
        wrkbuk.SaveAs(filePath, misval, misval, misval, misval, misval, XlSaveAsAccessMode.xlExclusive, misval, misval, misval, misval, misval);

        wrkbuk.Close(Type.Missing, Type.Missing, Type.Missing);
        workbukObj.Close();

        string Timezone = "India Standard Time";
        if (Session["timeZone"] != null)
            Timezone = Session["timeZone"].ToString();
        DateTime currentTime = timeZoned(Timezone);

        FileInfo file = new FileInfo(filePath);
        if (file.Exists)
        {
            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=" + "DistanceReport" + currentTime.ToString("yyyy/MM/dd HH:mm") + ".xlsx");
            Response.AddHeader("Content-Type", "application/Excel");
            Response.ContentType = "application/vnd.xls";
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.WriteFile(file.FullName);

        }
        try
        {
            app.Quit();
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Marshal.FinalReleaseComObject(cells);
            Marshal.FinalReleaseComObject(wrksheet);
            Marshal.FinalReleaseComObject(wrkbuk);
            Marshal.FinalReleaseComObject(workbukObj);
            Marshal.FinalReleaseComObject(app);
            //  wrkbuk.Close(null, null, null);
            GC.Collect();
            GC.WaitForPendingFinalizers();

        }
        catch
        {
        }

我正在尝试关闭始终在我的任务管理器中保持打开状态的Excel.exe实例。 我读到了解决方案here,但我无法做到。 有什么我想念的吗?请帮忙。!

1 个答案:

答案 0 :(得分:1)

我不确定您的代码中出现了什么问题。但是这里有一个关闭excel文件的功能:

 private void releaseObject(object obj) {
        try {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex) {
            obj = null;
            MessageBox.Show("Unable to release the Object " + ex.ToString());
        }
        finally {
            GC.Collect();
        }
    }

然后在代码的末尾调用它:

try {
   wrkbuk.Close(true);
   app.Quit();
   releaseObject(app);
   releaseObject(wrkbuk);     
   releaseObject(wrksheet);   
} catch (Exception ex) {
   MessageBox.Show(ex.ToString());     
}