C# Word OpenXml SDK - 添加文本到运行修剪空格

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

我正在尝试使用 OpenXml SDK 将文本运行添加到 Word 中的现有段落,但每次我这样做都会“修剪”我添加的文本。

例如

 Run newRun = newRun();
 newRun.AppendChild(new Text("Hello "));
 paragraph.AppendChild(newRun);

 Run newRun = newRun();
 newRun.AppendChild(new Text(" World"));
 paragraph.AppendChild(newRun);

 // the resulting paragraph contains "HelloWorld" as the text
 

我还检查了生成的结果运行的 XML,其中清楚地包含“空格”字符:

<w:t xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">Hello  </w:t>

我试过注入 '\u0020' unicode 值,以及只包含一个空格的“空”运行,但似乎没有任何效果。

有人知道这个的诀窍吗?

ms-word openxml openxml-sdk
2个回答
0
投票

发帖后 5 分钟(已经尝试了几个小时)我发现答案是多么典型

答案是将 XML xml:space="preserve" 属性添加到 Text 元素,否则空格将被修剪。

newRun.InnerXml = $"<w:t xml:space=\"preserve\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">{text}</w:t>";

0
投票

您可以使用

SpaceProcessingModeValues
枚举。

var text   = new Text("Hello ");

text.Space = SpaceProcessingModeValues.Preserve;

通过一些扩展方法,您可以自动处理它,也可以换行:

public static Text Append(this Run run, string text)
{
    Text lastText = null;

    if (text == null)
    {
        lastText = new Text();

        run.Append(lastText);

        return lastText;
    }

    var lines = text.Split(new[] { Environment.NewLine }, StringSplitOptions.None );

    for (int index = 0; index < lines.Length; index++)
    {
        if (index != 0)
            run.AppendBreak();

        var line = lines[index];

        lastText = new Text(line);

        if (line.StartsWith(" ") || line.EndsWith(" "))
            lastText.Space = SpaceProcessingModeValues.Preserve;

        run.Append(lastText);
    }

    return lastText;
}

public static void AppendBreak(this Run run)
{
    run.Append(new Break());
}
© www.soinside.com 2019 - 2024. All rights reserved.