streamReader.ReadToEnd() return 只是 header OpenXML

streamReader.ReadToEnd() return just header OpenXML

拜托,我想在 word 文档中使用 openXML 查找一个词并将其替换为另一个词

我用这个方法

public static void AddTextToWord(string filepath, string txtToFind,string ReplaceTxt)
    {

     WordprocessingDocument wordDoc = WordprocessingDocument.Open(filepath, true);
        string docText = null;
        StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream());
        docText = sr.ReadToEnd();
        System.Diagnostics.Debug.WriteLine(docText);
        Regex regexText = new Regex(txt);
        docText = regexText.Replace(docText,txt2);
        StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create));
        System.Diagnostics.Debug.WriteLine(docText);         
        wordDoc.Close();
    }

但是

docText

return 只是文件的 xml shema 页面的头部。

  <?xml version="1.0" encoding=.......

检查你的字符串

如果您想替换现有内容中的特定字词或短语,您可能只想使用 String.Replace() 方法,而不是执行可能无法按预期工作的 Regex.Replace()(因为它需要一个正则表达式而不是传统的字符串)。如果您希望使用正则表达式,这可能无关紧要,但值得注意。

确保您正在提取内容

Word 文档显然不像纯文本那样容易解析,因此为了获得实际的 "content",您可能必须使用针对 Document.Body 属性的 an approach similar to the one mentioned here而不是使用 StreamReader 对象读取:

docText = wordDoc.MainDocumentPart.Document.Body.InnerText;

执行替换

话虽如此,您目前似乎正在读取文件内容并将其存储在名为 docText 的字符串中。由于您拥有该字符串并知道要查找和替换的值,只需调用 Replace() 方法,如下所示:

docText = docText.Replace(txtToFind,ReplaceTxt);

写出你的内容

执行替换后,您只需将更新后的文本写入流即可:

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