我正在使用以下代码将 EPPlus 包作为 asp.net MVC 中的 Excel 文件发送到客户端。但是,我遇到了抛出 OutOfMemoryException 异常的大文件的问题。
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();
}
}
问题在于:ExcelPackage.SaveAs(context.HttpContext.Response.OutputStream);
我也试过:
context.HttpContext.Response.BinaryWrite(ExcelPackage.GetAsByteArray());
有没有办法直接从 ExcelPackage 流式传输响应,而不是在发送之前为其分配一块内存?