使用 OpenXML SDK 用换行符(换行符)替换 docx 文件上的文本 [英] Using OpenXML SDK to replace text on a docx file with a line break (newline)

查看:80
本文介绍了使用 OpenXML SDK 用换行符(换行符)替换 docx 文件上的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 C# 用换行符(换行符)替换 整个 DOCX 文件中的特定文本字符串.

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

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

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

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);
    }
  }
}

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

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?

推荐答案

尝试使用 打破.检查此链接上的示例.你只需要附加一个 Break

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

段落、智能标签、超链接都在运行.所以也许你可以试试这个方法.要更改表格内的文本,您必须使用此 方法.同样,文本始终在 Run 内.

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	estdocument.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());
                        }
                    }
                }
            }
        }

这篇关于使用 OpenXML SDK 用换行符(换行符)替换 docx 文件上的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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