使用OpenXML SDK用换行符替换docx文件上的文本(换行符)

我正在尝试使用C#替换整个 DOCX文件上的特定字符串,并使用换行符(换行符)。

我要搜索的文本字符串可以位于文件的段落或表格中。

我目前正在使用下面的代码替换文本。

using (WordprocessingDocument doc = WordprocessingDocument.Open("yourdoc.docx", true)) { var body = doc.MainDocumentPart.Document.Body; foreach (var text in body.Descendants()) { if (text.Text.Contains("##Text1##")) { text.Text = text.Text.Replace("##Text1##", Environment.NewLine); } } } 

问题:当我运行此代码时,输​​出DOCX文件将文本替换为空格(即“”)而不是换行符。

如何更改此代码才能使其正常工作?

试着rest一下 。 查看此链接上的示例。 你只需要附加一个Break

段落,智能标签,超链接都在Run中 。 所以也许你可以尝试这种方法 。 要更改表中的文本,您必须使用此方法 。 同样,文本总是在Run中。

如果你说替换只是替换空字符串,我会尝试这样做:

 using (WordprocessingDocument doc = WordprocessingDocument.Open(@"yourpath\testdocument.docx", true)) { var body = doc.MainDocumentPart.Document.Body; var paras = body.Elements(); foreach (var para in paras) { foreach (var run in para.Elements()) { foreach (var text in run.Elements()) { if (text.Text.Contains("text-to-replace")) { text.Text = text.Text.Replace("text-to-replace", ""); run.AppendChild(new Break()); } } } } } 

而不是添加换行符,尝试制作两个段落,一个在“要替换的文本”之前,一个在之后。 这样做会自动在两段之间添加换行符。

text.Parent.Append(new DocumentFormat.OpenXml.Wordprocessing.Break());

 // Open a WordprocessingDocument for editing using the filepath. using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepath, true)) { // Assign a reference to the existing document body. Body body = wordprocessingDocument.MainDocumentPart.Document.Body; //itenerate throught text foreach (var text in body.Descendants()) { text.Parent.Append(new Text("Text:")); text.Parent.Append(new Break()); text.Parent.Append(new Text("Text")); } } 

这将返回:

文本:
文本: