使用jsPDF生成PDF表格仅显示数组首个元素,求技术帮助
问题排查与解决
问题根源在于循环中每次都用新创建的单行数组覆盖了this.bodList,导致最终this.bodList里只会保留循环最后一次的元素(若数组仅含一个元素则显示第一个,多元素则显示最后一个)。
错误代码分析
循环内的这段代码每次都会创建仅包含当前行的新数组,然后直接赋值给this.bodList,之前循环添加的内容会被完全覆盖:
let bod:any[] = [ [this.attendList[i].id, this.attendList[i].name, this.attendList[i].status,this.attendList[i].created_date] ] this.bodList=bod;
修复后的代码
修改循环逻辑,先初始化空数组,再逐行添加元素:
generatePdf() { this.attendList = this.attendanceList; // 初始化空数组,存储所有表格行 this.bodList = []; for(let i:number=0;i<this.attendList.length; i++){ // 创建当前行的数组 let row = [ this.attendList[i].id, this.attendList[i].name, this.attendList[i].status, this.attendList[i].created_date ]; // 将当前行添加到bodList中 this.bodList.push(row); } let text = ""; var pdf = new jsPDF(); pdf.setFontSize(2); pdf.text('Attendace List', 11, 8); pdf.setFontSize(12); pdf.setTextColor(99); (pdf as any).autoTable({ head: this.header, body: this.bodList, theme: 'grid', didDrawCell: data => { // console.log(data.column.index) } }) pdf.output('dataurlnewwindow') // pdf.save('table.pdf'); }
关键修改点
- 循环前初始化
this.bodList = [],避免未定义或覆盖问题 - 循环内创建单行数组后,用
push()方法添加到this.bodList,而非直接赋值覆盖
这样处理后,this.bodList会包含数组中所有元素对应的表格行,生成PDF时就能显示完整的列表了。
内容的提问来源于stack exchange,提问作者Kwabena Kev
相关产品推荐
相关产品推荐

