在C#中使用Microsoft.Office.Interop.Excel.dll操作Excel文件时,有时创建的Application无法正常退出,因此我们就需要通过结束其进程的方式强制将Excel的Application退出:
一、引入Windows API获取进程Id函数:
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int id);
二、强制结束Excel的Application进程:
// 创建Excel进程
Microsoft.Office.Interop.Excel.Application app = new Application();
try
{
// 正常退出Excel进程
app.Quit();
}
catch
{
// 如Excel进程退出失败,则强制结束其进程
// 获取当前Excel进程的句柄
IntPtr intPtr = new IntPtr(app.Hwnd);
// 获取当前Excel进程的进程Id
int processId = 0;
GetWindowThreadProcessId(intPtr, out processId);
// 获取当前Excel进程
Process process = Process.GetProcessById(processId);
if (process != null)
{
// 强制结束Excel进程
process.Kill();
}
}