You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用OpenXml循环生成Docx段落持续报错,请求排查原因

解决OpenXML生成Docx段落的报错问题

报错原因分析

  • Paragraph结构违规:OpenXML中Paragraph的子元素只能是ParagraphProperties(段落属性)和Run(文本块),你把Run和另一个ParagraphProperties嵌套在第一个ParagraphProperties内部,完全不符合文档结构规范。
  • Run嵌套位置错误:第二个Run被放在了ParagraphProperties里,Run必须作为Paragraph的直接子元素,不能属于段落属性范畴。
  • RunProperties配置冗余:重复创建RunFonts实例,Ascii和HighAnsi字体可以在同一个对象中统一设置。
  • Text元素位置错误:第二个Run里的Text被错误塞进RunProperties中,Text应该是Run的同级子元素,和RunProperties并列。
  • 未关联到文档主体:仅实例化Paragraph但未将其添加到文档的Body集合,导致段落无法被写入,同时可能引发对象引用异常。

修正后的代码

// 确保你已获取文档的Body对象,示例:
// var body = document.MainDocumentPart.Document.Body;

foreach (var d1 in model.dtable)
{
    // 定义段落属性
    var paraProps = new ParagraphProperties(
        new Indentation { Left = "0", Hanging = "0" },
        new ParagraphStyleId { Val = "Normal" },
        new Justification { Val = JustificationValues.Both },
        new NumberingProperties(
            new NumberingLevelReference { Val = 0 },
            new NumberingId { Val = 1 }
        )
    );

    // 第一个文本块:加粗的d1.name
    var run1 = new Run(
        new RunProperties(
            new Bold(),
            new FontSize { Val = "22" },
            new RunFonts { Ascii = "Arial", HighAnsi = "Arial" }
        ),
        new Text(d1.name) { Space = SpaceProcessingModeValues.Preserve }
    );

    // 第二个文本块:普通的"text2"
    var run2 = new Run(
        new RunProperties(
            new FontSize { Val = "22" },
            new RunFonts { Ascii = "Arial", HighAnsi = "Arial" }
        ),
        new Text(" text2 ") { Space = SpaceProcessingModeValues.Preserve }
    );

    // 创建段落并追加到文档主体
    var paragraph = new Paragraph(paraProps, run1, run2);
    body.AppendChild(paragraph);
}

关键修正点

  1. 调整Paragraph的子元素结构,让ParagraphProperties和Run直接作为Paragraph的构造参数,符合OpenXML规范。
  2. 合并RunFonts的字体设置,消除冗余代码。
  3. 修正Text元素的嵌套位置,确保其属于Run的子元素。
  4. 添加body.AppendChild(paragraph),将生成的段落绑定到文档主体,保证内容能被写入Docx文件。

内容的提问来源于stack exchange,提问作者herakless

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 09:43:23