使用 DocumentFormat.OpenXml 进行 .docx 文件中的文本替换

问题描述 投票:0回答:0

我使用

DocumentFormat.OpenXml
来替换
.docx
文件中的文本。遇到了问题,因此开始进行一些调查,以便更深入地了解
DocumentFormat.OpenXml
的工作原理。结果我得到了两个 C# 方法,如下所示:

代码示例 1:

public static void SearchAndReplaceFile(string document)
        {
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
            {
                string docText = null;
                using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
                {
                    docText = sr.ReadToEnd();
                }

                Regex regexText = new Regex("Hello");
                docText = regexText.Replace(docText, "Good Morning");

                using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
                {
                    sw.Write(docText);
                }
                
            }
        }

代码示例 2:

public static void SearchAndReplaceFileUsingStream(string document)
        {
            Stream docStream = File.Open(document, FileMode.Open);
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(docStream, true))
            {
                string docText = null;
                using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
                {
                    docText = sr.ReadToEnd();
                }

                Regex regexText = new Regex("Hello");
                docText = regexText.Replace(docText, "Good Evening");

                
                using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
                {
                    sw.Write(docText);
                }
            }
        }

两种方法都应在输入

.docx
文件中将“Hello”替换为“Good Evening”,并且根据我的理解,两种方法都应提供相同的结果。然而,我实际上得到了不同的结果:

代码示例 1 - 运行良好,结果符合预期,“Hello”在

.docx
文件中被替换为“Good Evening”。

代码示例 2 - 我作为文本替换结果获得的

.docx
文件看起来已损坏。我无法通过 MS Word 打开更新的
.docx
文件,而是收到一条消息

我还观察到,通过

代码示例1
代码示例2获得的结果.docx文件的大小是不同的。

任何人都可以解释为什么代码示例 2 的结果不正确以及为什么它与代码示例 1 不同。我不想让您承担太多细节,只是想补充一点,对于我的任务来说,

WordprocessingDocument
对象是从 Stream 获取的,而不是直接从文件获取的,这一点很重要。因此,我需要让 Code Sample 2 正常工作,并且必须从 Code Sample 2 中的 Stream 获取
WordprocessingDocument
对象。

c# .net openxml
© www.soinside.com 2019 - 2024. All rights reserved.