如何在OpenXML段落,运行,文本中使用格式保留字符串? [英] How to Preserve string with formatting in OpenXML Paragraph, Run, Text?

查看:180
本文介绍了如何在OpenXML段落,运行,文本中使用格式保留字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遵循这种结构,将字符串中的文本添加到Word文档的一部分的OpenXML Runs中.

I am following this structure to add text from strings into OpenXML Runs, Which are part of a Word Document.

该字符串具有新的行格式,甚至具有段落缩进,但是当将文本插入到行中时,所有这些都将被剥离.我该如何保存?

The string has new line formatting and even paragraph indentions, but these all get stripped away when the text gets inserted into a run. How can I preserve it?

Body body = wordprocessingDocument.MainDocumentPart.Document.Body;

String txt = "Some formatted string! \r\nLook there should be a new line here!\r\n\r\nAndthere should be 2 new lines here!"

// Add new text.
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text(txt));

推荐答案

您需要使用

You need to use a Break in order to add new lines, otherwise they will just be ignored.

我组合了一个简单的扩展方法,该方法将在新行上分割字符串,并将Text元素追加到带有Break s的Run中,其中新行是:

I've knocked together a simple extension method that will split a string on a new line and append Text elements to a Run with Breaks where the new lines were:

public static class OpenXmlExtension
{
    public static void AddFormattedText(this Run run, string textToAdd)
    {
        var texts = textToAdd.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

        for (int i = 0; i < texts.Length; i++)
        {
            if (i > 0)
                run.Append(new Break());

            Text text = new Text();
            text.Text = texts[i];
            run.Append(text);
        }
    }
}

可以这样使用:

using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(@"c:\somepath\test.docx", true))
{
    var body = wordDoc.MainDocumentPart.Document.Body;

    String txt = "Some formatted string! \r\nLook there should be a new line here!\r\n\r\nAndthere should be 2 new lines here!";

    // Add new text.
    Paragraph para = body.AppendChild(new Paragraph());
    Run run = para.AppendChild(new Run());

    run.AddFormattedText(txt);
}

哪个会产生以下输出:

这篇关于如何在OpenXML段落,运行,文本中使用格式保留字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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