Another solution to this problem is to save the ProcessID of the Excel program in which you are working with. Then when you are done with the program, you can specifially kill that Excel process without targeting other excel processes.
I got the solution from this answer. Thought I would share it here
So first, you add these line of code outside of a class method
// The DllImport requires -- Using System.Runtime.InteropServices;
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr hwnd, ref int lpdwProcessId);
After that,
Now in a method of your choosing, add these lines.
These lines discard the specific excel process that you are working with
Modify them to your needs, but the logic is thesame
if (ExcelApp != null)
{
int excelProcessId = 0;
//your Excel Application variable has access to its Hwnd property
GetWindowThreadProcessId(new IntPtr(ExcelApp.Hwnd), ref excelProcessId);
// you need System.Diagnostics to use Process Class
Process ExcelProc = Process.GetProcessById(excelProcessId);
if (ExcelProc != null)
{
ExcelProc.Kill();
}
}
Hence in total your program should look like this
class Program
{
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr hwnd, ref int lpdwProcessId);
static void Main(string[] args)
{
Application ExcelApp = new Application();
_Workbook ExcelWrkBook = ExcelApp.Workbooks.Open(filePath);
_Worksheet ExcelWrkSht = ExcelWrkBook.ActiveSheet;
ExcelWrkSht.Cells[1, 2] = "70";
if (ExcelApp != null)
{
int excelProcessId = 0; // simple declare, zero is merely a place holder
GetWindowThreadProcessId(new IntPtr(ExcelApp.Hwnd), ref excelProcessId);
Process ExcelProc = Process.GetProcessById(excelProcessId);
if (ExcelProc != null)
{
ExcelProc.Kill();
}
}
}
}
I have tested this and it removes my Excel processes as shown in Task Manager