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

使用TemplateEngine.DocX时RepeatContent报错:Field content for field '' not found

解决TemplateEngine.DocX重复表格行的报错问题

核心问题分析

你遇到的“Field content for field '' not found”错误,主要来自三个方面:

  • 字段名称不匹配:模板里的Plain Text控件名称是USERNAME、AGE、SEX、ADDRESS,但代码里用的是NAME1、AGE1,引擎找不到对应字段,导致空字段报错。
  • 重复控件名称不匹配:RepeatContent("Repeater2")中的Repeater2必须和模板里Repeating Section Content Control的Title属性完全一致,否则引擎无法定位重复区域,也会触发空字段错误。
  • 代码语法错误:你的repeatertoFill定义末尾缺少闭合的);,语法错误会导致运行时异常。

修正后的代码示例

先确保模板设置正确:

  • 表格行的Repeating Section Content Control的Title设为Repeater2
  • 行内的Plain Text控件Title分别设为USERNAME、AGE、SEX、ADDRESS

然后替换为以下代码:

File.Copy(Repeater, RepeaterResult);

// 修正字段名称,匹配模板控件,修复语法
var repeatertoFill = new Content(
    new RepeatContent("Repeater2")
        .AddItem(
            new FieldContent("USERNAME", "Smith"),
            new FieldContent("AGE", "50"),
            new FieldContent("SEX", "M"),
            new FieldContent("ADDRESS", "Address Smith"))
        .AddItem(
            new FieldContent("USERNAME", "Mary"),
            new FieldContent("AGE", "50"),
            new FieldContent("SEX", "F"),
            new FieldContent("ADDRESS", "Address Mary"))
        .AddItem(
            new FieldContent("USERNAME", "David"),
            new FieldContent("AGE", "50"),
            new FieldContent("SEX", "M"),
            new FieldContent("ADDRESS", "Address David"))
);

using (var outputDocument = new TemplateProcessor(RepeaterResult))
{
    outputDocument.FillContent(repeatertoFill);
    outputDocument.SaveChanges();
}

额外注意事项

  • 所有Content Control的Title属性必须唯一且和代码中的名称完全一致(区分大小写)
  • 确保Repeating Section完全包裹需要重复的表格行,不要包含多余的行或控件
  • 生成的文件路径要确保有读写权限,避免保存失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 23:47:31