Search code examples
npoi

NPOI version 2.2+ MemoryStream.ToArray() 0 bytes


Using NPOI version 2.1.3.1, this line works perfectly, returning a a byte array with data: workbook is an XSSFWorkbook

using (var memoryStream = new MemoryStream())
{
    workbook.Write(memoryStream);
    return  memoryStream.ToArray();
}

when upgrading to 2.2 (and 2.3), this no longer returns any data, the byte array has 0 bytes. no exceptions are thrown, it just silently fails to write data.

Is there a new way to write this workbook out in the updated version?


Solution

  • I don't see any issue in your code. In fact I am using similar approach to get the result. Try type casting your returned value with MemoryStream class or define memorystream variable as type MemoryStream.

    Below is my approach

    public MemoryStream GetExcelStream()        
     {    
         MemoryStream ms = null;
         using (ms = new MemoryStream())
         {
           workbook.Write(ms); 
         }
       return ms;
     }
    
    MemoryStream excelMS = GetExcelStream();
     ..........................
    Response.BinaryWrite(excelMS.ToArray());
    Response.End();
    

    If above approach doesn't work, see this link as well NPOI writes 0 bytes in the MemoryStream