NPOI - Writing to file corrupts .xlsx workbook

不打扰是莪最后的温柔 提交于 2019-12-10 17:32:19

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/36142337/npoi-writing-to-file-corrupts-xlsx-workbook

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