Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

I am trying to use C# to replace a specific string of text on an entire DOCX file with a line break (newline).

The string of text that I am searching for could be in a paragraph or in a table in the file.

I am currently using the code below to replace text.

using (WordprocessingDocument doc = WordprocessingDocument.Open("yourdoc.docx", true))
{
  var body = doc.MainDocumentPart.Document.Body;

  foreach (var text in body.Descendants<Text>())
  {
    if (text.Text.Contains("##Text1##"))
    {
      text.Text = text.Text.Replace("##Text1##", Environment.NewLine);
    }
  }
}

ISSUE: When I run this code, the output DOCX file has the text replaced with a space (i.e. " ") instead of a line break.

How can I change this code to make this work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(@"yourpathestdocument.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());
                        }
                    }
                }
            }
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...