Save modified WordprocessingDocument to new file

前端 未结 5 671
礼貌的吻别
礼貌的吻别 2020-11-30 03:48

I\'m attempting to open a Word document, change some text and then save the changes to a new document. I can get the first bit done using the code below but I can\'t figure

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 04:16

    For me this worked fine:

    // To search and replace content in a document part.
    public static void SearchAndReplace(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 world!");
            docText = regexText.Replace(docText, "Hi Everyone!");
    
            using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
            {
                sw.Write(docText);
            }
        }
    }
    

提交回复
热议问题