如何用Google Apps Script比较Google Sheet日期选取较新值作参数
Google Sheet批量生成PDF的startingDate逻辑修复
现存问题点
- 原代码将日期转成本地化字符串后做对比,受时区、区域格式影响极易出现判断错误,日期对比必须基于原生Date对象的时间戳完成
- 原
createPDF函数内替换{DEBUT}占位符时,误用了未定义的debut变量,会直接触发运行时报错 - 提前声明数组存储所有行startingDate的方案没有必要,逐行处理数据时实时计算即可,逻辑更简单
- 用
getDisplayValues()读取日期字段时,拿到的是格式化后的字符串,解析容错率低,容易出现日期转换失败 - 原代码传参时将姓、名的索引写反,会导致生成的PDF中姓名位置颠倒
修复后完整代码
function createBulkPDFs(){ const docFile = DriveApp.getFileById("1CEJjt50pwNQpK_9tefzpNg5fzie8BeswZV3B4cecpPs"); const tempFolder = DriveApp.getFolderById("1keBnLhrMWjGokTOFdi2o25tjkTKjrKbO"); const pdfFolder = DriveApp.getFolderById("18N2DyrBRNggXle9Pfdi3wbn0NTcdgt93"); const currentSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Récupération du lead") // 用getValues读取原生数据,避免显示格式带来的解析问题 const data = currentSheet.getRange(2,1,currentSheet.getLastRow()-1,33).getValues(); const now = new Date(); // 生成本月首日日期,时分秒统一设为0,避免时间差影响对比 const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0); let errors = []; data.forEach(row => { try{ // 逐行计算当前行的startingDate const rowStartDate = new Date(row[4]); const startingDate = rowStartDate.getTime() > firstDayOfMonth.getTime() ? rowStartDate : firstDayOfMonth; createPDF( row[3], // FirstName row[2], // LastName row[10],// Formation row[11],// Client startingDate, // 计算好的起始日期 `${row[2]} ${row[3]}`, // PDF文件名 docFile, tempFolder, pdfFolder ); errors.push([""]); } catch(err){ errors.push(["Failed"]); } }); currentSheet.getRange(2,32,currentSheet.getLastRow()-1,1).setValues(errors); } function createPDF(firstName,lastName,formation,client,startingDate,pdfName,docFile,tempFolder,pdfFolder) { const tempFile = docFile.makeCopy(tempFolder); const tempDocFile = DocumentApp.openById(tempFile.getId()); const body = tempDocFile.getBody(); body.replaceText("{PRENOM}", firstName); body.replaceText("{NOM}", lastName); body.replaceText("{FORMATION}", formation); body.replaceText("{CLIENT}", client); // 修复原代码变量名笔误,统一转成法语区日期格式写入模板 body.replaceText("{DEBUT}", startingDate.toLocaleDateString("fr-FR")); tempDocFile.saveAndClose(); const pdfContentBlob = tempFile.getAs(MimeType.PDF); pdfFolder.createFile(pdfContentBlob).setName(pdfName); tempFolder.removeFile(tempFile); }
关键修改说明
- 日期对比全部基于
getTime()返回的毫秒级时间戳完成,完全规避字符串格式、本地化规则带来的判断误差 - 本月首日日期统一将时分秒设为0,避免和行内日期的时分秒值产生不必要的大小偏差
- 修复了原代码三处笔误:一是姓、名传参顺序颠倒,二是占位符替换时误用未定义的
debut变量,三是lasttName参数名多写了一个t - 日期写入PDF模板时统一转成法语区常用的
dd/mm/yyyy格式,适配你的表格使用场景 - 去掉了冗余的数组预存逻辑,逐行计算起始日期,代码可维护性更高
- 如果需要自定义startingDate在PDF里的显示格式,直接修改
toLocaleDateString的参数即可
内容的提问来源于stack exchange,提问作者Sebbie
相关产品推荐
相关产品推荐

