如何在不破坏 C# 样式的情况下向现有段落添加文本?

How to add text to existing paragraph without breaking the style in C#?

我一直在尝试解决 C# 中关于使用一些额外的新文本信息更新段落文本的问题:

我不是 C# 开发者,如果问题很愚蠢或容易解决,请原谅我。

我有几个这样的段落:

Alice is going to do some shopping.

Bob is a good guy.

比方说,这些段落是用 11 pts 的 Arial 字体写的。所以我想在每个段落之后添加一些文字。

最终结果将是:

Alice is going to do some shopping.SomeText0

Bob is a good guy.SomeText1

我试过这个:

using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
{
     List<Paragraph> paragraphs = paragraphService.GetParagraphs(wordDoc);
     foreach (Paragraph par in paragraphs) 
     {
         string paragraphText = paragraphService.ParagraphToText(par);
         paragraphText = textService.DeleteDoubleSpace(paragraphText);
         if (paragraphText.Length != 0) 
         {
             if (paragraphText == targetParagraph) 
             {
                 //Here I know that the added text will be corresponding to the my target paragraph.
                 //This paragraph comes from a JSON file but for simplicity I did not add that part.
                 par.Append(new Run(new Text("SomeText0")));
                 par.ParagraphProperties.CloneNode(true);
             }
         }
     }
 }

添加文本有效,但样式不一样,而且是一些我不想要的随机样式。我希望新添加的文本与段落具有相同的字体和大小。

我也尝试了几个选项,让它成为段落,只是文本等等。但是我找不到解决方案。

如有任何帮助,我们将不胜感激。

开放xml格式存储如下段落

<w:p>
  <w:r>
    <w:t>String from WriteToWordDoc method.</w:t>
  </w:r>
</w:p>

这里,

  1. p是Paragraph表示的元素class,
  2. r是Runclass表示的元素,并且,
  3. t是Textclass.
  4. 表示的元素

所以您要附加一个新的 <w:r> => Run 元素,它有自己的格式设置,并且由于您没有指定任何格式,因此使用默认值。

编辑 1:看起来,当本段中的某些部分格式不同时,一个段落下可以有多个 运行 元素。

因此,您可以找到包含 Text 元素的最后一个 运行 元素并修改其文本。

foreach (Paragraph par in paragraphs)
{
    Run[] runs = par.OfType<Run>().ToArray();
    if (runs.Length == 0) continue;
    Run[] runsWithText = runs.Where(x => x.OfType<Text>().ToArray().Length > 0).ToArray();
    if (runsWithText.Length == 0) continue;
    Text lastText = runsWithText.Last().OfType<Text>().Last();
    lastText.Text += " Some Text 0";
}

希望对您有所帮助。