在异步请求中要返回文件流,不能使用JQuery,因为$.ajax,$.post 不支持返回二进制文件流的类型,可以看到下图,dataType只支持xml,json,script,html这几种格式,没有blob类型。所以只能选择使用原生Ajax XMLReques对象进行处理
前端代码
function output() { var branchCode = $("#currentBranchCode").val(); var transDate = $("#currentTransDate").val(); if (branchCode == "" || transDate == "") { layer.msg("暂无记录,无法导出",{ icon: 7,time: 1000 }); return; } var fileName = $("table caption").html() + ".xls";//设置下载时候的文件名 //要请求的Url和携带的参数 var url = "/SellAnalyze/Export?currentBranchCode=" + branchCode + "¤tTransDate=" + transDate; var xhr = new XMLHttpRequest(); //设置响应类型为blob类型 xhr.responseType = "blob"; xhr.onload = function () { if (this.status == "200") {
//获取响应文件流 var blob = this.response; var aElem = document.getElementById("exportUrl");
//将文件流保存到a标签 aElem.href = window.URL.createObjectURL(blob); aElem.download = fileName; aElem.onload = function (e) { window.URL.revokeObjectURL(aElem.href); }; $("#exportUrl").removeClass("hidden"); layer.confirm(‘文件已导出,立即下载?‘,function (index) { $("#download").click(); layer.close(index); }); } } xhr.open("post",url,true); xhr.send(); }
后端代码
public ActionResult Export(int? currentBranchCode,DateTime currentTransDate) {@H_404_125@ MemoryStream ms = NPOIExcelWrite(datas); ms.Seek(0,SeekOrigin.Begin); return File(ms,"application/vnd.ms-excel"@H_404_125@); } /// <param name="datas">写入的数据</param> /// <returns></returns> private MemoryStream NPOIExcelWrite(SellDTO[] datas) { string[] titles = { "货品类别","货品类别描述","销售额","同比","环比" }; NPOI.hssf.usermodel.hssfWorkbook book = new NPOI.hssf.usermodel.hssfWorkbook(); NPOI.SS.usermodel.ISheet sheet = book.CreateSheet("Sheet1"); NPOI.SS.usermodel.IRow row = sheet.CreateRow(0); for (int i = 0; i < titles.Length; i++) { row.CreateCell(i).SetCellValue(titles[i]); } for (int i = 0; i < datas.Length; i++) { row = sheet.CreateRow(i + 1); row.CreateCell(0).SetCellValue(datas[i].JewelryType); row.CreateCell(1).SetCellValue(datas[i].JewelryTypeDesc); row.CreateCell(2).SetCellValue(datas[i].CurrentMonthSaleroom.ToString("F2")); row.CreateCell(3).SetCellValue(datas[i].YearOverYear); row.CreateCell(4).SetCellValue(datas[i].LinkRelative); } @H_404_125@MemoryStream ms @H_404_125@= new MemoryStream(); book.Write(ms); ms.Flush(); book = null; return@H_404_125@ ms; }
参考:https://blog.csdn.net/swl979623074/article/details/77855629/
https://www.cnblogs.com/cdemo/p/5225848.html
https://blog.csdn.net/fangchen12312/article/details/55271296
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。