如何用OpenXml C#实现段落居中?设置后无效果求解决方案
解决OpenXml段落居中对齐不生效的问题
我尝试使用OpenXml将段落设置为居中对齐,但该设置对段落没有生效。以下是我的代码:
//段落属性 ParagraphProperties User_heading_pPr = new ParagraphProperties(); //尝试设置段落居中 Justification justification1 = new Justification() { Val = JustificationValues.Center }; //逐段构建文本 Text text = new Text(DateTime.Now.ToString() + " , "); Text text1 = new Text(gjenerimi + " , "); Text text2 = new Text(...)
我看了你的代码,问题很明显——你只创建了段落属性和居中对齐的对象,但没把对齐设置加入到段落属性集合里,也没把段落属性绑定到目标段落上,OpenXml根本不知道要把这个对齐规则应用到哪里,自然不会生效。
给你修正后的完整代码示例:
// 创建段落属性对象 ParagraphProperties User_heading_pPr = new ParagraphProperties(); // 创建居中对齐对象,并添加到段落属性的元素集合中 Justification justification1 = new Justification() { Val = JustificationValues.Center }; User_heading_pPr.Append(justification1); // 这一步是核心,不能省略 // 把所有文本放到Run里(OpenXml要求文本必须包裹在Run中) Run textRun = new Run(); textRun.Append(new Text(DateTime.Now.ToString() + " , ")); textRun.Append(new Text(gjenerimi + " , ")); textRun.Append(new Text(...)); // 补全你的剩余文本内容 // 创建段落对象,关联段落属性和文本Run Paragraph targetParagraph = new Paragraph(); targetParagraph.Append(User_heading_pPr); // 绑定段落属性到段落 targetParagraph.Append(textRun); // 添加文本内容 // 最后记得把段落添加到文档的正确容器中(比如文档主体) // document.MainDocumentPart.Document.Body.Append(targetParagraph);
另外再提醒几个容易踩的坑:
- 如果是修改已有段落,不要直接新建
ParagraphProperties,而是获取段落已有的ParagraphProperties(如果没有就创建),再添加对齐设置,避免覆盖原有属性 - 检查是否存在其他冲突的对齐设置,比如之前给段落加了左对齐,会覆盖居中效果
- 严格遵循OpenXml的层级结构:
Document->Body->Paragraph->ParagraphProperties/Run,层级错误也会导致设置失效
内容的提问来源于stack exchange,提问作者Arbenita Musliu
相关产品推荐
相关产品推荐

