I am implementing a small export feature for a legacy webforms application.
My export code right now is only headers (just testing the that I can successfully create a file):
public MemoryStream Export()
{
var result = new MemoryStream();
using (var p = new ExcelPackage())
{
var ws = p.Workbook.Worksheets.Add("Contacts");
var col = 1;
ws.Cells[1, col++].Value = "ID";
ws.Cells[1, col++].Value = "First Name";
ws.Cells[1, col++].Value = "Last Name";
ws.Cells[1, col++].Value = "Email";
ws.Cells[1, col++].Value = "Phone";
ws.Cells[1, col++].Value = "Address";
p.SaveAs(result);
}
return result;
}
Here is the button handler:
var ms = Export();
ms.WriteTo(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("Content-Disposition", $"attachment;filename=Contacts_{DateTime.Now:yyyyMMddhhmmss}.xlsx");
HttpContext.Current.Response.StatusCode = 200;
// HttpContext.Current.Response.End();
So one issue is that all the examples I find have the HttpContext.Current.Response.End() call at the end of the method, but if I do this, it throws an exception. Commenting this line out seems to work fine but that leads me to my main problem: when the file is saved and then opened in excel, Excel complains there is a problem with the file. My impression is that EPPlus makes well formed files, so what am I missing?
Update #1 I tried directly saving the EPPlus package to disk. That seems to work without issue. So the problem lies somewhere between writing the package to the memorystream and returning the result.