使用Google Apps Script批量更新Google Docs时遇404错误
问题分析与修复方案
你的404错误根源有两个核心问题:
- 调用Docs API的
batchUpdate时,BatchRequest的batchPath误用了Drive的路径batch/drive/v3,需替换为Docs API对应的batch/docs/v1 - Docs API的
batchUpdate请求体格式错误:你把两个replaceAllText操作塞在同一个对象里,既会导致第二个替换规则覆盖第一个,也不符合API的结构要求——正确格式是将每个替换操作放在requests数组中
修正后的完整代码
const LIST = SpreadsheetApp.getActiveSpreadsheet() .getSheetByName('1') .getDataRange() .getValues() .filter(f => f[0] != "") .map(f => [f[0], f[1]]); function Creator() { var requests = LIST.map(([b1, a2]) => ({ method: "POST", endpoint: `https://www.googleapis.com/drive/v3/files/1IzwefpoJOksTyBo0CaGcsaG9L_jrZW6Vuw4lGqC07_Y/copy`, requestBody: { parents: ["1qI-T2m1sL_I69wc7EAOJr3ZK3233X5qX"], name: `Договор № ${b1} с ${a2}` } })); var res = BatchRequest.EDo({ batchPath: "batch/drive/v3", requests: requests, }); console.log(res); batchUpdate(res); } function batchUpdate(res) { var IDS = res.map(item => item.id); var requests = support_lib.concatArrays(LIST,IDS).map(([num, name, id]) => ({ method: "POST", endpoint: `https://docs.googleapis.com/v1/documents/${id}:batchUpdate`, requestBody: { requests: [ { replaceAllText: { replaceText: num, containsText: { text: "<номер>", matchCase: true } } }, { replaceAllText: { replaceText: name, containsText: { text: "<фио>", matchCase: true } } } ] } })); var response = BatchRequest.EDo({ batchPath: "batch/docs/v1", // 替换为Docs API的批量请求路径 requests: requests, }); console.log(JSON.stringify(response, null, 2)); }
关键修改说明
- 批量请求路径修正:将
batchUpdate函数中BatchRequest.EDo的batchPath改为batch/docs/v1,匹配Docs API的批量请求规则 - 请求体结构修正:每个文档的更新请求体中,用
requests数组包裹两个独立的replaceAllText操作,确保两个替换规则都能生效,同时符合API的参数格式要求
内容的提问来源于stack exchange,提问作者Antonio
相关产品推荐
相关产品推荐

