asp.net关闭excel进程(win32).txt

来自「学习c#语言的一本好书可以帮助初学者」· 文本 代码 · 共 38 行

TXT
38
字号
1.ASP.NET不可行
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();        
    }
2.远程计算机不行
//杀死Excel进程
			Process []procs=Process.GetProcessesByName("excel");
			foreach(Process proc in procs)
			{
				if(!proc.CloseMainWindow())
					proc.Kill();
			}
3.在远程计算机可行

xlBook.Close(false,Type.Missing,Type.Missing);
			xlApp.Workbooks.Close();
			xlApp.Quit();

			//杀死Excel进程
			System.Runtime.InteropServices.Marshal.ReleaseComObject (xlApp);
			System.Runtime.InteropServices.Marshal.ReleaseComObject (xlSheet);
			System.Runtime.InteropServices.Marshal.ReleaseComObject (xlBook);
			xlApp=null;
			xlSheet=null;
			xlBook = null;
			GC.Collect() ;
			GC.WaitForPendingFinalizers();

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?