Excel NPOI生成不可读的内容

Excel NPOI生成不可读的内容,excel,apache-poi,npoi,Excel,Apache Poi,Npoi,我正在使用NPOI打开一个现有的Excel文件,进行修改,然后将其写回磁盘 但是,当我用NPOI打开文件并将其写回时,文件会被损坏。Excel抱怨文件“包含不可读的内容”,并询问是否要“恢复文件内容”。当我选择OK时,它会显示: Excel cannot open the file 'test.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrup

我正在使用NPOI打开一个现有的Excel文件,进行修改,然后将其写回磁盘

但是,当我用NPOI打开文件并将其写回时,文件会被损坏。Excel抱怨文件“包含不可读的内容”,并询问是否要“恢复文件内容”。当我选择OK时,它会显示:

Excel cannot open the file 'test.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.
这是我的密码:

        var excelFilename = "c:\\temp\\simplefile.xlsx";
        IWorkbook wb;
        using (var fs = File.OpenRead(excelFilename))
        {
            wb = new XSSFWorkbook(fs);
        }
        var sheet = wb.GetSheetAt(0);
        // For this sample, we don't make any modifications to the file.
        // Just opening and writing it back is enough to produce this error.
        using (var str = new FileStream(excelFilename, FileMode.Open, FileAccess.ReadWrite))
        {
            wb.Write(str);
        }
“simplefile.xlsx”是由excel 2010创建的空excel工作簿。
这里发生了什么?

我会尝试
var str=new FileStream(excelFilename,FileMode.Create,FileAccess.Write)
,因为工作簿应该覆盖整个文件并使用
FileMode.Open
:谢谢!问题解决了。对于任何遇到这个问题的人来说:NPOI在其他情况下会生成无法读取的文件。例如,在Excel中保存文件时,过滤器处于活动状态。保存前请先取消激活Excel中的任何筛选器-否则NPOI可能会生成不可读的文件。我会尝试
var str=new FileStream(excelFilename,FileMode.Create,FileAccess.Write)
,因为工作簿应该覆盖整个文件并使用
FileMode.Open
:谢谢!问题解决了。对于任何遇到这个问题的人来说:NPOI在其他情况下会生成无法读取的文件。例如,在Excel中保存文件时,过滤器处于活动状态。保存前请先取消激活Excel中的任何筛选器-否则NPOI可能会生成无法读取的文件。