Bre*_*ien 4 c# openxml openxml-sdk wordprocessingml
我正在尝试使用 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());
}
}
Run Code Online (Sandbox Code Playgroud)
消息框确实显示了它应该进行的大量替换,但是当我打开文档时,我没有看到任何替换。另外,我认为我不需要这些文档 .Save() 调用,但我一直在尝试任何方法来让这个东西工作。有什么建议么?谢谢
我很幸运地在 18:52 的 OpenXmlRegex youtube 视频( https://youtu.be/rDGL-i5zRdk?t=18m52s )中偶然发现了答案。我需要在 MainDocumentPart 上调用这个 PutXDocument() 方法来进行更改生效(而不是我试图做的 doc.Save() )
doc.MainDocumentPart.PutXDocument();
Run Code Online (Sandbox Code Playgroud)