Google Apps Script在Sheets中报错:TypeError: Cannot read properties of null (reading 'getBody')
问题解决:TypeError: Cannot read properties of null (reading 'getBody')
错误原因
你在Google Sheets环境下运行脚本时,DocumentApp.getActiveDocument()会返回null——这个方法仅针对在Google Docs编辑器内运行的脚本设计,在Sheets里无法获取"活跃文档",因此调用getBody()会触发空指针错误。
修正后的代码
function InsertarDatos() { const plantillaDocId = "1kM-zglMjbckKnacmV5K21j1r3CjDmn70yrzsCcKrNdw"; const plantillaDoc = DriveApp.getFileById(plantillaDocId); const hojaActual = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // 一次性读取所有需要的数据,提升运行效率 const datos = hojaActual.getRange(2, 1, hojaActual.getLastRow() - 1, 5).getValues(); datos.forEach(filaDatos => { const nombre = filaDatos[0]; if (!nombre) return; // A列为空则跳过当前行 // 复制模板文档并命名 const nuevoDoc = plantillaDoc.makeCopy(`Nombre: ${nombre}`); // 打开新复制的文档(核心修正) const documento = DocumentApp.openById(nuevoDoc.getId()); const cuerpoDoc = documento.getBody(); // 生成格式化日期文本 const fecha = new Date(); const fechaT = `Certificado emitido el día ${fecha.getDate()} del mes ${fecha.getMonth() + 1} de ${fecha.getFullYear()}.`; // 替换文档中的占位符 cuerpoDoc.replaceText("<<nombre>>", nombre); cuerpoDoc.replaceText("<<dni>>", filaDatos[1] || ""); cuerpoDoc.replaceText("<<curso>>", filaDatos[2] || ""); cuerpoDoc.replaceText("<<empresa>>", filaDatos[3] || ""); cuerpoDoc.replaceText("<<calific>>", filaDatos[4] || ""); cuerpoDoc.replaceText("<<fecha>>", fechaT); // 保存并关闭文档,确保修改生效 documento.saveAndClose(); }); }
关键修正说明
- 核心错误修复:用
DocumentApp.openById(nuevoDoc.getId())替代DocumentApp.getActiveDocument(),直接打开刚复制的新文档,避免空指针。 - 性能优化:一次性读取所有行数据,避免循环中反复调用
getRange(),减少API请求次数。 - 数据安全:添加
documento.saveAndClose()确保修改后的文档正确保存。 - 空值处理:对可能为空的单元格用
|| ""兜底,避免替换时出现undefined。
内容的提问来源于stack exchange,提问作者Asier Párraga
相关产品推荐
相关产品推荐

