使用docx node库map生成表格报RangeError: Invalid array length
错误原因
你遇到的RangeError: Invalid array length是传入Table构造函数的rows参数格式错误导致的:
docx库中Table的rows字段要求传入TableRow实例组成的一维数组- 你的代码在
rowChildren.map()外层多套了一对方括号,相当于传入了嵌套的二维数组,库内部解析行配置时无法正确识别数组长度,直接抛出长度非法错误。
修复方法
移除包裹rowChildren.map()的外层方括号即可,如果你需要同时展示姓氏字段,可以在每行的children里补充对应单元格,修复后的完整示例代码:
const rowChildren = [ {firstName : "Susan", lastName: "Steward"}, {firstName : "Daniel", lastName: "Longbottom"}, {firstName : "Jacob", lastName: "Black"} ]; const table = new Table({ // 直接传入map生成的TableRow数组,无需额外套数组 rows: rowChildren.map(function(element){ return new TableRow({ children: [ new TableCell({ children: [new Paragraph(element.firstName)], }), // 如需展示lastName保留该单元格,不需要可删除 new TableCell({ children: [new Paragraph(element.lastName)], }) ], }) }), });
排查提示
后续给表格追加表头、合计行等内容时,直接把对应的TableRow实例和map生成的数组合并即可,不要额外嵌套数组层级,所有行节点必须放在同一个一维数组内传给rows字段。
内容的提问来源于stack exchange,提问作者Kode
相关产品推荐
相关产品推荐

