页面代码:
js代码:
//下载excel模板 $("#downLoad").click(function () { //方式1 window.open('/BaseInfoPage/DowntTemplate'); //方式2 此方式还未解锁 //$.ajax({ // url: "/BaseInfoPage/DownLoadExcel", //处理页面的路径 // data: { fileName: "大件运输许可导入模板.xls" }, //要提交的数据是一个JSON // type: "POST", //提交方式 // dataType: "JSON", //返回数据的类型 //TEXT字符串 JSON返回JSON XML返回XML // success: function (data) { // console.log(data); // }, // error: function (msg) { // //layer.msg('!', { icon: 1, time: 1000 }, function () { // //}); // //layer.msg(msg, { icon: 2, time: 2000 }); // } //}) //方式3 //param = "fileName=" + "大件运输许可模板.xls"; //window.location.href = "/BaseInfoPage/DownLoadExcel?" + param; })
c#后台代码:
////// 下载excel模板1 /// /// 文件名 public void DownLoadExcel(string fileName) { if (Request.Cookies["LoginValue"] == null) Response.Redirect("../Login/LoginPage"); try { string path = AppDomain.CurrentDomain.BaseDirectory + "\\ExcelTemplate\\" + fileName + "";//文件路径 FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);//读取文件路径 byte[] buffer = new byte[fs.Length]; fs.Position = 0; fs.Read(buffer, 0, (int)fs.Length); Response.Clear(); Response.AddHeader("Content-Length", fs.Length.ToString()); Response.ContentType = "application/xls"; Response.AddHeader("Content-Disposition", "inline;FileName=大件运输许可导入模板.xls"); fs.Close(); Response.BinaryWrite(buffer); Response.OutputStream.Flush(); Response.OutputStream.Close(); //Response.OutputStream.Write(buffer, 0, (int)fs.Length); } catch (Exception ex) { CSysCfg.WriteLog("获取文档异常:" + ex.Message); } } /// 下载excel模板2 public ActionResult DowntTemplate(HttpPostedFileBase file) { //模板文件的路径 string filePath = Server.MapPath("~/ExcelTemplate/大件运输许可导入模板.xls");////获取文件路径 if (System.IO.File.Exists(filePath)) { string strfileName = Path.GetFileName(filePath);//获取文件名称 return File(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), "application/octet-stream", strfileName); } else { return Content("模板文件找不到!请检查文件是否存在!");//提示用户 } }