Home > Net >  Excel does not close
Excel does not close

Time:11-25

My problem is that I have a program that reads data from an Excel sheet .xlsb, but when the Excel file is open, then it asks me to save. Why?

 async Task<bool> ReadVariable()
        {
            bool succeeded = false;
            while (!succeeded)
            {
                
                //open file excel using microsoft dll
                Excel.Application app = new Excel.Application();
                

                //open workbook
                Workbook wk = app.Workbooks.Open(excelpath, ReadOnly : true);
                //get first sheet
                Worksheet sh = wk.Worksheets[1];
                //get cell
                // Cells[unten/rechts] Example: [1,2] = B1 
                var day1tag = sh.Cells[27, 2].Value.ToString();
                exceltest1.Text = day1tag;
              
                var day1früh = sh.Cells[26, 2].Value.ToString();
                Day24oee24.Text = day1früh;


               
                app.DisplayAlerts = false;
                wk.Close(SaveChanges : false);
                app.Quit();

                await Task.Delay(15000);
                //await Task.Delay(108000000);
            }
            return succeeded;
        }

CodePudding user response:

[In addition to @JohnG]

First, you should put the app.Quit(); command line out side of the while loop and then do your algorthyms, after that save your workbook with this code;

xlWorkbook.SaveAs(saveFileDialog1.FileName   ".xlsx", Excel.XlFileFormat.xlWorkbookDefault, null, null, null, null, Excel.XlSaveAsAccessMode.xlExclusive, null, null, null, null, null);

and then use

app.Quit();

In addition; After all process zombie excel will be shown on your task manager to solve that I would like to recommend as follow;

Import;

using System.Diagnostics;

To kill zombie excel use this function;

private void KillSpecificExcelFileProcess(string excelFileName)
{
    var processes = from p in Process.GetProcessesByName("EXCEL")
                    select p;

    foreach (var process in processes)
    {
        if (process.MainWindowTitle == excelFileName)
            process.Kill();
    }
}

And call the function as follow; (Interop excels are nameless due to we should use ("").

KillSpecificExcelFileProcess("");
  • Related