寻求Salesforce集成场景下单次调用的Google Sheets多表多行Upsert API
实现单次Google Sheets API调用完成多表多行Upsert
Google Sheets API本身没有原生的单端点多表Upsert接口,但可以通过spreadsheets.batchUpdate接口实现单次调用处理多工作表的多行增改操作,以下是具体方案:
核心思路
利用spreadsheets.batchUpdate的批量操作能力,在单次请求中包含多个针对不同工作表的更新/插入操作,以此模拟多表Upsert的效果。
具体步骤
预查询现有数据(Upsert前置)
要实现Upsert(更新已有行、插入新行),首先需要确定目标工作表中哪些行是已存在的。可以通过spreadsheets.values.get接口批量查询多个工作表的指定范围数据(比如主键列),对比本地数据后,区分出需要更新的行和需要插入的行。构造Batch Update请求体
在请求的requests数组中,为每个工作表的每个操作添加对应的请求对象:- 更新现有行:使用
UpdateCellsRequest,指定目标工作表ID、单元格范围和要更新的值,同时设置userEnteredValue来填充数据。 - 插入新行:使用
AppendCellsRequest,指定目标工作表ID和要插入的单元格数据,设置fields为userEnteredValue确保值被写入。
示例请求体(JSON格式):
{ "requests": [ // 更新Sheet1的第2行数据 { "updateCells": { "range": { "sheetId": 123456, "startRowIndex": 1, "endRowIndex": 2, "startColumnIndex": 0, "endColumnIndex": 3 }, "rows": [ { "values": [ {"userEnteredValue": {"stringValue": "ID001"}}, {"userEnteredValue": {"stringValue": "Updated Name"}}, {"userEnteredValue": {"numberValue": 99}} ] } ], "fields": "userEnteredValue" } }, // 向Sheet2插入新行 { "appendCells": { "sheetId": 789012, "rows": [ { "values": [ {"userEnteredValue": {"stringValue": "ID002"}}, {"userEnteredValue": {"stringValue": "New Entry"}}, {"userEnteredValue": {"numberValue": 50}} ] } ], "fields": "userEnteredValue" } } ] }- 更新现有行:使用
发送请求
调用spreadsheets.batchUpdate接口,将构造好的请求体发送,即可在单次调用中完成多表的多行增改。
注意事项
- 单个
batchUpdate请求最多包含100个操作,请求体大小不能超过10MB,超出的话需要拆分请求。 - 操作按请求中的顺序执行,并非原子性操作——如果某一个操作失败,后续操作仍会继续执行,需要自行处理错误回滚逻辑。
- 确保你的API授权账号拥有所有目标工作表的编辑权限。
内容的提问来源于stack exchange,提问作者Anurag Singh
相关产品推荐
相关产品推荐

