Word open xml的富文本内容控件中的换行

问题描述 投票:0回答:1

我有一个带Rich text Content Control的Word文档。

我想用新行添加文本。

using (WordprocessingDocument theDoc = WordprocessingDocument.Open(docName, true))
 {
   MainDocumentPart mainPart = theDoc.MainDocumentPart;
   foreach (SdtElement sdt in mainPart.Document.Descendants<SdtElement>())
     {
        SdtAlias alias = sdt.Descendants<SdtAlias>().FirstOrDefault();
        if (alias != null)
          {
            string sdtTitle = alias.Val.Value;
            var t = sdt.Descendants<Text>().FirstOrDefault();
             if (sdtTitle == "Body")
               {
                 t.Text = "Welcome to Yazd With its winding lanes, forest of badgirs,\r\n mud-brick houses and delightful places to stay, Yazd is a 'don't miss' destination. On a flat plain ringed by mountains, \r\nthe city is wedged between the northern Dasht-e Kavir and southern Dasht-e Lut and is every inch a city of the desert." }
         }
     }
}

我在\r\n中使用文本,但不添加新行。

c# model-view-controller ms-word openxml openxml-sdk
1个回答
0
投票

某些字符,如制表符,换行符等,是用特殊的XML元素定义的。对于您的情况,您需要<w:br/>元素,因此请尝试以下操作:

using (WordprocessingDocument theDoc = WordprocessingDocument.Open(docName, true))
{
    MainDocumentPart mainPart = theDoc.MainDocumentPart;
    foreach (SdtElement sdt in mainPart.Document.Descendants<SdtElement>())
    {
        SdtAlias alias = sdt.Descendants<SdtAlias>().FirstOrDefault();
        if (alias != null && alias.Val.Value == "Body")
        {
            var run = sdt.Descendants<Run>().FirstOrDefault();
            run.RemoveAllChildren<Text>();

            var text = "Welcome to Yazd With its winding lanes, forest of badgirs,\r\n mud-brick houses and delightful places to stay, Yazd is a 'don't miss' destination. On a flat plain ringed by mountains, \r\nthe city is wedged between the northern Dasht-e Kavir and southern Dasht-e Lut and is every inch a city of the desert.";
            var lines = text.Split(new string[] { "\r\n" }, StringSplitOptions.None);

            foreach (var line in lines)
            {
                run.AppendChild(new Text(line));
                run.AppendChild(new Break());
            }

            run.Elements<Break>().Last().Remove();
        }
    }
}

我希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.