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.
XSSFWorkbook wb = null;
using (FileStream file = new FileStream("D:\\Test_Output.xlsx",
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"),
byte bytes = new byte[mstream.Length];
mstream.Read(bytes, 0, (int)mstream.Length);
xfile.Write(bytes, 0, bytes.Length);