I'm writing an application in C# that opens an Excel template file for read/write operations. I want to when user closes the application, excel application process has been closed, without saving excel file. See my Task Manager after multiple runs of the app.
I use this code to open the excel file :
public Excel.Application excelApp = new Excel.Application();
public Excel.Workbook excelBook;
excelBook = excelApp.Workbooks.Add(@"C:/pape.xltx");
and for data access I use this code :
Excel.Worksheet excelSheet = (Worksheet)(excelBook.Worksheets[1]);
excelSheet.DisplayRightToLeft = true;
Range rng;
rng = excelSheet.get_Range("C2");
rng.Value2 = txtName.Text;
I see similar questions in stackoverflow such as this question and this, and test answers, but it doesn't works.
The right way to close all excel process
excelBook.Close(); excelApp.Quit(); add end of the code, it could be enough. it is working on my code
Killing Excel is not always easy; see this article: 50 Ways to Kill Excel
This article takes the best advice from Microsoft (MS Knowlege Base Article) on how to get Excel to quit nicely, but then also makes sure about it by killing the process if necessary. I like having a second parachute.
Make sure to Close any open workbooks, Quit the application and Release the xlApp object. Finally check to see if the process is still alive and if so then kill it.
This article also makes sure that we don't kill all Excel processes but only kills the exact process that was started.
See also Get Process from Window Handle
Here is the code I use: (works every time)