下面是完整的调用Excel,关闭Excel,结束Excel进程的代码. [原创]
环境:VS2008 + Excel
2011.11.26 再次修订
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
namespace KillExcelProcess
{
public partial class Form_KillExcelProcess : Form
{
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
//函数原型;DWORD GetWindowThreadProcessld(HWND hwnd,LPDWORD lpdwProcessld);
//参数:hWnd:窗口句柄
//参数:lpdwProcessld:接收进程标识的32位值的地址。如果这个参数不为NULL,GetWindwThreadProcessld将进程标识拷贝到这个32位值中,否则不拷贝
//返回值:返回值为创建窗口的线程标识。
[DllImport("kernel32.dll")]
public static extern int OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
//函数原型:HANDLE OpenProcess(DWORD dwDesiredAccess,BOOL bInheritHandle,DWORD dwProcessId);
//参数:dwDesiredAccess:访问权限。
//参数:bInheritHandle:继承标志。
//参数:dwProcessId:进程ID。
public const int PROCESS_ALL_ACCESS = 0x1F0FFF;
public const int PROCESS_VM_READ = 0x0010;
public const int PROCESS_VM_WRITE = 0x0020;
//定义Excel Application, Workbook
public static Microsoft.Office.Interop.Excel.Application ExcelApp;
public static Microsoft.Office.Interop.Excel.Workbook WorkBook;
public static object doNotSaveChanges = XlSaveAction.xlDoNotSaveChanges;
//定义句柄变量
public static IntPtr hwnd;
//定义进程ID变量
public static int pid = 0;
public Form_KillExcelProcess()
{
InitializeComponent();
this.lb_ProcessID.Text = "";
}
private void bt_StartExcel_Click(object sender, EventArgs e)
{
ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
WorkBook = ExcelApp.Workbooks.Open("C:\\1.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);
//获取Excel App的句柄
hwnd = new IntPtr(ExcelApp.Hwnd);
//通过Windows API获取Excel进程ID
GetWindowThreadProcessId(hwnd, out pid);
this.lb_ProcessID.Text = pid.ToString();
}
private void bt_KillExcel_Click(object sender, EventArgs e)
{
try
{
//正常退出Excel
//ExcelApp.Quit()后,若Form_KillExcelProcess进程正常结束,那么,Excel进程也会自动结束.
//ExcelApp.Quit()后,若Form_KillExcelProcess进程被用户手工强制结束,那么,Excel进程不会自动结束.
WorkBook.Close(doNotSaveChanges, null, null);
ExcelApp.Quit();
}
catch (Exception)
{
//正常退出Excel失败,可以记录一下日志.
}
finally
{
//强制结束Excel进程
if (ExcelApp != null && pid > 0)
{
int ExcelProcess;
ExcelProcess = OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE, false, pid);
//判断进程是否仍然存在
if (ExcelProcess > 0)
{
try
{
//通过进程ID,找到进程
System.Diagnostics.Process process = System.Diagnostics.Process.GetProcessById(pid);
//Kill 进程
process.Kill();
this.lb_ProcessID.Text = "";
}
catch (Exception)
{
//强制结束Excel进程失败,可以记录一下日志.
}
}
else
{
//进程已经结束了
this.lb_ProcessID.Text = "";
}
}
}
}
}
}
这篇博客提供了使用C#操作Excel并彻底关闭Excel进程的完整代码,适用于VS2008和Excel2011环境。内容包括如何避免出现异常、处理对象释放和确保excel.exe进程正确结束。
223

被折叠的 条评论
为什么被折叠?



