I am using NPOI library to export datatable to excel file.
When using HSSFWorkbook, everything works well. But I try to migrate to XSSFWorkbook today, got “Cannot access a closed stream” error. After debug, It is confirmed that XSSFWorkbook.write function closed the stream after write.
So the solution is clearly, use book.Write(ms, true); overided version to leave the stream open.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
XSSFWorkbook wb = null; using (FileStream file = new FileStream("D:\\Test_Output.xlsx", FileMode.Open, FileAccess.Read)) { wb = new XSSFWorkbook(file); } MemoryStream mstream = new MemoryStream(); wb.Write(mstream,true); //HSSFWorkbook do not have this overloaded version FileStream xfile = new FileStream(Path.Combine(taskpath, "Test_Output.xlsx"), FileMode.OpenOrCreate, System.IO.FileAccess.Write); byte[] bytes = new byte[mstream.Length]; mstream.Read(bytes, 0, (int)mstream.Length); xfile.Write(bytes, 0, bytes.Length); xfile.Close(); mstream.Close(); |