Google Sheets单元格内容迁移至Google Doc脚本报错求助
问题解决:Google Apps Script 数组索引越界错误
错误原因
你遇到的TypeError: Cannot read properties of undefined (reading '7')是数组索引越界导致的:
sheet.getSheetValues(1, 1, rowCount, numColumns)返回的二维数组是0起始索引,即data[0]对应表格第1行,data[rowCount-1]对应表格最后一行。- 你的循环里用
counter+1作为行索引,当counter循环到rowCount-1时,number = rowCount,此时data[number]不存在(数组最大索引是rowCount-1),自然无法读取第7个元素(H列)。 - 另外,你要取的回复编号在I列,对应数组索引应该是
8(I是第9列,0起始),而非用循环计数生成编号。
修正后的代码
根据你的需求(I列是回复编号,H列是内容,每个条目单独占一页),修正后的脚本如下:
function myFunction() { const ss = SpreadsheetApp.getActiveSpreadsheet(); const sheet = ss.getActiveSheet(); const rowCount = sheet.getLastRow(); const numColumns = sheet.getLastColumn(); const doc = DocumentApp.create("Application (Responses) (1)"); const body = doc.getBody(); // 获取表格所有数据,0起始索引 const data = sheet.getSheetValues(1, 1, rowCount, numColumns); // 跳过表头(如果第1行是表头,从counter=1开始;无表头则从counter=0开始) for(let counter = 1; counter < rowCount; counter++){ // 取I列的回复编号(I列是第9列,索引8) const responseNumber = data[counter][8]; // 取H列的回复内容(H列是第8列,索引7) const responseContent = data[counter][7]; body.appendParagraph(responseNumber); body.appendParagraph(responseContent); body.appendPageBreak(); } }
关键修改点
- 行索引修正:直接用
counter作为data的行索引,避免超出数组范围。 - 编号来源修正:从I列(数组索引8)读取回复编号,确保编号和表格数据一致。
- 循环起始调整:如果表格第1行是表头,循环从
counter=1开始跳过表头;无表头则改为counter=0。
内容的提问来源于stack exchange,提问作者user30073632
相关产品推荐
相关产品推荐

