c# - 为什么用 npoi 编辑后 docx 文件损坏

标签 c# docx npoi

我想编辑 .docx 文件并使用 npoi 库。

是一个片段:

XWPFDocument doc;
using( FileStream fileStream = new FileStream(@"D:\\template.docx", FileMode.Open, FileAccess.Read) ) {
doc = new XWPFDocument(fileStream);
    fileStream.Close();
}

// here can change doc or do nothing

using(FileStream fileStreamNew = new FileStream(@"D:\\test.docx", FileMode.CreateNew)) {
    doc.Write(fileStreamNew);
    fileStreamNew.Close();
}

但是我得到了损坏的文件。当我尝试打开文件时,显示模态窗口:“很抱歉。我们无法打开 test.docx,我们发现其内容有问题。详细信息:未指定的错误。位置:/word/header1.xml,行:0 , 列: 0"

提前致谢

============================================= =============

更新:

问题出在模板文件中。如果我从页眉和页脚中删除图像,那么错误就会消失。但是,如果我将模板图像放回错误返回。有什么想法吗?

============================================= ==============

更新:

当图像属性“Wrap Text”的值不是“In Line With Text”时,就会出现问题。在我的例子中,当图像是文本的背景时。 (“文本后面”值)。

最佳答案

尝试仅使用常规 Stream 和 System.IO.File 读取文件,然后使用 FileStream 和 System.IO.File 保存。

How to: Create a File or Folder (C# Programming Guide) C# (CSharp) NPOI.XWPF.UserModel.XWPFDocument Code Examples

XWPFDocument doc;
using( Stream fileStream = File.OpenRead("D:\\template.docx") ) {
doc = new XWPFDocument(fileStream);
    fileStream.Close();
}


using(FileStream fileStreamNew = File.Create("D:\\test.docx")) {
    doc.Write(fileStreamNew);
    fileStreamNew.Close();
}

关于c# - 为什么用 npoi 编辑后 docx 文件损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52169811/

相关文章:

c# - 使用 NPOI 生成带有合并标题的 Excel?

c# - 检查每个页面的登录

excel - 为什么这种格式 "[$-F400]h:mm:ss\AM/PM"在 Excel 中是 24 小时格式?

c# - NPOI 格式错误

c# - 使用 OpenXML SDK 将 docx 文件中的文本替换为换行符(换行符)

excel - VBA:Word将.docx文件保存为.doc文件,如何保存为docx?

php - 如何使用 PHP 读写编辑 pptx/docx/xlsx 文件?

c# - SMTP客户端 : How do I get failed delivery notifications?

c# - Web API 中的模型验证 - 在没有 throw 语句的情况下抛出异常?

c# - 使用 LINQ 选择 n 个最大的