Search code examples
c#cellworksheetexcel

How I can close a excel windows automatic?


I want to open and change a cell in excel by using C#

And it works but if i save the document I get a windows from excel -.- and everytime i must click on the button. See the picture.

Here is my code:

foreach (string file in Directory.GetFiles(path))
                         {
                             MSExcel.Workbook book1 = null;
                             MSExcel.Worksheet sheet1;
                             MSExcel.Range range_A1;

                             try
                             {
                                 book1 = app.Workbooks.Open(file);
                                 sheet1 = (MSExcel.Worksheet)book1.Worksheets[1];
                                 range_A1 = sheet1.GetRange(cell);

                                 string content = range_A1.Value2.ToString();

                                 if (content == value || content == value2)
                                 {

                                     range_A1.Value2 = string.Empty;
                                     book1.Save(); // here i save the value
                                     Console.WriteLine(count +" - OPEN AND CHANGE - " + file + " SAVE");
                                 }
                                 else
                                 {

                                     Console.WriteLine(count + " - OPEN - " + file + " NOT SAVE");
                                 }

                                 count++;
                             }
                             catch (Exception)
                             {
                                 count++;
                                 Console.WriteLine(count + " - ERROR FILE " + file);
                                 liste.Add(file); 
                             }
                             finally
                             {
                                 book1.Close(false);

                             }

                         }

enter image description here

How I can make it automatic ?


Solution

  • Have you tried this:

    app.DisplayAlerts = false;
    

    Maybe also these two for additional hiding (if needed):

    app.Visible = false;
    app.ScreenUpdating = false;