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

如何使用Google Apps Script导入ICS文件?支持多源多文件导入

嘿,我之前刚好折腾过用Google Apps Script导入ICS文件的需求,不管是从Google Drive批量导入,还是从本地电脑上传导入,都有可行的方案,下面给你详细拆解下~

用Google Apps Script导入ICS文件到Google日历

先提前说下:不管哪种方式,第一次运行脚本时都需要授权访问Google Drive和Google Calendar的权限,按照提示操作就行,授权后才能正常执行。

一、从Google Drive导入单个/多个ICS文件

如果你的ICS文件已经存在Google Drive里,直接写脚本读取文件内容并导入即可,支持单个文件或整个文件夹批量导入。

1. 导入单个ICS文件

替换代码里的日历ID和文件ID,直接运行即可:

function importSingleICSFromDrive() {
  // 替换成你的目标日历ID(在日历设置的「集成日历」里能找到)
  const targetCalendarId = "your-calendar-id@group.calendar.google.com";
  // 替换成Drive中ICS文件的ID(文件URL里的那串字符)
  const icsFileId = "your-ics-file-id";

  try {
    // 获取Drive中的ICS文件
    const icsFile = DriveApp.getFileById(icsFileId);
    // 读取文件内容为文本格式
    const icalText = icsFile.getBlob().getDataAsString();
    // 获取目标日历对象
    const calendar = CalendarApp.getCalendarById(targetCalendarId);
    
    // 自动解析ICS并导入所有事件,返回事件数组
    const importedEvents = calendar.createEventFromIcal(icalText);
    
    // 弹出成功提示
    SpreadsheetApp.getUi().alert(`导入成功!共添加了${importedEvents.length}个事件`);
    console.log(`已成功导入 ${importedEvents.length} 个事件`);
  } catch (error) {
    console.error("导入失败:", error);
    SpreadsheetApp.getUi().alert(`导入出错:${error.message}`);
  }
}

2. 批量导入文件夹内的所有ICS文件

如果Drive里有一堆ICS文件存在同一个文件夹,可以用这段脚本批量处理:

function importBatchICSFromDriveFolder() {
  const targetCalendarId = "your-calendar-id@group.calendar.google.com";
  // 替换成存放ICS文件的文件夹ID
  const folderId = "your-folder-id";

  try {
    const folder = DriveApp.getFolderById(folderId);
    // 筛选出文件夹内的所有ICS文件
    const icsFiles = folder.getFilesByType(MimeType.CALENDAR);
    let totalImported = 0;

    // 遍历每个文件导入
    while (icsFiles.hasNext()) {
      const icsFile = icsFiles.next();
      const icalText = icsFile.getBlob().getDataAsString();
      const calendar = CalendarApp.getCalendarById(targetCalendarId);
      
      const events = calendar.createEventFromIcal(icalText);
      totalImported += events.length;
      console.log(`已导入文件「${icsFile.getName()}」中的 ${events.length} 个事件`);
    }

    SpreadsheetApp.getUi().alert(`批量导入完成!共添加了${totalImported}个事件`);
  } catch (error) {
    console.error("批量导入失败:", error);
    SpreadsheetApp.getUi().alert(`批量导入出错:${error.message}`);
  }
}

二、从本地电脑导入多个ICS文件

因为脚本没法直接访问本地文件,我们可以做一个简单的Web上传界面,让用户选择本地的多个ICS文件,然后后端自动导入到日历。

步骤1:创建上传界面

在脚本编辑器里新建一个HTML文件(命名为UploadForm),复制以下代码:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <style>
      body { padding: 20px; font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; }
      .upload-area { margin: 20px 0; }
      button { padding: 10px 20px; background: #4285F4; color: white; border: none; border-radius: 4px; cursor: pointer; }
      button:hover { background: #3367D6; }
      .result-item { margin: 10px 0; padding: 8px; border-radius: 4px; }
      .success { background: #E8F5E9; color: #2E7D32; }
      .error { background: #FFEBEE; color: #C62828; }
    </style>
  </head>
  <body>
    <h2>ICS文件导入工具</h2>
    <div class="upload-area">
      <input type="file" id="icsFiles" multiple accept=".ics">
      <br><br>
      <button onclick="startImport()">开始导入</button>
    </div>
    <div id="resultContainer"></div>

    <script>
      function startImport() {
        const files = document.getElementById('icsFiles').files;
        const resultContainer = document.getElementById('resultContainer');
        
        if (files.length === 0) {
          resultContainer.innerHTML = '<p class="result-item error">请选择至少一个ICS文件!</p>';
          return;
        }

        resultContainer.innerHTML = '<p>正在处理,请稍候...</p>';
        let processPromises = [];

        // 逐个处理上传的文件
        for (let i = 0; i < files.length; i++) {
          const file = files[i];
          const formData = new FormData();
          formData.append('file', file);

          processPromises.push(
            google.script.run
              .withSuccessHandler(response => {
                if (response.success) {
                  resultContainer.innerHTML += `<p class="result-item success">✅ ${file.name}:成功导入${response.count}个事件</p>`;
                } else {
                  resultContainer.innerHTML += `<p class="result-item error">❌ ${file.name}:导入失败 - ${response.error}</p>`;
                }
              })
              .withFailureHandler(error => {
                resultContainer.innerHTML += `<p class="result-item error">❌ ${file.name}:处理出错 - ${error.message}</p>`;
              })
              .handleICSImport(formData)
          );
        }

        // 所有文件处理完成后提示
        Promise.all(processPromises).then(() => {
          resultContainer.innerHTML += '<p>所有文件处理完毕!</p>';
        });
      }
    </script>
  </body>
</html>

步骤2:编写后端处理脚本

在Code.gs文件里替换成以下代码:

// 显示上传界面
function doGet() {
  return HtmlService.createHtmlOutputFromFile('UploadForm')
    .setTitle('ICS文件导入工具');
}

// 处理上传的ICS文件
function handleICSImport(formData) {
  try {
    const targetCalendarId = "your-calendar-id@group.calendar.google.com";
    const file = formData.file;
    const icalText = file.getDataAsString();
    const calendar = CalendarApp.getCalendarById(targetCalendarId);
    
    const importedEvents = calendar.createEventFromIcal(icalText);
    
    return {
      success: true,
      count: importedEvents.length
    };
  } catch (error) {
    return {
      success: false,
      error: error.message
    };
  }
}

步骤3:部署Web应用

点击脚本编辑器右上角的「部署」→「新部署」:

  1. 选择类型为「Web应用」
  2. 执行权限选「我」
  3. 访问权限根据需求选(自己用的话选「仅限我自己」更安全)
  4. 点击部署,复制生成的URL,打开就能使用上传界面了

几个注意点

  • 日历ID获取:打开Google日历,找到目标日历→点击「三个点」→「设置和共享」→「集成日历」里的「日历ID」
  • 若遇到超时问题(比如导入超大ICS文件),可以把导入逻辑拆分成小批次,用时间触发器异步处理
  • 确保ICS文件是标准格式,自定义的非标准ICS可能会解析失败,建议先测试单个文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:56:24