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

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();
  }
}

关键修改点

  1. 行索引修正:直接用counter作为data的行索引,避免超出数组范围。
  2. 编号来源修正:从I列(数组索引8)读取回复编号,确保编号和表格数据一致。
  3. 循环起始调整:如果表格第1行是表头,循环从counter=1开始跳过表头;无表头则改为counter=0。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 15:55:11