El proceso de Excel permanece abierto después de la interoperabilidad; metodo tradicional no funciona

 C Programming >> Programación C >  >> Tags >> Excel
El proceso de Excel permanece abierto después de la interoperabilidad; metodo tradicional no funciona

Esto ha funcionado con éxito para mí:

        xlApp.Quit();

        //release all memory - stop EXCEL.exe from hanging around.
        if (xlWorkBook != null) { Marshal.ReleaseComObject(xlWorkBook); } //release each workbook like this
        if (xlWorkSheet != null) { Marshal.ReleaseComObject(xlWorkSheet); } //release each worksheet like this
        if (xlApp != null) { Marshal.ReleaseComObject(xlApp); } //release the Excel application
        xlWorkBook = null; //set each memory reference to null.
        xlWorkSheet = null;
        xlApp = null;
        GC.Collect();

Este código funciona para mí.

//Declare separate object variables
Excel.Application xlApp = new Excel.Application();
Excel.Workbooks xlWorkbooks = xlApp.Workbooks;
Excel.Workbook xlWorkbook = xlWorkbooks.Add(Missing.Value);
Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.get_Item(1);

//Create worksheet

xlWorkbook.Close(false, Missing.Value, Missing.Value);
xlWorkbooks.Close();
xlApp.Quit();

Marshal.FinalReleaseComObject(xlWorksheet);
Marshal.FinalReleaseComObject(xlWorkbook);
Marshal.FinalReleaseComObject(xlWorkbooks);
Marshal.FinalReleaseComObject(xlApp);

xlWorksheet = null;
xlWorkbook = null;
xlWorkbooks = null;
xlApp = null;

GC.Collect();

Este artículo de Microsoft tiene buena información sobre este problema.


Soy un aficionado total a COM, lo usé para algo menor en un proyecto hace mucho tiempo, pero aquí hay un fragmento que usé allí. Probablemente lo encontré en algún lugar en línea, no lo recuerdo. En cualquier caso, lo pego en todo su esplendor;)

public static class ComBlackBox
{
    public static void ReleaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (ArgumentException ex)
        {
            obj = null;
            MessageBox.Show("Unable to release the Object " + ex.Message);
        }
        finally
        {
            GC.Collect();
        }
    } 
}

No puedo probarlo ahora, pero probablemente funcionó (honestamente, no recuerdo ningún detalle). Tal vez te ayude. Siéntase libre de señalar cualquier problema obvio con este código, realmente estoy lejos de ser alfabetizado en COM;)