3

我正在尝试使用 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() 调用,但我一直在尝试任何事情来让这个东西工作。有什么建议么?谢谢

4

2 回答 2

6

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

doc.MainDocumentPart.PutXDocument();
于 2017-03-21T17:34:53.073 回答
0

试试这个方法:

        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();               
        }
于 2017-03-21T15:50:12.000 回答