1

我一直在将应用程序从 .net 框架移植到 .net 5。我正在尝试通过读取模板文件、使用 Open-XML-PowerTools 替换一些文本并保存新版本来生成 Word 文档。我无法让“Save()”做任何事情!
这里有一些稍微简化的代码来演示这个问题:

byte[] content = System.IO.File.ReadAllBytes("c:\\Temp\\myrequesttemplate.docx");
using (MemoryStream mstr = new MemoryStream())
{
    mstr.Write(content, 0, content.Length);
    using var docTest = WordprocessingDocument.Open(mstr, true);
    {
        docTest.ReplaceText("%NAME%", mrcrequest.RequesterName); // At this point, I can see by looking at the document.innerxml that the replacement has been successful.
        docTest.MainDocumentPart.Document.Save();
    }
    using (FileStream fs = new FileStream("c:\\Temp\\TestWordDoc.docx", FileMode.CreateNew))
    {
        mstr.WriteTo(fs);
    }
}

创建的文件只是旧文件的副本,没有替换。我可以看到使用调试器查看 MainDocument 的 innerXML 替换成功。它似乎只是没有写回流。

我试过使用.MainDocumentPart.PutXDocument();而不是.Save()- 它没有区别。

我正在使用 DocumentFormat.OpenXML 2.12 版、System.IO.Packaging 5.0.0 和 Open-XML-PowerTools 4.4.0

有什么想法吗?快把我逼疯了!

4

1 回答 1

1

终于,我找到了!
对于面临同样问题的其他人:
您需要在不需要它的旧 .Net Framework 版本docTest.Close();之后放置.Save();,但在 .Net 核心中,您需要。

byte[] content = System.IO.File.ReadAllBytes("c:\\Temp\\myrequesttemplate.docx");
using (MemoryStream mstr = new MemoryStream())
{
    mstr.Write(content, 0, content.Length);
    using var docTest = WordprocessingDocument.Open(mstr, true);
    {
        docTest.ReplaceText("%NAME%", mrcrequest.RequesterName); // At this point, I can see by looking at the document.innerxml that the replacement has been successful.
        docTest.MainDocumentPart.Document.Save();
        docTest.Close();
    }
    using (FileStream fs = new FileStream("c:\\Temp\\TestWordDoc.docx", FileMode.CreateNew))
    {
        mstr.WriteTo(fs);
    }
}

顺便说一句,我忘了提到这docTest.ReplaceText只是我在保留换行符的同时替换文本的扩展方法,这并不重要。

于 2021-01-13T16:08:00.073 回答