NPOI - 写入文件会损坏 .xlsx 工作簿 [英] NPOI - Writing to file corrupts .xlsx workbook

查看:23
本文介绍了NPOI - 写入文件会损坏 .xlsx 工作簿的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码当前写入 .xls 工作簿 (HSSFWorkbook) 没有问题.但是,当我尝试使用相同的代码写入 .xlsx 工作簿 (XSSFWorkbook) 时,存档已损坏且无法在 excel 中打开.

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

我尝试对空白的 .xlsx 工作簿运行此代码,但文件已损坏,无法再打开.

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

我使用的是来自 nuget 的最新稳定版 NPOI:NPOI 2.1.3.1

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

推荐答案

在尝试了 NPOI 上提到的所有内容之后Codeplex 无济于事,我尝试弄乱 FileStream 属性,并且能够获得空白的 .xslx 以进行保存.我正在使用以下代码写回文件:

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

这已经解决了将返回保存到 XssfWorkbook 的主要问题.

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

这篇关于NPOI - 写入文件会损坏 .xlsx 工作簿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆