c# OpenXML 搜索和替换文本不保存 [英] c# OpenXML search and replace text not saving

查看:57
本文介绍了c# OpenXML 搜索和替换文本不保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to do a basic search and replace of text on a .docx word document using OpenXML and Eric White's OpenXmlPowerTools (installed from NuGet). I've followed examples on this site and his blog, but for some reason I never see the changes appearing in the document when I open it after running the code. Here is the simple function I'm running:

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() 调用,但我一直在尝试任何事情来让这件事发挥作用.有什么建议么?谢谢

The message box does show a big number of replacements it should have made, yet when I open the document I see no replacements. Also, I don't think I should need those document .Save() calls, but I've been trying anything to get this thing to work. Any suggestions? Thanks

推荐答案

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

I very luckily stumbled across the answer at 18:52 into the OpenXmlRegex youtube video (https://youtu.be/rDGL-i5zRdk?t=18m52s).. I need to call this PutXDocument() method on the MainDocumentPart for the changes to go into effect (instead of the doc.Save() I was trying to do)

doc.MainDocumentPart.PutXDocument();

这篇关于c# OpenXML 搜索和替换文本不保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆