无法从Google Sheet提取最后一行数据,请求技术协助
问题排查与修复:Google Sheet无法提取最后一行数据生成PDF邮件
核心错误原因
你代码里的关键问题是误用了方法:用获取最后一列的getLastColumn()来获取最后一行的行号,导致提取的是表格最后一列的行数据(而非最后一行),自然无法拿到刚提交的表单记录。
修复后的完整代码
function pdfMaker() { const id = 'ID123456789'; const ss = SpreadsheetApp.openById(id); const sheet = ss.getSheetByName('PDF-Data'); // 修正:改用getLastRow()获取最后一行行号 const lastRow = sheet.getLastRow(); // 修正:基于最后一行行号获取整行数据 const lastRowData = sheet.getRange(lastRow, 1, 1, sheet.getLastColumn()).getDisplayValues()[0]; const emailTemplate = HtmlService.createTemplateFromFile('qaemail.html'); const name = lastRowData[0]; const pom = lastRowData[4]; const email = lastRowData[3]; if (!email || !/^\S+@\S+\.\S+$/.test(email)) { Logger.log("Invalid email: " + email); return; } const user = { AgentName: name, DateOfEvaluation: lastRowData[2] }; emailTemplate.user = user; emailTemplate.id = pom; let html = `<div><img src="https://drive.google.com/file/d/123456789/view?usp=sharing" style="width: 200px;"></div>`; html += '<hr>'; html += '<h4>Quality Evaluation</h4>'; html += '<table style="border-collapse: collapse;">'; html += '<tbody>'; html += `<tr><td>Quality Evaluation for:</td><td>${lastRowData[0]}</td></tr>`; html += `<tr><td>Date of Evaluation:</td><td>${lastRowData[1]}</td></tr>`; html += `<tr><td>Evaluation made by:</td><td>${lastRowData[2]}</td></tr>`; html += `<tr><td>POM Number:</td><td>${lastRowData[4]}</td></tr>`; html += `<tr><td>Call Type:</td><td>${lastRowData[5]}</td></tr>`; html += `<tr><td>Evaluation Score:</td><td>${lastRowData[6]}</td></tr>`; html += '</tbody></table>'; html += '<hr>'; const htmlBody = emailTemplate.evaluate().getContent(); const blob = Utilities.newBlob(html, MimeType.HTML); blob.setName(lastRowData[0] + ' ' + lastRowData[4] + '.pdf'); const subject = 'Quality Evaluation for' + ' ' + lastRowData[0] + ' ' + 'POM' + ' ' + lastRowData[4]; MailApp.sendEmail({ to: email, subject: subject, htmlBody: htmlBody, attachments: [blob.getAs(MimeType.PDF)], }); // 修正:标记最后一行的第26列为"Email Sent" sheet.getRange(lastRow, 26).setValue("Email Sent"); }
额外优化建议
- 绑定表单提交触发器:要实现「提交Google Form后立即执行脚本」,需要在脚本编辑器中创建表单提交触发器:
- 点击编辑器顶部的「编辑」→「当前项目的触发器」
- 添加触发器,选择
pdfMaker函数,事件源选「表单」,事件类型选「表单提交」
- 避免硬编码列索引:可以把列索引定义为常量,比如
const COL_NAME = 0; const COL_EMAIL = 3;,后续用lastRowData[COL_NAME]代替,提升代码可读性和维护性 - 空数据校验:可以增加对
lastRowData是否为空的判断,避免因表格无数据导致报错
内容的提问来源于stack exchange,提问作者Metrpolitan Warehouse
相关产品推荐
相关产品推荐

