Cannot access a closed stream (NPOI Library)

2019-09-18 00:44发布

问题:

I am using the following code to create an excel file using NPOI library. I am getting "Cannot access a closed stream" error. I have gone through a few threads and tried to implement the suggestions, but its not working.

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);

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();

Kindly help me out in this regard.

Thanks

回答1:

int index=0;
XSSFWorkbook  wb = new XSSFWorkbook();
ISheet sheet = wb.CreateSheet("First Sheet");
  crow = sheet.CreateRow(rowindex);
            crow.HeightInPoints = 50;
            string Title = "[Case : " + "Demonstration Database for Clients" + "]\n" + "Productivity Report";
            ccel = crow.CreateCell(0);
            ccel.SetCellValue(Title);
            ccel.CellStyle = hstyle;
            ccel.CellStyle.WrapText = true;
            cra = new CellRangeAddress(rowindex, rowindex, 0, 14);
            sheet.AddMergedRegion(cra);
            rowindex++;
 FileStream sw = File.Create("d://header.xlsx");
            wb.Write(sw);
            sw.Close();
            MessageBox.Show("File Create");


回答2:

you do not need the memory stream try something like

 string excelLocation = Path.Combine(taskpath, "Test_Output.xlsx");
 FileStream sw = File.Create(excelLocation);

 wb.Write(sw);

 sw.Close();


标签: c# .net npoi