1

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

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
Harsh
  • 173
  • 1
  • 3
  • 11
  • What exactly are you trying to achieve in your sample? It looks slightly far from real application. If you want to get bytes of xlsx file content - you can read it directly from disk without using NPOI for opening file and then writing it back to memory stream. Workbook method `Write` closes the stream implicitly, and it is unavoidable (see [this discussion](http://apache-poi.1045710.n5.nabble.com/XSSFWorkbook-write-OutputStream-closes-the-stream-td4870079.html)) – Andrey Korneyev Jul 17 '15 at 07:27
  • I think you need to reset position `mstream.Position = 0;`, then you can invoke `mstream.Read` – cshu Jul 17 '15 at 08:35

2 Answers2

0
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");
PParmar
  • 95
  • 2
  • 9
0

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