Close excel.exe after parsing the c operation excel
- 2020-05-17 06:16:07
- OfStack
Therefore, the method of kill process was proposed. The method I have seen so far mostly USES the process creation time to filter the excel.exe process, and then kill. This method is neither accurate nor safe. After reading some articles about Api on the Internet, I found a more direct and accurate way to find process and kill
Here's the code
The above code is 100% successful in shutting down the excel.exe process
What I do is combine the two, release the resource first, and then close the process.
At the same time, the website says to avoid using the GC.Collect method (), because it will cause the whole clr to gc and affect your performance, so I did not call GC.Collect
Here's the code
using System.Runtime.InteropServices;
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
protected void Button1_Click(object sender, EventArgs e)
{
Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
excel.Workbooks.Open("d:\aaa.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
IntPtr t = new IntPtr(excel.Hwnd);
int k = 0;
GetWindowThreadProcessId(t, out k);
System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
p.Kill();
}
The above code is 100% successful in shutting down the excel.exe process
What I do is combine the two, release the resource first, and then close the process.
At the same time, the website says to avoid using the GC.Collect method (), because it will cause the whole clr to gc and affect your performance, so I did not call GC.Collect