簡體   English   中英

OpenXML MainDocumentPart.Document.Save() 似乎沒有保存在.Net 5

[英]OpenXML MainDocumentPart.Document.Save() doesn't seem to save in .Net 5

我一直在將應用程序從 .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 替換成功。 它似乎沒有寫回 stream。 我試過使用“.MainDocumentPart.PutXDocument();” 而不是“.Save()”——沒有區別。

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

有什么想法嗎? 它快把我逼瘋了。 謝謝。

最后,我找到了它:對於其他面臨同樣問題的人。 你需要把 docTest;Close(). 在;保存()之后。 - 在舊的、Net Framework 版本上它不需要它。 但在,網絡核心。 你做。

                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 只是我用來替換文本同時保留換行符的擴展方法——這並不重要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM