读取docx文件,并用另一个单词替换它(OpenXml)

时间:2019-05-24 12:52:25

标签: c# openxml

大家好,我只是用c#编程,正如我在标题中所问的那样,我希望获得帮助。 我有一个.docx文件,想阅读它,更改某些单词,最后将修改后的内容重写为另一个.docx文件。谢谢大家的帮助!

我将发布我的代码。代码会生成损坏的文件。

     public void SearchAndReplace(string documentInput, string pathOutput)
    {
        string docText = null;
        //Read
        using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(documentInput, true))
        {
            using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
            {
                docText = sr.ReadToEnd();
            }
        }

        //change word
        Regex regexText = new Regex("#DIREZIONECAP");
        docText = regexText.Replace(docText, "PROVAAAAA");

        using (WordprocessingDocument wordDocument =  WordprocessingDocument.Create(pathOutput, WordprocessingDocumentType.Document))
        {
          using (StreamWriter sw = new StreamWriter(pathOutput, false))
          {
             sw.Write(docText);
           }
        }
     }

0 个答案:

没有答案
相关问题