.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(newheads[columnName]);

}

//生成数据

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

{

row = sheet.CreateRow(count++);

int bodyIndex = 0;

foreach (string key in newheads.Keys)

{

row.CreateCell(bodyIndex++).SetCellValue(data2[key] != null ? data2[key].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();

相关推荐
dy17174 分钟前
vue左右栏布局可拖拽
前端·css·html
zhougl9965 分钟前
AJAX本质与核心概念
前端·javascript·ajax
GISer_Jing21 分钟前
Taro跨端开发实战:核心原理与关键差异解析
前端·javascript·taro
无心使然云中漫步21 分钟前
vant实现自定义日期时间选择器(年月日时分秒)
前端·vue
极客先躯27 分钟前
EasyUI + jQuery 自定义组件封装规范与项目结构最佳实践
前端·jquery·easyui
❀͜͡傀儡师39 分钟前
docker部署Docker Compose文件Web管理工具Dockman
java·前端·docker·dockman
karshey1 小时前
【前端】sort:js按照固定顺序排序
开发语言·前端·javascript
MyBFuture1 小时前
索引器实战:对象数组访问技巧及命名空间以及项目文件规范
开发语言·前端·c#·visual studio
IT_陈寒1 小时前
Redis性能提升50%的7个实战技巧,连官方文档都没讲全!
前端·人工智能·后端
打小就很皮...1 小时前
React 富文本图片上传 OSS 并防止 Base64 图片粘贴
前端·react.js·base64·oss