我正在尝试通过 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 的 googleapis 更改单元格的背景颜色。
- 您已经能够使用 Sheets API 获取和输入 Google 电子表格的值。
修改点:
- 当您想使用Sheets API的batchUpdate方法时,请将每个请求放入
requests
数组的每个元素。 - 我认为您的脚本中 UpdateCellsRequest 的请求正文不正确。
- 根据您的问题
我正在尝试通过 PHP 中的 Google Sheets API 更改范围颜色。
,当您想用一种颜色更改多个单元格的背景颜色时,我认为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 的 batchUpdate 方法时,电子表格的标题会更改,并且单元格“A1:B3”的背景颜色会更改为红色。
如果您想使用 UpdateCellsRequest,则可以使用以下请求正文。在以下请求正文中,单元格“A1:B1”的背景颜色分别更改为红色和绿色。当使用UpdateCellsRequest时,可以更新每个单元格。关于UpdateCellsRequest的详细信息请查看官方文档。 Ref
$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' ] ]) ];
引用文献:
关于php - 使用 Google Sheets API 更改单元格颜色 (PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64852834/