Google表单联动Sheet:批量提取多列超链接存入文件夹的代码修改需求
解决方案:提取Google Sheet所有列的超链接并批量移动文件
以下是修改后的完整脚本,实现提取表单响应表中所有列的所有超链接(支持单列多个逗号分隔的链接),并将对应文件移动到新建的编号文件夹中:
function filter() { const ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form responses 1'); // 获取最新一行的所有数据 const lastRow = ss.getLastRow(); const data = ss.getRange(lastRow, 1, 1, ss.getLastColumn()).getValues()[0]; // 直接复制整行数据,无需手动逐个push const dataToCopy = [...data]; copyToProjectTab(dataToCopy, data); } function copyToProjectTab(dataToCopy, allData) { const sourceSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form responses 1'); const targetSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Response Folder Generation'); const sourceLastRow = sourceSheet.getLastRow(); const targetLastRow = targetSheet.getLastRow() + 1; // 生成文件夹编号 const ref = "JLSIR." + Utilities.formatDate(new Date(), "GMT+1", "yy") + "." + sourceLastRow; dataToCopy.unshift(ref); // 将数据写入目标表 targetSheet.getRange(targetLastRow, 1, 1, dataToCopy.length).setValues([dataToCopy]); // 传入整行数据给文件夹创建函数,而非单列数据 createFolder(targetLastRow, ref, allData); } function createFolder(rowNumber, refNumber, allData) { const targetSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Response Folder Generation'); // 替换为你的父文件夹ID const parentFolder = DriveApp.getFolderById('YOUR_PARENT_FOLDER_ID'); const newFolder = parentFolder.createFolder(refNumber); // 提取所有列中的文件ID const allFileIds = extractAllFileIds(allData); // 批量移动文件到新文件夹 allFileIds.forEach(fileId => { try { DriveApp.getFileById(fileId).moveTo(newFolder); } catch (e) { console.error(`无法移动文件ID ${fileId}: ${e.message}`); } }); // 设置文件夹链接 targetSheet.getRange(rowNumber, 1).setFormula(`=HYPERLINK("${newFolder.getUrl()}","${refNumber}")`); targetSheet.getRange(rowNumber, 150).setFormula(`=HYPERLINK("${newFolder.getUrl()}","${newFolder.getUrl()}")`); } // 通用函数:提取所有单元格中的Google文件ID(支持逗号分隔的多个链接) function extractAllFileIds(dataRow) { const fileIds = []; // 遍历整行的每个单元格 dataRow.forEach(cellValue => { if (typeof cellValue === 'string' && cellValue.trim() !== '') { // 拆分逗号分隔的多个链接 const links = cellValue.split(',').map(link => link.trim()); links.forEach(link => { // 匹配Google文件ID(25位以上的字母数字连字符组合) const match = link.match(/[-\w]{25,}/); if (match) { fileIds.push(match[0]); } }); } }); // 去重,避免重复移动同一文件 return [...new Set(fileIds)]; }
关键修改说明
- 简化数据复制:
filter函数中直接通过扩展运算符复制整行数据,替代原脚本中手动逐个push到100的冗余代码 - 全列超链接提取:新增
extractAllFileIds函数,遍历整行所有单元格,自动拆分逗号分隔的多链接,提取所有有效的Google文件ID - 批量文件处理:在
createFolder中批量遍历所有提取到的ID,移动文件时增加异常捕获,避免单个文件出错导致整个流程中断 - 移除硬编码依赖:不再依赖固定的列索引(如原脚本的第20列),适配任意数量的表单列
- 文件ID去重:自动去除重复的文件ID,避免同一文件被多次移动
注意:请将代码中的
YOUR_PARENT_FOLDER_ID替换为你实际的父文件夹ID(从Google Drive文件夹链接中获取)
内容的提问来源于stack exchange,提问作者Chris Brown
相关产品推荐
相关产品推荐

