我正在按照此结构将字符串中的文本添加到Word文档的一部分的OpenXML运行中.
该字符串具有新的行格式,甚至具有段落缩进,但是当将文本插入到运行中时,所有这些都将被剥离.我该如何保存?
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));
解决方法:
您需要使用Break
才能添加新行,否则它们将被忽略.
我整理了一个简单的扩展方法,该方法将在新行上分割字符串,并将Text元素追加到带有中断的Run处,其中新行是:
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);
}
产生以下输出: