第一种下载方法
private void DownExcel(string filePath) { //string path = HttpContext.Current.Server.MapPath("/UploadFiles/KGData/test.xls");string path = HttpContext.Current.Server.MapPath(filePath); FileInfo fileInfo = new FileInfo(filePath); Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name); Response.AddHeader("Content-Length", fileInfo.Length.ToString()); Response.AddHeader("Content-Transfer-Encoding", "binary"); Response.ContentType = "application/octet-stream"; Response.ContentEncoding = Encoding.GetEncoding("gb2312"); Response.WriteFile(fileInfo.FullName); Response.Flush(); Response.End(); }
第二种方法
windows.location.href = "/test/ExcelDownLoad.aspx?file=test.xls" ;
protected void ResponseFile() { string fileName = Request.QueryString["file"]; ext(fileName); System.IO.Stream iStream = null; // 缓冲区为10k byte[] buffer = new Byte[10240]; // 文件长度 int length; // 需要读的数据长度 long dataToRead; try { string fileName = path; string filepath = HttpContext.Current.Server.MapPath("/ExcelTemp/") + fileName; //待下载的文件路径 iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); Response.Clear(); dataToRead = iStream.Length; //iStream.Position = 0; long p = 0; if (Request.Headers["Range"] != null) { Response.StatusCode = 206; p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", "")); } if (p != 0) { Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long)(dataToRead - 1)).ToString() + "/" + dataToRead.ToString()); } Response.AddHeader("Content-Length", ((long)(dataToRead - p)).ToString()); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" +HttpUtility.UrlEncode(Path.GetFileName(filepath))); Response.AppendHeader("Location", Request.Url.AbsoluteUri); iStream.Position = p; dataToRead = dataToRead - p; while (dataToRead > 0) { // 检查客户端是否还处于连接状态 if (Response.IsClientConnected) { length = iStream.Read(buffer, 0, 10240); Response.OutputStream.Write(buffer, 0, length); Response.Flush(); buffer = new Byte[10240]; dataToRead = dataToRead - length; } else { // 如果不再连接则跳出死循环 dataToRead = -1; } } } catch (Exception ex) { Response.Write("Error : 文件不存在!!!"); // Response.Redirect("../Supplier_Idex.aspx"); } finally { if (iStream != null) { iStream.Close(); } Response.End(); } }
protected string ext(string file) { string str = string.Empty; if(!string.IsNullOrEmpty(file)) { var invalidPattern = new Regex(@"[\\\/\:\*\?<\>\|]"); string strExt = invalidPattern.Replace(file, ""); strExt = Path.GetExtension(file); switch(strExt) { case ".config": str = "文件不存在"; break; default: str = file; break; } } return str; }
使用jquery下载方法
js方法
jQuery.download = function (downloadurl, method, filepath, filename) { jQuery('') .appendTo('body').submit().remove(); }; function ExportToExcel() { if (confirm("确定要导出Excel吗?")) { var start = getQueryString('fromDate'); var end = getQueryString('toDate'); var brand = getQueryString('brandCompany'); var staff = getQueryString('staff'); var groupName = getQueryString('groupName'); $.ajax({ type: "POST", dataType: "json", url: "Test.aspx/ExportToExcel", data: "{fromDate:'" + start + "',toDate:'" + end + "',brandName:'" + brand + "'}", contentType: "application/json; charset=utf-8", success: function (data) { var result = eval('(' + data.d + ')'); if (result.Body == '没有需要导出的信息') { alert(result.Body); } else { $.download(result.DownLoadUrl, 'post', result.FilePath, result.FileName); } }, error: function (msg) { alert('系统繁忙,请稍后重试!'); } }); } }function getQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var result = window.location.search.substr(1).match(reg); if (result != null) { return unescape(result[2]); } else { return null; } }
后台方法
[WebMethod] public static string ExportToRiskExcel(DateTime fromDate,DateTime toDate,string brandName) { DataSet ds = new wcfInternalService.InternalServiceClient().GetList(fromDate, toDate, brandName); DownResult result = new DownResult() { Success = false, Body = "导出失败,请稍后再试!" }; if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0) { string[] columns = { "序号", "案件", "车牌", "分类", "处理时间", "人员", "金额" }; result = ExportExcel(ds.Tables[0], columns, "分布详情", result); } else { result = new DownResult() { Success = true, Body = "没有需要导出的信息" }; } return JsonConvert.SerializeObject(result); }public static DownResult ExportExcel(DataTable dt, string[] columns, string sheetName, DownResult result) { string filePath = string.Empty;//文件路径 string fileName = string.Empty;//文件名称 Stream stream = DataTableToExcel(dt, columns, sheetName); ExcelPackage package = new ExcelPackage(stream); fileName = sheetName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"; filePath = HttpContext.Current.Server.MapPath("~/UploadFile/");//文件保存地址 if (!Directory.Exists(filePath))//如果不存在就创建file文件夹 { Directory.CreateDirectory(filePath); } package.SaveAs(new FileInfo(filePath + fileName)); result = new DownResult() { Success = true, Body = "导出成功!", DownLoadUrl = "DownExcel.aspx", FilePath = filePath, FileName = fileName, }; return result; } public static Stream DataTableToExcel(DataTable dataTable, string[] columns, string sheetName) { try { using (ExcelPackage pck = new ExcelPackage()) { ExcelWorksheet ws = pck.Workbook.Worksheets.Add(sheetName); ws.Cells["A1"].LoadFromDataTable(dataTable, true); for (int i = 1; i <= columns.Length; i++) { using (ExcelRange rng = ws.Cells[1, i]) { rng.Style.Font.Bold = true; rng.Value = columns[i - 1]; } } MemoryStream ms = new MemoryStream(); pck.SaveAs(ms); ms.Flush(); ms.Position = 0;//指定当前流的位置从0开始 return ms; } } catch (Exception ex) { throw ex; } } public class DownResult { public bool Success { get; set; } public string Body { get; set; } public string DownLoadUrl { get; set; } public string FilePath { get; set; } public string FileName { get; set; } }
方法必须为静态,参数需要一致
下载页面方法
protected void Page_Load(object sender, EventArgs e) { string fileName = Request["filename"];//下载文档名 string filePath = Request["filepath"]; FileInfo fileInfo = new FileInfo(filePath + fileName); Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); String userAgent = HttpContext.Current.Request.UserAgent; //判断是否为ie10以下及ie11浏览器 if (userAgent.Contains("MSIE") || userAgent.Contains("rv:11")) { fileName = HttpUtility.UrlEncode(fileName); } Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}\"", fileName)); Response.AddHeader("Content-Length", fileInfo.Length.ToString()); Response.AddHeader("Content-Transfer-Encoding", "binary"); Response.ContentType = "application/octet-stream"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); Response.WriteFile(fileInfo.FullName); Response.Flush(); if (File.Exists(Path.GetFullPath(fileInfo.ToString()))) { File.Delete(Path.GetFullPath(fileInfo.ToString()));//用户下载后删除服务器文件 } Response.End(); }