【问题标题】:OpenXML MainDocumentPart.Document.Save() doesn't seem to save in .Net 5 CoreOpenXML MainDocumentPart.Document.Save() 似乎没有保存在 .Net 5 Core
【发布时间】:2021-01-11 17:17:12
【问题描述】:

我一直在将应用程序从 .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

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

【问题讨论】:

    标签: asp.net-core openxml openxml-powertools


    【解决方案1】:

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

    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 只是我用来替换文本同时保留换行符的扩展方法,这并不重要。

    【讨论】:

    • 我正在处理 Excel 导出,数据未写入 Excel 文件。就我而言,_spreadsheetDocument.Close() 帮助解决了这个问题,感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 2014-03-05
    • 1970-01-01
    相关资源
    最近更新 更多