Cannot access a closed stream (NPOI Library)

对着背影说爱祢 提交于 2019-12-13 21:32:47

问题


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


来源:https://stackoverflow.com/questions/31470173/cannot-access-a-closed-stream-npoi-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!