如何用Google Script将带表头表格按每50行拆分导出至Google Drive
解决方案
你的现有代码仅完成了原表格的完整复制与多余工作表清理,并未实现按50行拆分的核心逻辑。以下是修改后的代码,可自动将数据按每50行一组(每组保留相同表头)生成独立表格,并保存到指定Drive文件夹:
function splitAndExportSheets() { const sheetName = "My sheet Name"; // 替换为你的源工作表名称 const folderID = "Folder ID to copy"; // 替换为目标文件夹ID const rowsPerFile = 50; // 每组行数 const destFolder = DriveApp.getFolderById(folderID); const srcSpreadSheet = SpreadsheetApp.getActiveSpreadsheet(); const srcSheet = srcSpreadSheet.getSheetByName(sheetName); // 读取所有数据(包含表头) const allData = srcSheet.getDataRange().getValues(); if (allData.length <= 1) { Browser.msgBox("无数据可拆分"); return; } const header = allData[0]; // 提取表头 const dataRows = allData.slice(1); // 提取除表头外的所有数据行 const totalGroups = Math.ceil(dataRows.length / rowsPerFile); // 计算总组数 for (let i = 0; i < totalGroups; i++) { // 截取当前组的数据行 const startRow = i * rowsPerFile; const endRow = startRow + rowsPerFile; const currentGroup = dataRows.slice(startRow, endRow); // 创建新的空白表格 const newSpreadsheet = SpreadsheetApp.create(`拆分表格_${i+1}_${Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "dd-MM-yyyy hh_mm a")}`); const newSheet = newSpreadsheet.getActiveSheet(); // 写入表头和当前组数据 newSheet.getRange(1, 1, 1, header.length).setValues([header]); newSheet.getRange(2, 1, currentGroup.length, currentGroup[0].length).setValues(currentGroup); // 将新表格移动到目标文件夹(默认在根目录,需要移动) const file = DriveApp.getFileById(newSpreadsheet.getId()); destFolder.addFile(file); DriveApp.getRootFolder().removeFile(file); } Browser.msgBox(`拆分完成!共生成 ${totalGroups} 个表格`); }
关键逻辑说明
- 数据读取与拆分:先提取表头,再将剩余数据按50行一组切割,最后一组不足50行也会自动处理
- 新表格创建:每组数据对应一个新的空白表格,写入表头和分组数据后,从Drive根目录移动到指定文件夹
- 命名区分:新表格名称包含组号和时间戳,避免重名
注意事项
- 首次运行时需授权脚本访问你的Google Drive和Spreadsheet
- 如果源表格数据量极大(如35000行),可能需要分批执行或调整脚本超时设置(可通过
File > Project properties > Script editor settings调整超时时间)
内容的提问来源于stack exchange,提问作者dkrug3r
相关产品推荐
相关产品推荐

