如何使用Apps Script将表格1的起止日期对应Type值填充到表格2
实现代码
function fillTypeToDateSheet() { // 读取表格1(当前激活的表)数据,默认列顺序:A列ID、B列名称、C列开始日期、D列结束日期、E列Type const ss1 = SpreadsheetApp.getActiveSpreadsheet(); const sheet1 = ss1.getActiveSheet(); const sheet1LastRow = sheet1.getLastRow(); const sheet1Data = sheet1.getRange("A2:E" + sheet1LastRow).getValues(); // 打开表格2,请替换引号内的ID为你自己的表格2ID const ss2 = SpreadsheetApp.openById('1z5WB1sACp1zvgfyXDbAmYxklSZOMIC8kNi_3Yci-PkM'); const sheet2 = ss2.getActiveSheet(); const sheet2LastCol = sheet2.getLastColumn(); // 读取表格2表头日期行,默认表头在第1行,从C列开始为2021年日期列 const headerDates = sheet2.getRange(1, 3, 1, sheet2LastCol - 2).getValues()[0]; // 统一转换为日期时间戳,避免格式与时区差异导致匹配失败 const headerTimestampList = headerDates.map(date => { const tempDate = new Date(date); return new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate()).getTime(); }); // 初始化输出数据数组 const outputValues = Array(sheet1Data.length).fill('').map(() => Array(headerTimestampList.length).fill('')); // 遍历每条表格1记录,匹配日期填充Type值 sheet1Data.forEach((record, rowIndex) => { const startDate = new Date(record[2]); const startTimestamp = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate()).getTime(); const endDate = new Date(record[3]); const endTimestamp = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate()).getTime(); const typeVal = record[4]; headerTimestampList.forEach((ts, colIndex) => { if(ts >= startTimestamp && ts <= endTimestamp) { outputValues[rowIndex][colIndex] = typeVal; } }); }); // 批量写入数据到表格2 // 写入ID与名称列 const idNameList = sheet1Data.map(record => [record[0], record[1]]); sheet2.getRange(2, 1, idNameList.length, 2).setValues(idNameList); // 写入日期对应Type值 sheet2.getRange(2, 3, outputValues.length, outputValues[0].length).setValues(outputValues); }
调整说明
- 如果你的表格1列顺序和默认不符,修改
record[x]中的数字即可,索引从0开始对应A列 - 如果你的表格2表头不在第1行、日期列不是从C列开始,修改
getRange的对应参数即可 - 代码采用一次性批量写入逻辑,运行效率远高于逐单元格写入,适合数据量较大的场景
内容的提问来源于stack exchange,提问作者MONICA
相关产品推荐
相关产品推荐

