Search code examples
asp.net-mvcexcelasp.net-mvc-5npoi

Return excel file without saving it in the server inside controller


I want to return Excel file (using NPOI library) to user without the need to save the file in the server first. Here's my code :

        [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();
        }

Any help will be appreciated.


Solution

  • [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();
    }