我正在尝试通过PHP中的Google Sheets API更改范围颜色。
我做了大约一个小时的研究。下面的代码是我所掌握的。
$requests = [
// Change the spreadsheet's title.
new Google_Service_Sheets_Request([
'updateSpreadsheetProperties' => [
'properties' => [
'title' => "The Title"
],
'fields' => 'title'
],
'UpdateCellsRequest' => [
'properties' => [
'range' => "Sheet1!A1",
'backgroundColor' => "#000"
],
'fields' => ''
]
])
];
// Add additional requests (operations) ...
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
'requests' => $requests
]);
$response = $GoogleSheetsAPIHandler->sheets->spreadsheets->batchUpdate("SHEETID", $batchUpdateRequest);
print_r($response);
如果我取出这个:
'UpdateCellsRequest' => [
'properties' => [
'range' => "Sheet1!A1",
'backgroundColor' => "#000"
],
'fields' => ''
]
然后,代码将更新图纸标题。然而,我似乎无法更新范围颜色。
如有任何建议,我们将不胜感激!
我相信你的目标和情况如下。
- 您想要使用php的googleapi来更改单元格的背景颜色
- 您已经能够使用Sheets API获取和放置Google电子表格的值
修改点:
- 当您想要使用Sheets API的batchUpdate方法时,请将每个请求放在
requests
数组的每个元素中 - 我认为脚本中UpdateCellsRequest的请求主体不正确。
- 根据您的
I'm trying to change a ranges colour via the Google Sheets API in PHP.
问题,当您想用一种颜色更改多个单元格的背景颜色时,我认为RepeatCellRequest可能是合适的
- 根据您的
在这个答案中,我想提出一个修改后的脚本,用于使用一种颜色更改几个单元格。当您的脚本被修改时,它变成如下。
修改的脚本:
在使用之前,请设置纸张ID。
$requests = [
new Google_Service_Sheets_Request([
'updateSpreadsheetProperties' => [
'properties' => [
'title' => "The Title"
],
'fields' => 'title'
]
]),
new Google_Service_Sheets_Request([
'repeatCell' => [
'cell' => [
'userEnteredFormat' => [
'backgroundColor' => [
'red' => 1,
'green' => 0,
'blue' => 0
]
]
],
'range' => [
'sheetId' => $sheetId, // <--- Please set the sheet ID.
'startRowIndex' => 0,
'endRowIndex' => 3,
'startColumnIndex' => 0,
'endColumnIndex' => 2
],
'fields' => 'userEnteredFormat'
]
])
];
当以上请求主体用于Sheets API的批更新方法时,电子表格的标题被改变,单元格的背景颜色"被改变;A1:B3";改为红色。
如果您想使用UpdateCellsRequest,可以使用以下请求正文。在下面的请求体中;A1:B1";分别变为红色和绿色。使用UpdateCellsRequest时,可以更新每个单元格。关于UpdateCellsRequest的详细信息,请查看官方文档。参考
$requests = [ new Google_Service_Sheets_Request([ 'updateCells' => [ 'rows' => array([ 'values' => array( ['userEnteredFormat' => [ 'backgroundColor' => [ 'red' => 1, 'green' => 0, 'blue' => 0 ] ]], ['userEnteredFormat' => [ 'backgroundColor' => [ 'red' => 0, 'green' => 1, 'blue' => 0 ] ]] ) ]), 'range' => [ 'sheetId' => $sheetId, // <--- Please set the sheet ID. 'startRowIndex' => 0, 'startColumnIndex' => 0, ], 'fields' => 'userEnteredFormat' ] ]) ];
参考文献:
- 更新CellsRequest
- RepeatCellRequest