简体   繁体   English

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

[英]New Line in Rich Text Content Control of Word open xml

I have a Word document that has a Rich text Content Control .我有一个包含Rich text Content Control的 Word 文档。

I want to add text with new line.我想用新行添加文本。

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." }
         }
     }
}

I use a text with \r\n but don't add new line.我使用带有\r\n的文本,但不添加新行。

Some characters like tabs, new lines, etc. are defined with a special XML element.一些字符,如制表符、换行符等,是用特殊的 XML 元素定义的。
For your case, you need <w:br/> element so try something like the following:对于您的情况,您需要<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();
        }
    }
}

I hope this helps.我希望这有帮助。

Assuming you do want to restrict your function to Rich Text Content Controls, ie, block-level structured document tags, you would be looking for instances of SdtBlock .假设您确实希望将 function 限制为富文本内容控件,即块级结构化文档标签,您将寻找SdtBlock的实例。 Using SdtElement , you would also find inline-level ( SdtRun ), row-level ( SdtRow ), and cell-level ( SdtCell ) structured document tags, because SdtBlock , SdtRun , SdtRow , and SdtCell are subclasses of SdtElement .使用SdtElement ,您还会发现内联级 ( SdtRun )、行级 ( SdtRow ) 和单元级 ( SdtCell ) 结构化文档标签,因为SdtBlockSdtRunSdtRowSdtCellSdtElement的子类。

The following is a straightforward implementation that assumes the Rich Text Content Control is supposed to contain only the multi-line text.下面是一个简单的实现,假设富文本内容控件应该只包含多行文本。 It trims the lines because the sample text contains what looks like extraneous spaces.它修剪线条,因为示例文本包含看起来像无关空格的内容。

public void AddMultiLineTextToRichTextContentControlsUsingRuns()
{
    // Produce the list of lines from the text separated by "\r\n"
    // in the question, trimming leading and trailing whitespace.
    const string 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.";
    string[] separator = { "\r\n" };

    List<string> lines = text
        .Split(separator, StringSplitOptions.None)
        .Select(line => line.Trim())
        .ToList();

    // Get the w:document element.
    const string path = @"path\to\your\document.docx";
    using WordprocessingDocument wordDocument = WordprocessingDocument.Open(path, true);
    Document document = wordDocument.MainDocumentPart.Document;

    // Get all Rich Text (i.e., block) w:sdt elements having a w:alias
    // descendant with w:val="Body".
    IEnumerable<SdtBlock> sdts = document
        .Descendants<SdtBlock>()
        .Where(sdt => sdt.Descendants<SdtAlias>().Any(alias => alias.Val == "Body"));

    foreach (SdtBlock sdt in sdts)
    {
        // Create one w:r element per line, prepending a w:br to the
        // second and following runs.
        IEnumerable<Run> runs = lines
            .Select((line, index) =>
                index == 0
                    ? new Run(new Text(line))
                    : new Run(new Break(), new Text(line)));

        // Create or replace the w:sdtContent element with one that has
        // a single w:p with one or more w:r children.
        sdt.SdtContentBlock = new SdtContentBlock(new Paragraph(runs));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM