Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NPOI - Writing to file corrupts .xlsx workbook

Tags:

c#

xlsx

npoi

I have a piece of code that is currently writes to a .xls workbook (HSSFWorkbook) with no issue. However when I try to use the same code to write to a .xlsx workbook (XSSFWorkbook) the archive becomes corrupted and cannot be opened in excel.

The following code is what I am using to access the workbook, edit the workbook, and then save back to the workbook. I originally assumed that the code that I was using to edit the workbook was the issue, but after commenting it out the issue still persists.

IWorkbook workbook;
using (var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    if (Path.GetExtension(fileName).Contains("xlsx"))
    {
        workbook = new XSSFWorkbook(file);
    }
    else
    {
        workbook = new HSSFWorkbook(file);
    }
}

//Code that edits workbook which is currently commented out

using (var file = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
{
    workbook.Write(file);
}

I have tried running this code against a blank .xlsx workbook and the file becomes corrupt, and is no longer able to be opened.

I am using the latest stable version of NPOI from nuget: NPOI 2.1.3.1

like image 324
James C. Taylor IV Avatar asked Mar 12 '23 20:03

James C. Taylor IV


1 Answers

After trying everything that was mentioned on NPOI's Codeplex to no avail, I tried messing with the FileStream properties and was able to get the blank .xslx to save. I am using the following code to write back to the file:

using (var file = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
    workbook.Write(file);
}

This has fixed the primary issue of saving a back to a XssfWorkbook.

like image 195
James C. Taylor IV Avatar answered Mar 27 '23 02:03

James C. Taylor IV