Return excel file without saving it in the server inside controller

warheat1990 picture warheat1990 · Aug 19, 2015 · Viewed 9.3k times · Source

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.

Answer

holdenmcgrohen picture holdenmcgrohen · Aug 19, 2015
[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();
}