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

查看:1068
本文介绍了使用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?

推荐答案

尝试用的打破。检查此链接的例子。你只需要添加一个休息

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

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

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