Unable to add new sheet to existing workbook

Dec 17, 2014 at 8:57 PM
Edited Dec 17, 2014 at 8:58 PM
I am using NPOI 2.1.3, and having an issue where the workbook.CreateSheet method is not adding a new sheet to an existing workbook. It's not even overwriting the sheet that's already there.

Here's my code:

FileStream fs = new FileStream(myExistingWorkbook.xlsx, FileMode.Open, FileAccess.ReadWrite);
IWorkBook workbook = new XSSFWorkbook(fs);
ISheet sheet1 = workbook.CreateSheet(newSheet);
sheet1.SetActive(true);

This code throws no errors, but still isn't working. Ideas? I'm using Excel 2013, FYI.
Coordinator
Dec 17, 2014 at 9:52 PM
Please make sure you write the result back to your Excel file. To write back, a new FileStream should be created. The original stream is for read purpose only!
Dec 18, 2014 at 12:23 PM
A thousand thanks, tonyqus. That worked like a charm.

For anyone else having the problem, here's how I fixed it:

//Check for existing workbook
FileStream fs = new FileStream(myExistingWorkbook.xlsx, FileMode.Open, FileAccess.ReadWrite);
IWorkBook workbook = new XSSFWorkbook(fs);
ISheet sheet1 = workbook.CreateSheet(newSheet);

//Code to populate new sheet content goes here

FileStream fs2 = new FileStream(mydocpath + @"\Productivity Report - " + fetch.ToString("MM-dd-yyyy") + ".xlsx", FileMode.Open, FileAccess.ReadWrite);
workbook.Write(fs2);
fs.Close();