0

I've been looking to similar questions trying to solve this issue to no avail:
The process EXCEL.EXE is not closing after use, despite closing the Workbook, Workbooks and Application objects. I've also tried using Marshal.ReleaseComObject to release them and also the Range Sheet and Sheets objects. None of the answers I looked up have worked.

Some of the answers I looked up:
How do I properly clean up Excel interop objects?
Cannot close Excel.exe after Interop process

Here's the code I've been using:

Resultado res = new Resultado();
List<RegistroHH> lista = MantenedoresNegocio.RegistrosHH.Listar(ccosto, 1);

//Excel.Application app = new Application();
Excel.Application app = null;
Excel.Workbooks books = null;
Excel._Workbook wbook = null;
Excel._Worksheet sheet = null;
Excel.Sheets sheets = null;
Excel.Range rang = null;

try
{
    //Start Excel and get Application object.
    app = new Excel.Application();
    app.Visible = true;
    app.DisplayAlerts = false;

    //Get a new workbook.
    books = app.Workbooks;
    wbook = books.Add(Missing.Value);
    sheets = wbook.Sheets;
    //sheet = (Excel._Worksheet)wbook.ActiveSheet;
    sheet = sheets.Add();

    int idActividad = 0;
    List<string> horas = new List<string>();
    rang = sheet.Cells[1, 1] as Excel.Range;
    rang.Value2 = "ID";
    rang.Borders.Weight = Excel.XlBorderWeight.xlThin;
    rang.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.DarkBlue);

    rang = sheet.Cells[1, 2] as Excel.Range;
    rang.Value2 = "Actividad";
    rang.Borders.Weight = Excel.XlBorderWeight.xlThin;

    Dictionary<int, string> responsables = new Dictionary<int, string>();
    List<string> columnasResponsables = new List<string>();

    int idColumna = 3;
    int idFila = 1;

    foreach (RegistroHH reg in lista)
    {
        if (reg.idActividad != idActividad)
        {
            idColumna = 3;

            rang = sheet.Cells[idFila, 1] as Excel.Range;
            rang.NumberFormat = "@";
            rang.Value2 = reg.jerarquia;
            rang.Borders.Weight = Excel.XlBorderWeight.xlThin;

            rang = sheet.Cells[idFila, 2] as Excel.Range;
            rang.Value2 = reg.nombreActividad;
            rang.Borders.Weight = Excel.XlBorderWeight.xlThin;

            idFila++;
        }
        if (!responsables.ContainsKey(reg.idResponsable))
        {
            responsables.Add(reg.idResponsable, reg.nombreResponsable);

            rang = sheet.Cells[1, idColumna] as Excel.Range;
            rang.Value2 = reg.nombreResponsable;
            rang.Borders.Weight = Excel.XlBorderWeight.xlThin;
        }
        rang = sheet.Cells[idFila, idColumna] as Excel.Range;

        if (reg.horasAsignadas != 0)
            rang.Value2 = reg.horasAsignadas;
        /*
        if (!dt.Columns.Contains(reg.nombreResponsable.ToString()))
            dt.Columns.Add(reg.nombreResponsable.ToString());
        horas.Add((reg.horasAsignadas > 0 ? reg.horasAsignadas.ToString() : ""));
        */
        idActividad = reg.idActividad;
        idColumna++;
    }
    rang = sheet.Columns[2] as Excel.Range;
    rang.AutoFit();

    wbook.SaveAs(ruta);

    res.CodigoResultado = 0;
    res.Mensaje = "Exito";
}
catch (Exception theException)
{
    res.CodigoResultado = -1;
    res.Mensaje = theException.Message;
}
finally
{
    if (rang != null) Marshal.ReleaseComObject(rang);
    if (sheet != null) Marshal.ReleaseComObject(sheet);
    if (sheets != null) Marshal.ReleaseComObject(sheets);

    if (wbook != null)
        wbook.Close();
    if (wbook != null) Marshal.ReleaseComObject(wbook);

    if (books != null)
        books.Close();
    if (books != null) Marshal.ReleaseComObject(books);

    if (app != null)
    {
        app.Application.Quit();
        app.Quit();
    }
    if (app != null) Marshal.ReleaseComObject(app);
    //cleanup
    GC.Collect();
    GC.WaitForPendingFinalizers();
}
GSerg
  • 76,472
  • 17
  • 159
  • 346
  • Look at [this answer](https://stackoverflow.com/a/38111294/1115360) from the Q&A you linked to, I have found it to work. – Andrew Morton Nov 25 '21 at 18:31
  • @AndrewMorton, that answer is in VB, I'm using C# – Eduardo Quezada Nov 25 '21 at 18:46
  • How are you determining that the Excel process is not released? And are the processes released if you close the application? The code appears to release the Excel process successfully… I am curious when and where you are checking this. – JohnG Nov 25 '21 at 18:50
  • @EduardoQuezada Online VB.NET-to-C# convertors will deal with that, e.g. [this one](https://codeconverter.icsharpcode.net/). – Andrew Morton Nov 25 '21 at 18:51
  • @JohnG I'm looking at the Task Manager, seeing that every time I call the method, it created a new process listed. A version prior to what I posted used to leave every process open, but now it seems that it's leaving open at most 1 process once the method is finished (it has 2 processes open while creating the file) – Eduardo Quezada Nov 25 '21 at 19:02
  • @JohnG Previously, it used to be that if it ran 20 time, 20 processes would remain, but now only one does. I must've unknowingly gotten to this point by debugging and not running the code more than once per change, assuming that the one process that kept open would multiply if I ran it more times. (All this before posting to Stack Overflow). Right now, since it's only keeping one process no matter how many times I run it, that should be good enough I guess ^^; Though it would still be nice to know how to end that final process. – Eduardo Quezada Nov 25 '21 at 19:16
  • 1
    `GC.Collect(); GC.WaitForPendingFinalizers();` is bogus here, you need to run it outside of the function storing these values, otherwise nothing will get released. Although it depends on whether you are building Release or Debug. Also, Excel may decide to stay open, independently of whatever you do with your application – Charlieface Nov 25 '21 at 20:12
  • [How do I properly clean up Excel interop objects?](https://stackoverflow.com/questions/158706/how-do-i-properly-clean-up-excel-interop-objects) was a good starting point because it links you to https://stackoverflow.com/a/25135685/11683 which is your ultimate guidance. – GSerg Nov 25 '21 at 20:29

0 Answers0