.NET 后端返回 File 文件,及前端处理直接在浏览器下载
在实际开发中,经常遇到需要后端生成文件(如 Excel)并让浏览器直接下载的需求。这里分享一套基于 C# 后端流式输出与前端 XMLHttpRequest 接收 Blob 的完整方案,重点解决文件名编码和下载触发问题。
后端代码逻辑
后端主要使用 NPOI 库生成 Excel 数据,通过内存流写入后设置响应头,最后以 File 结果返回。注意这里对文件名进行了 UTF-8 URL 编码,防止中文乱码。
[AllowAnonymous]
public System.Web.Mvc.ActionResult ExportByteExcel(string datatab, string columnnames, string schemecode)
{
// 生成文件名,包含时间戳避免冲突
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 = ;
strPath = System.Web.HttpContext.Current.Server.MapPath();
strExcelFile = strPath + ReportName + ;
FileStream OutFile = FileStream(strExcelFile, FileMode.Create, FileAccess.Write);
[] btArray = ms.ToArray();
OutFile.Write(btArray, , btArray.Length);
OutFile.Flush();
OutFile.Close();
encodedFileName = System.Web.HttpUtility.UrlEncode((ReportName + ).Replace(, ), System.Text.Encoding.UTF8);
contentDisposition = ContentDispositionHeaderValue()
{
FileName = encodedFileName
};
Response.Headers.Add(, contentDisposition.ToString());
contentType = ;
Response.Headers.Add(, contentType);
File(btArray, contentType);
}

