Return excel 文件而不将其保存在控制器内的服务器中

Return excel file without saving it in the server inside controller

我想 return 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]
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);
   }
}
[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();
}