OpenXML replace text in all document

前端 未结 3 631
一整个雨季
一整个雨季 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:15

    Maybe this solution is easier

    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
    {
     string docText = null;
     //1. Copy all the file into a string
     using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
         docText = sr.ReadToEnd();
    
     //2. Use regular expression to replace all text
     Regex regexText = new Regex(find);
     docText = regexText.Replace(docText, replace);
    
     //3. Write the changed string into the file again
     using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
          sw.Write(docText);
    

提交回复
热议问题