Google Sheets v4 API PHP批量更新指定单元格报错如何解决?
问题原因
你混淆了Google Sheets API的两类批量操作接口:
spreadsheets->batchUpdate接口配套Google_Service_Sheets_BatchUpdateSpreadsheetRequest对象,仅用于修改表格结构(增删工作表、调整格式、合并单元格等),不支持值更新相关的valueInputOption、data参数,这是你报错的直接原因。- 批量更新多个不连续单元格的值,需要使用
spreadsheets_values->batchUpdate接口,配套Google_Service_Sheets_BatchUpdateValuesRequest对象。
正确实现代码
// 构造待更新的单元格数据 $data = []; // 2020工作表B92赋值 array_push( $data, new Google_Service_Sheets_ValueRange([ 'range' => '2020!B92', 'values' => [["updatetest2"]] ]) ); // 2020工作表F92赋值 array_push( $data, new Google_Service_Sheets_ValueRange([ 'range' => '2020!F92', 'values' => [["updatetest6"]] ]) ); // 2020工作表G92赋值 array_push( $data, new Google_Service_Sheets_ValueRange([ 'range' => '2020!G92', 'values' => [["updatetest7"]] ]) ); // 实例化值批量更新请求对象 $body = new Google_Service_Sheets_BatchUpdateValuesRequest([ "valueInputOption" => "RAW", "data" => $data ]); // 调用值批量更新接口 $result = $service->spreadsheets_values->batchUpdate($spreadsheetId, $body);
注意事项
- 所有range参数必须携带工作表名称(示例中为
2020!前缀),否则会默认操作表格的第一个工作表 - 单个单元格赋值时,values参数必须保持二维数组结构,外层对应行、内层对应列,格式固定为
[["你的值"]] - 该方案仅发起1次API请求,符合你避免多次调用接口的需求
内容的提问来源于stack exchange,提问作者user11092881
相关产品推荐
相关产品推荐

