我想编辑 .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/