.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();

相关推荐
橙子家7 小时前
浏览器缓存之【身份与会话管理】:Cookies 和 Private state tokens
前端
最新资讯动态8 小时前
HDC 2026 | 对话鲸鸿动能:存量时代,品牌如何夺回营销“主动权”?
前端
最新资讯动态8 小时前
游戏出海,从产品走向体系
前端
最新资讯动态8 小时前
20人团队跑出百万DAU、大厂也来抢量:谁在鸿蒙生态跑出加速度
前端
最新资讯动态9 小时前
千万开发者背后,鸿蒙商业化的B面
前端
爱勇宝10 小时前
AI 时代:智商决定起点,情商决定走多远
前端·ai编程
kyriewen11 小时前
用了半年 Claude Code 后,我尝试关掉它写了一周代码——结果比想象中严重
前端·javascript·ai编程
IT_陈寒11 小时前
Vite的静态资源打包让我熬夜到三点,这坑千万别跳
前端·人工智能·后端
徐小夕12 小时前
万字拆解 JitWord:企业级实时协同文档底层架构 + 大模型 AI 融合完整实践
前端·vue.js·github
一份执念12 小时前
uni-app 小程序分包限制处理与主包体积优化实战
前端·微信小程序