Using OpenXML SDK to replace text on a docx file with a line break (newline)

一个人想着一个人 提交于 2019-11-28 12:44:41
Turay Melo

Try with a break. Check the example on this link. You just have to append a Break

Paragraphs, smart tags, hyperlinks are all inside Run. So maybe you could try this approach. To change the text inside a table, you will have to use this approach. Again the text is always inside a Run.

If you are saying that the replace is only replacing for an empty string, i would try this:

using (WordprocessingDocument doc =
                WordprocessingDocument.Open(@"yourpath\testdocument.docx", true))
        {
            var body = doc.MainDocumentPart.Document.Body;
            var paras = body.Elements<Paragraph>();

            foreach (var para in paras)
            {
                foreach (var run in para.Elements<Run>())
                {
                    foreach (var text in run.Elements<Text>())
                    {
                        if (text.Text.Contains("text-to-replace"))
                        {
                            text.Text = text.Text.Replace("text-to-replace", "");
            run.AppendChild(new Break());
                        }
                    }
                }
            }
        }

Instead of adding a line break, try making two paragraphs, one before the "text to be replaced" and one after. Doing that will automatically add a line break between two paragraphs.

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>())
 {
   text.Parent.Append(new Text("Text:"));
   text.Parent.Append(new Break());
   text.Parent.Append(new Text("Text"));
 }
}

This will return:

Text:
Text:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!