You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Google Apps Script批量转换迁移文件并删除原文件求助

Google Apps Script批量转换Excel/CSV到Sheets并处理文件(解决6分钟超时)

问题背景

需要实现以下功能:

  • 批量将.xlsx、.xls、.csv格式文件转换为Google Sheets
  • 转换后的文件移至指定Drive文件夹
  • 删除源文件夹中的原文件
    当前脚本因处理文件过多触发6分钟执行限制,需通过批处理方式优化。

优化后的脚本

// 配置参数:替换为你的源文件夹ID和目标文件夹ID
const SOURCE_FOLDER_ID = "你的源文件夹ID";
const DEST_FOLDER_ID = "你的目标文件夹ID";
// 每次批处理的文件数量,可根据文件大小调整(大文件设小,小文件设大)
const BATCH_SIZE = 5;

function startConversion() {
  // 初始化处理进度,清除上次残留的令牌
  PropertiesService.getScriptProperties().setProperty("nextFileToken", null);
  processBatch();
}

function processBatch() {
  const props = PropertiesService.getScriptProperties();
  const nextToken = props.getProperty("nextFileToken");
  
  // 获取源文件夹中的待处理文件(直接过滤Excel和CSV)
  const folder = DriveApp.getFolderById(SOURCE_FOLDER_ID);
  let files;
  if (nextToken) {
    files = folder.searchFiles('title contains ".xlsx" or title contains ".xls" or title contains ".csv"', nextToken);
  } else {
    files = folder.searchFiles('title contains ".xlsx" or title contains ".xls" or title contains ".csv"');
  }

  let processedCount = 0;
  while (files.hasNext() && processedCount < BATCH_SIZE) {
    const xFile = files.next();
    const fileName = xFile.getName();
    
    // 转换文件为Google Sheets并指定目标文件夹
    const blob = xFile.getBlob();
    Drive.Files.insert(
      { title: fileName.replace(/\.(xlsx|xls|csv)$/i, "_converted"), parents: [{ id: DEST_FOLDER_ID }] },
      blob,
      { convert: true }
    );
    
    // 删除源文件
    Drive.Files.remove(xFile.getId());
    processedCount++;
  }

  // 检查是否还有未处理文件,设置下一批触发
  if (files.hasNext()) {
    const newToken = files.getContinuationToken();
    props.setProperty("nextFileToken", newToken);
    // 1分钟后自动触发下一批,避免触发频率限制
    ScriptApp.newTrigger("processBatch")
      .timeBased()
      .after(60000)
      .create();
  } else {
    // 处理完成,清除进度记录
    props.deleteProperty("nextFileToken");
    // 可选:添加邮件通知,替换为你的邮箱
    // MailApp.sendEmail("你的邮箱地址", "文件转换完成", "所有待处理文件已完成转换与清理");
  }
}

// 可选:在关联的Google Sheets中添加菜单,方便手动触发
function onOpen() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu("文件转换工具")
    .addItem("开始批量转换", "startConversion")
    .addToUi();
}

脚本说明

  • 批处理控制:每次仅处理指定数量的文件,避免单次执行超过6分钟限制
  • 进度续传:用PropertiesService存储文件搜索的续传令牌,确保下次处理从上次中断位置继续,不会重复处理
  • 自动触发:每批处理完成后,1分钟后自动启动下一批,直到所有文件处理完毕
  • 高效过滤:直接在文件搜索阶段筛选目标格式,减少循环内的判断逻辑
  • 命名规范:自动替换原文件后缀为_converted,避免文件名冗余

使用步骤

  1. 打开Google Apps Script编辑器(通过任意Google Sheets的「扩展程序」→「Apps Script」进入)
  2. 替换脚本中SOURCE_FOLDER_ID和DEST_FOLDER_ID为你的实际文件夹ID
  3. 根据文件大小调整BATCH_SIZE(大文件可设为2-3,小文件可设为10)
  4. 点击「运行」→「startConversion」,首次运行需完成权限授权
  5. (可选)添加菜单后,可直接在关联的Sheets中通过菜单触发转换

内容的提问来源于stack exchange,提问作者Filip Urbanec

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 19:43:31