如何用Google Apps Script批量自动导出Google Docs为Markdown?
如何用Google Apps Script批量将Google Docs导出为Markdown?
可以通过Google Apps Script调用Google Drive的导出接口,自动化Google Docs的原生Markdown导出功能,还能批量处理文件夹(含子文件夹)内的所有文档。
实现思路
- 遍历目标文件夹及子文件夹,筛选出所有Google Docs文件(MIME类型为
application/vnd.google-apps.document) - 对每个文档调用Drive API的导出接口,指定
text/markdown作为导出格式,获取原生Markdown内容 - 在对应路径下创建同名
.md文件,完整保留原文件夹结构
示例代码
function exportDocsToMarkdown() { const sourceFolderId = "你的源文件夹ID"; // 替换为目标文件夹的ID const sourceFolder = DriveApp.getFolderById(sourceFolderId); // 递归处理文件夹及子文件夹 processFolder(sourceFolder, sourceFolder); } function processFolder(currentFolder, rootFolder) { // 获取当前文件夹下的所有Google Docs文件 const docFiles = currentFolder.getFilesByType(MimeType.GOOGLE_DOCS); // 逐个导出为Markdown while (docFiles.hasNext()) { const doc = docFiles.next(); const docId = doc.getId(); const mdFileName = doc.getName().replace(/\.[^/.]+$/, "") + ".md"; // 构建目标文件夹路径,保留原结构 const relativePath = currentFolder.getUrl().replace(rootFolder.getUrl(), "").split("/").filter(part => part); let targetFolder = rootFolder; relativePath.forEach(folderName => { let existingFolder = targetFolder.getFoldersByName(folderName); targetFolder = existingFolder.hasNext() ? existingFolder.next() : targetFolder.createFolder(folderName); }); // 调用Drive API导出Markdown const exportUrl = `https://www.googleapis.com/drive/v3/files/${docId}/export?mimeType=text/markdown`; const fetchOptions = { headers: { Authorization: `Bearer ${ScriptApp.getOAuthToken()}` } }; try { const response = UrlFetchApp.fetch(exportUrl, fetchOptions); targetFolder.createFile(mdFileName, response.getContentText(), MimeType.PLAIN_TEXT); console.log(`导出完成: ${doc.getName()}`); } catch (error) { console.error(`导出失败 ${doc.getName()}: ${error.message}`); } } // 递归处理子文件夹 const subFolders = currentFolder.getFolders(); while (subFolders.hasNext()) { processFolder(subFolders.next(), rootFolder); } }
使用步骤
- 打开Google Apps Script编辑器(Google Drive → 新建 → 更多 → Google Apps Script)
- 粘贴代码,将
sourceFolderId替换为你要处理的文件夹ID - 启用Drive API:编辑器内点击「资源」→「高级Google服务」,找到「Drive API」并开启
- 运行
exportDocsToMarkdown函数,首次运行需完成授权流程 - 脚本执行完成后,所有Google Docs会以Markdown格式导出到原文件夹结构中
注意事项
- 导出的Markdown格式与Google Docs原生导出效果一致,支持标题、列表、链接等基础格式
- 处理大量文件时,建议分批次执行,避免脚本超时
- 确保账号有足够的Drive存储空间存放导出文件
更新:
已基于该方案开发完成完整工具,支持导出任意Google Drive文件夹并保留子文件夹结构,可将Google Docs转换为Markdown或PDF等格式,工具已开源供使用。
内容的提问来源于stack exchange,提问作者Vladimirzb
相关产品推荐
相关产品推荐

