.NET后端返回File文件,及前端处理直接在浏览器下载

后端代码

AllowAnonymous

public System.Web.Mvc.ActionResult ExportByteExcel(string datatab, string columnnames, string schemecode)

{

返回excel。

string ReportName = "ExcelTemplete" + DateTime.Now.Ticks.ToString();

IWorkbook workbook = new HSSFWorkbook();

ISheet sheet = workbook.CreateSheet("sheet1");

int count = 0;

// 生成标题行

IRow row = sheet.CreateRow(count++);

int headerIndex = 0;

foreach (string columnName in newheads.Keys)

{

row.CreateCell(headerIndex++).SetCellValue(newheadscolumnName);

}

//生成数据

foreach (Dictionary<string, object> data2 in datas)

{

row = sheet.CreateRow(count++);

int bodyIndex = 0;

foreach (string key in newheads.Keys)

{

row.CreateCell(bodyIndex++).SetCellValue(data2key != null ? data2key.ToString() : "");

}

}

MemoryStream ms = new MemoryStream();

workbook.Write(ms);

ms.Position = 0;

string strPath = System.Web.HttpContext.Current.Server.MapPath("~/TempImages/");

string strExcelFile = strPath + ReportName + ".xls";

FileStream OutFile = new FileStream(strExcelFile, FileMode.Create, FileAccess.Write);

byte\[\] btArray = ms.ToArray();

OutFile.Write(btArray, 0, btArray.Length);

OutFile.Flush();

OutFile.Close();

//object FileUrl = ExportExcel.ExportTempExecl("ExcelTemplete" + DateTime.Now.Ticks.ToString(), newheads, datas);

//修改utf8编码,不然可能汉字会乱码

string encodedFileName = System.Web.HttpUtility.UrlEncode((ReportName + ".xls").Replace("/", ""), System.Text.Encoding.UTF8);

var contentDisposition = new ContentDispositionHeaderValue("attachment")

{

FileName = encodedFileName

};

Response.Headers.Add("Content-Disposition", contentDisposition.ToString());

var contentType = "application/octet-stream";

Response.Headers.Add("Content-Type", contentType);

return File(btArray, contentType);

}

前端代码直接在浏览器下载:

var xhr = new XMLHttpRequest();

xhr.open("POST", "/portal/TXEmail/ExportByteExcel?datatab=" + encodeURIComponent(data.datatab) + "&columnnames=" + data.columnnames + "&schemecode=" + data.schemecode, true);

xhr.responseType = "blob";

xhr.onreadystatechange = function () {

if (xhr.readyState === XMLHttpRequest.DONE) {

if (xhr.status === 200) {

//获取header中的内容

var contentDispositionHeader = xhr.getResponseHeader('Content-Disposition');

var fileName = contentDispositionHeader ? contentDispositionHeader.split('filename=')1 : 'default_filename.xls';

//需要对汉字编码否则会可能会乱码

var decodedFileName = decodeURIComponent(fileName);

// 创建Blob对象

var blob = new Blob(xhr.response, { type: 'application/octet-stream' });

// 创建临时URL并分配给一个链接

var url = window.URL.createObjectURL(blob);

var a = document.createElement('a');

a.href = url;

a.download = decodedFileName;

document.body.appendChild(a);

a.click();

} else {

console.error("Error:", xhr.statusText);

}

}

};

xhr.send();

相关推荐
lichenyang4536 分钟前
NestJS + Socket.IO 鉴权、用户房间与幂等邀请
前端·后端
paopaokaka_luck7 分钟前
基于springboot3+vue3+uniapp的剧本杀预约小程序(AI角色对话、协同过滤算法、地图Api、Echarts图形化分析)
java·前端·spring boot·学习·echarts
lichenyang4537 分钟前
React 实时通知与异步竞态处理
前端·后端
三十而立洋13 分钟前
搭建现代化 Git 提交规范:commitlint + czg + husky + lint‑staged 完整实战
前端
半个落月15 分钟前
React + Vite Todo 实践:用 Axios 与 Mock 解开前后端等待
前端
yuqifang17 分钟前
var deferred = jQuery.Deferred(); 使用示例
前端·javascript·面试
阳火锅18 分钟前
领导夸我日报越写越详细了,其实我只敲了 npm run commit
前端·javascript·人工智能
lichenyang45319 分钟前
实时团队邀请的架构与数据流
前端·后端
一鸣AI编程21 分钟前
AI UI 测试平台从 0 到 1:8 次跑通一条 19 步用例的实战复盘
前端
PedroQue9928 分钟前
Vite 1.2.0发布:自动生成pages.json
前端·vite