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

相关推荐
bkspiderx2 分钟前
HTTP协议:Web通信的“通用语言”解析
前端·网络协议·http
云水一下3 分钟前
模块系统与 npm——万物皆模块
前端·npm·node.js
ZC跨境爬虫11 分钟前
跟着 MDN 学CSS day_47:(移动优先实战——从手机到宽屏的响应式进化)
前端·css·html·tensorflow·媒体
小新11012 分钟前
vue实战项目 计算器
前端·javascript·vue.js
秋田君13 分钟前
2026 前端新出路:掌握 C++ 核心语法,无缝衔接 QT 桌面开发
前端·c++·qt
学以智用14 分钟前
.NET Core 序列化 **超清晰完整版教程**
后端·.net
老毛肚24 分钟前
jeecgboot vue 路由 拆分01
前端·javascript·typescript
ZC跨境爬虫25 分钟前
跟着 MDN 学CSS day_46:(响应式实战——用媒体查询打造双列布局)
前端·css·ui·html·tensorflow·媒体
狗凯之家源码网27 分钟前
多语言企鹅养殖投资返利系统 自定义产品配置 一键部署源码
前端·架构·php
每天吃饭的羊30 分钟前
LeetCode 链表
前端