Npoi Web 項目中(XSSFWorkbook) 導出出現無法訪問已關閉的流


NPOI生產.xlsx文件件時,在使用book.Write(ms);后,會關閉流,這樣導致再次使用Respons輸出流的時候就出錯了。

造成關閉流的主要原因有時其實是跨域,同域是沒有問題的。

//新建類 重寫Npoi流方法
public class NpoiMemoryStream : MemoryStream
    {
        public NpoiMemoryStream()
        {
            AllowClose = true;
        }
 
        public bool AllowClose { get; set; }
 
        public override void Close()
        {
            if (AllowClose)
                base.Close();
        }
}
//導出Excel文件的方法
var ms = new NpoiMemoryStream();
ms.AllowClose = false;
workbook.Write(ms);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
ms.AllowClose = true;
 
HttpContext curContext = HttpContext.Current;
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = Encoding.UTF8;
curContext.Response.Charset = "";
curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
long fileSize = ms.Length;
curContext.Response.AddHeader("Content-Length", fileSize.ToString());
curContext.Response.BinaryWrite(ms.GetBuffer());
curContext.Response.End();

原文:https://blog.csdn.net/eit520/article/details/53231642 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM