第一步重写MemoryStream , 让它不能自动关闭.
1 //新建类 重写Npoi流方法 2 public class NpoiMemoryStream : MemoryStream 3 { 4 public NpoiMemoryStream() 5 { 6 AllowClose = true; 7 } 8 9 public bool AllowClose { get; set; } 10 11 public override void Close() 12 { 13 if (AllowClose) 14 base.Close(); 15 } 16 }
第二部 控制一下.
//导出Excel文件的方法 var ms = new NpoiMemoryStream(); ms.AllowClose = false; workbook.Write(ms); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); ms.AllowClose = true; return File(ms, "application/vnd.ms-excel","某某.xlsx");