I'm using the following code to send an EPPlus package to the client as an Excel file in asp.net MVC. However, I'm having an issue with large files throwing OutOfMemoryException exceptions.
public class ExcelPackageResult : ActionResult
{
public ExcelPackage ExcelPackage { get; set; }
private string _fileName;
public ExcelPackageResult(ExcelPackage excelPackage, string fileName)
{
ExcelPackage = excelPackage;
_fileName = fileName;
}
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.ClearContent();
ExcelPackage.SaveAs(context.HttpContext.Response.OutputStream);
context.HttpContext.Response.AddHeader("content-disposition", string.Format(@"attachment;filename=""{0}.xlsx""", _fileName));
context.HttpContext.Response.ContentType = "application/excel";
context.HttpContext.Response.Flush();
context.HttpContext.Response.End();
ExcelPackage.Dispose();
}
}
The issue is at the line: ExcelPackage.SaveAs(context.HttpContext.Response.OutputStream);
I've also tried:
context.HttpContext.Response.BinaryWrite(ExcelPackage.GetAsByteArray());
Is there a way to stream the response directly from the ExcelPackage instead of allocating a block of memory for it before sending?