后端代码
[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();