【问题标题】:c# OpenXML search and replace text not savingc# OpenXML 搜索和替换文本不保存
【发布时间】:2017-11-09 06:16:38
【问题描述】:

我正在尝试使用 OpenXML 和 Eric White 的 OpenXmlPowerTools(从 NuGet 安装)对 .docx word 文档上的文本进行基本搜索和替换。我已经关注了这个站点和他的博客上的示例,但由于某种原因,当我在运行代码后打开它时,我从来没有看到文档中出现的更改。这是我正在运行的简单函数:

void ReadDocument(string path)
{
    using (WordprocessingDocument doc = WordprocessingDocument.Open(path, true))
    {
        var content = doc.MainDocumentPart.GetXDocument().Descendants(W.p);
        var regex = new Regex(@"the", RegexOptions.IgnoreCase);
        int count = OpenXmlRegex.Replace(content, regex, "NewText", null);
        doc.MainDocumentPart.Document.Save();
        doc.Save();
        MessageBox.Show(count.ToString());
    }
}

消息框确实显示了它应该进行的大量替换,但是当我打开文档时,我没有看到任何替换。另外,我不认为我应该需要那些文档 .Save() 调用,但我一直在尝试任何事情来让这个东西工作。有什么建议么?谢谢

【问题讨论】:

    标签: c# openxml openxml-sdk wordprocessingml


    【解决方案1】:

    我非常幸运地在 18:52 偶然发现了 OpenXmlRegex youtube 视频 (https://youtu.be/rDGL-i5zRdk?t=18m52s) 的答案。我需要在 MainDocumentPart 上调用这个 PutXDocument() 方法才能使更改生效(而不是文档.Save() 我正在尝试做的)

    doc.MainDocumentPart.PutXDocument();
    

    【讨论】:

      【解决方案2】:

      试试这个方法:

              using (WordprocessingDocument doc = WordprocessingDocument.Open(@"filePath", true))
              {
                  string docText = null;
                  using (StreamReader sr = new StreamReader(doc.MainDocumentPart.GetStream()))
                  {
                      docText = sr.ReadToEnd();
                  }
      
                  Regex regexText = new Regex(@"the", RegexOptions.IgnoreCase);
                  docText = regexText.Replace(docText, "New text");
      
                  using (StreamWriter sw = new StreamWriter(doc.MainDocumentPart.GetStream(FileMode.Create)))
                  {
                      sw.Write(docText);
                  }
      
                  doc.MainDocumentPart.Document.Save();               
              }
      

      【讨论】:

      • 感谢您的回复。虽然这确实成功地进行了一些编辑并保存了文件,并且我可以在打开 Word 时看到更改,但它不适用于跨越 xml 中的多个运行的文本。这是导致我尝试使用 OpenXmlPowerTools 的最初问题,据说它可以对跨越多次运行的文本进行文本搜索。您的方法与我根据此问题中接受的答案尝试过的另一种方法不同:stackoverflow.com/questions/28697701/openxml-tag-search
      猜你喜欢
      • 2015-07-28
      • 2018-05-15
      • 2015-01-09
      • 2023-01-25
      • 2022-11-15
      • 2010-12-04
      • 1970-01-01
      • 1970-01-01
      • 2012-08-06
      相关资源
      最近更新 更多