<head runat="server"> <title></title> <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script> <script type="text/javascript"> function getExecl() { $.ajax({ type: 'POST', url: 'ashx/execl.ashx', success: function (data) { var re = eval(data); for (var i in re) { if (re[i].num > 0) alert(re[i].num); } }, error: function (data) { } }); } </script> </head>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; using System.Web.Script.Serialization; namespace WebApplication1.ashx { /// <summary> /// Summary description for execl /// </summary> public class execl : IHttpHandler { [DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID); JavaScriptSerializer json = new JavaScriptSerializer(); public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; int s= getExecl(); MessageInfo MessageRe = new MessageInfo(s, null); string returnValue = json.Serialize(MessageRe); returnValue = "[" + returnValue + "]"; context.Response.Write(returnValue); } private int getExecl() { int num = 0; try { ApplicationClass excel = new ApplicationClass(); string time = DateTime.Now.ToString("yyyyMMddHHmmss"); string path = @"H:exel" + time + ".xlsx"; excel.Workbooks.Open(@"H:exel1.xlsx", 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.Visible = false; //设置可见性 Worksheet workshet = (Worksheet)excel.Worksheets.get_Item(1); workshet.Cells[3, 1] = "11"; //行和列 workshet.Cells[4, 1] = "11"; workshet.Cells[5, 1] = "11"; workshet.Cells[6, 1] = "11"; workshet.SaveAs(path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); excel.Quit(); //退出 IntPtr t = new IntPtr(excel.Hwnd); //运用句柄 int k = 0; GetWindowThreadProcessId(t, out k); System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); p.Kill(); //杀死当前进程 num = 1; } catch (Exception e) { } return num; } public bool IsReusable { get { return false; } } } }
参考了地址 http://www.cnblogs.com/zhangchenliang/archive/2011/07/21/2112430.html