tickwave
tickwave

Reputation: 3455

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.

Upvotes: 7

Views: 12609

Answers (2)

holdenmcgrohen
holdenmcgrohen

Reputation: 1063

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

Upvotes: 5

vijay shiyani
vijay shiyani

Reputation: 766

This stack overflow Question has your answer in it. How to download memory stream object via angularJS and webaAPI2

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

Upvotes: 1

Related Questions