Word Open XML富文本内容控件添加\r\n无法换行问题求助
在Word的Rich Text Content Control中添加换行的正确方法
你遇到的问题其实是因为Word的Open XML格式不认可普通的\r\n换行符——在WordprocessingML里,换行需要用专门的<w:br>元素(对应C#里的Break类)来实现,而不是直接在文本字符串里加换行符。
下面是修改后的代码,替换你原来的赋值逻辑,就能正确添加带换行的内容了:
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; // 找到Rich Text控件的内容容器 var sdtContent = sdt.Descendants<SdtContentBlock>().FirstOrDefault(); if (sdtTitle == "Body" && sdtContent != null) { // 清空原有内容 sdtContent.RemoveAllChildren(); // 第一段文本 var run1 = new Run(new Text("Welcome to Yazd With its winding lanes, forest of badgirs,")); // 添加换行 var break1 = new Run(new Break()); // 第二段文本 var run2 = new Run(new Text(" mud-brick houses and delightful places to stay, Yazd is a 'don't miss' destination. On a flat plain ringed by mountains,")); // 再添加换行 var break2 = new Run(new Break()); // 第三段文本 var run3 = new Run(new Text("the city is wedged between the northern Dasht-e Kavir and southern Dasht-e Lut and is every inch a city of the desert.")); // 将所有内容添加到控件容器中 sdtContent.Append(run1, break1, run2, break2, run3); } } } }
关键说明:
- 我们直接操作Rich Text控件的
SdtContentBlock容器,而不是只修改单个Text元素——这样能完全控制内容的结构。 - 每一个换行对应一个
Break元素,放在单独的Run里(或者和前后文本同属一个Run也可以,但分开更清晰)。 - 先清空原有内容,避免和旧文本混杂。
如果你的文本是动态生成的,也可以写一个小方法来拆分字符串并自动添加Break,比如根据\r\n拆分后循环创建Run和Break:
private static void AddTextWithLineBreaks(SdtContentBlock container, string text) { string[] lines = text.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None); for (int i = 0; i < lines.Length; i++) { container.Append(new Run(new Text(lines[i]))); if (i != lines.Length - 1) { container.Append(new Run(new Break())); } } }
然后在主代码里调用:
string content = "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."; AddTextWithLineBreaks(sdtContent, content);
这样不管你的文本有多少换行,都能自动处理啦!
内容的提问来源于stack exchange,提问作者ar.gorgin
相关产品推荐
相关产品推荐

