返回excel文件,而不保存在控制器内的服务器

我想要将Excel文件(使用NPOI库)返回给用户,而不需要先将文件保存在服务器中。 这是我的代码:

[HttpPost] [ValidateAntiForgeryToken] public ActionResult Report(SalesReportViewModel model) { if (ModelState.IsValid) { XSSFWorkbook wb = context.GetReport(model); //I have no idea what to return after I got my wb } return View(); } 

任何帮助将不胜感激。

 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Report(SalesReportViewModel model) { if (ModelState.IsValid) { XSSFWorkbook wb = context.GetReport(model); byte[] fileContents = null; using (var memoryStream = new MemoryStream()) { wb.Write(memoryStream); fileContents = memoryStream.ToArray(); } return File(fileContents, System.Net.Mime.MediaTypeNames.Application.Octet, "file.xlsx"); } return View(); } 

这个堆栈溢出问题有你的答案。 如何通过angularJS和webaAPI2下载内存stream对象

 [HttpPost] public HttpResponseMessage ExportReport([FromBody]DTOs.Report report) { try { IReportPersistenceManager manager = ContainerConfigurator.Instance.Resolve<IReportPersistenceManager>(); MemoryStream ms = new MemoryStream(); //we have to pass to the NOPI assemble file type as well as file name //since we only deal with excel for now we will set it but this could be configured later. long id = report.ReportId; string mimeType = "application/vnd.ms-excel"; string filename = "unknown"; manager.ExportDataToExcel(id, (name, mime) => { mimeType = mime; filename = name; return ms; }); ms.Position = 0; var response = new HttpResponseMessage(); response.Content = new ByteArrayContent(ms.ToArray()); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel"); return (response); } catch (Exception) { //error return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest); } }