如何通过Google Apps Script获取Google表单提交行的Reference ID值
问题
我有一个Google表单,提交的数据会同步到Google表格,同时会将详情生成PDF保存到Google云端硬盘,目前这些操作运行正常。
随后为表格新增了一个“Reference ID”字段,需要在Google Apps Script中获取该字段的值。我可以通过以下代码获取固定单元格(第1行第2列)的值且运行正常:
const sh1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheet1").getRange(1,2).getValue();
但我需要获取本次表单提交对应行的第2列(即Reference ID列)的值,由于可能存在多用户同时提交的情况,不能直接取最后一行的值。
以下是我的完整Apps Script代码:
//Form submission function afterFormSubmit(e) { const info = e.namedValues; const referId = getSheelValue(); createPDF(info, referId); } //Getting values from spreadsheet function getSheelValue(){ //here I need to get the value in a 2 column and row submitted from the form const sh1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheet1").getRange(1,2).getValue(); return sh1; } //Save PDF function createPDF(info, referId) { const pdfFolder = DriveApp.getFolderById("1xHzPbN17uF5fet7C"); const tempFolder = DriveApp.getFolderById("1nV6tOC99hj5G8Bbvg0O9Lxr"); const templateDoc = DriveApp.getFileById("1mv_5R5lkzOBuGCmwEe7BYd4S2IQkwE"); const newTempFile = templateDoc.makeCopy(tempFolder); const openDoc = DocumentApp.openById(newTempFile.getId()); const body = openDoc.getBody(); body.replaceText("{reff}", referId); body.replaceText("{date}", info['Timestamp'][0]); body.replaceText("{emal}", info['Email'][0]); body.replaceText("{name}", info['Name'][0]); openDoc.saveAndClose(); const blobPDF = newTempFile.getAs(MimeType.PDF); const pdfFile = pdfFolder.createFile(blobPDF).setName(info['Name'][0] + info['Timestamp'][0]); newTempFile.setTrashed(true); }
解决方案
核心思路是利用表单提交事件对象e自带的range属性,它指向本次提交数据所在的单元格范围,通过这个范围可以直接定位到对应行的第2列,完全避免多用户并发提交的冲突问题。
修改后的完整代码:
//Form submission function afterFormSubmit(e) { const info = e.namedValues; // 获取当前提交行的第2列值(Reference ID) const submitRow = e.range.getRow(); const referId = SpreadsheetApp.getActiveSpreadsheet() .getSheetByName("sheet1") .getRange(submitRow, 2) .getValue(); createPDF(info, referId); } //Save PDF function createPDF(info, referId) { const pdfFolder = DriveApp.getFolderById("1xHzPbN17uF5fet7C"); const tempFolder = DriveApp.getFolderById("1nV6tOC99hj5G8Bbvg0O9Lxr"); const templateDoc = DriveApp.getFileById("1mv_5R5lkzOBuGCmwEe7BYd4S2IQkwE"); const newTempFile = templateDoc.makeCopy(tempFolder); const openDoc = DocumentApp.openById(newTempFile.getId()); const body = openDoc.getBody(); body.replaceText("{reff}", referId); body.replaceText("{date}", info['Timestamp'][0]); body.replaceText("{emal}", info['Email'][0]); body.replaceText("{name}", info['Name'][0]); openDoc.saveAndClose(); const blobPDF = newTempFile.getAs(MimeType.PDF); const pdfFile = pdfFolder.createFile(blobPDF).setName(info['Name'][0] + info['Timestamp'][0]); newTempFile.setTrashed(true); }
关键说明:
e.range是表单提交事件的核心属性,它代表本次提交数据写入的单元格区域,即使多用户同时提交,每个事件的e.range都只会指向自己的提交行getRow()方法获取该区域所在的行号,再通过getRange(submitRow, 2)精准定位到当前提交行的第2列,确保拿到的是对应提交的Reference ID值
内容的提问来源于stack exchange,提问作者Chwijer
相关产品推荐
相关产品推荐

