OpenXML replace text in all document

前端 未结 3 628
一整个雨季
一整个雨季 2021-02-08 15:23

I have the piece of code below. I\'d like replace the text \"Text1\" by \"NewText\", that\'s work. But when I place the text \"Text1\" in a table that\'s not work anymore for th

3条回答
  •  不知归路
    2021-02-08 16:03

    Your code does not work because the table element (w:tbl) is not contained in a paragraph element (w:p). See the following MSDN article for more information.

    The Text class (serialized as w:t) usually represents literal text within a Run element in a word document. So you could simply search for all w:t elements (Text class) and replace your tag if the text element (w:t) contains your tag:

    using (WordprocessingDocument doc = WordprocessingDocument.Open("yourdoc.docx", true))
    {
      var body = doc.MainDocumentPart.Document.Body;
    
      foreach (var text in body.Descendants())
      {
        if (text.Text.Contains("##Text1##"))
        {
          text.Text = text.Text.Replace("##Text1##", "NewText");
        }
      }
    }
    

提交回复
热议问题