使用Google Drive API更新表格时JSON被转CSV的问题排查
解决Google Sheets API更新时JSON被转为CSV的问题
核心问题
你误用了Google Drive的文件内容更新接口,而非Sheets API专门的批量更新接口。Drive接口会把请求体当作文件纯文本内容,默认按CSV规则解析,导致JSON被拆分成单元格。
正确解决方案
使用Sheets API的
batchUpdate端点
不要调用Drive的files/update,改用Sheets API的专用更新接口:POST https://sheets.googleapis.com/v4/spreadsheets/{SPREADSHEET_ID}:batchUpdate替换
{SPREADSHEET_ID}为你的表格ID。设置正确的请求头
- 必须指定
Content-Type: application/json(这是API请求的内容类型,和Drive文件的MIME类型application/vnd.google-apps.spreadsheet无关) - 带上授权头:
Authorization: Bearer {你的访问令牌}
- 必须指定
构造合规的JSON请求体
按照Sheets API的格式编写请求体,包含要执行的更新操作(比如设置单元格值、样式)。示例:{ "requests": [ { "updateCells": { "range": { "sheetId": 0, // 目标工作表ID(可在表格URL中找到) "startRowIndex": 0, "endRowIndex": 1, "startColumnIndex": 0, "endColumnIndex": 2 }, "rows": [ { "values": [ { "userEnteredValue": { "stringValue": "key1" }, "userEnteredFormat": { "textFormat": { "bold": true } } }, { "userEnteredValue": { "stringValue": "value1" }, "userEnteredFormat": { "backgroundColor": { "red": 0.8, "green": 0.8, "blue": 0.8 } } } ] } ], "fields": "userEnteredValue,userEnteredFormat(textFormat,backgroundColor)" } } ] }requests数组可包含多个操作(比如同时更新多个单元格区域、设置格式)fields指定要更新的属性,避免不必要的字段覆盖
避免无用操作
- 不需要使用multipart请求,
batchUpdate接口仅接受纯JSON请求体 - 不要把JSON当作文件内容上传,Sheets API的更新是通过结构化JSON指令实现,而非替换文件内容
- 不需要使用multipart请求,
内容的提问来源于stack exchange,提问作者RandomDeveloper11
相关产品推荐
相关产品推荐

