Google 表格 - 设置背景颜色

Google Sheets - Setting background color

我正在编写一个以前由其他开发人员持有的应用程序。经过一定处理后,他想用值填充一个 Google Sheets 文件。在他开始开发之前,他就走了,留给我理解 google-api-client-php 库的任务。

我设法插入值(这对我来说是一大步)但我想为某些单元格添加背景颜色。我没有找到任何方法来实现这个...

现在,这就是我插入值的方式:

class Sheet {
    public function __construct($client) {
        $this->service = new \Google_Service_Sheets($client);
    }
    public function write($line, $newValues, $startColumn)
    {
        $values = new \Google_Service_Sheets_ValueRange();
        $values->setValues([    $newValues  ]); 

        $this->service->spreadsheets_values->update($this->id, $range, $values, ['valueInputOption' => 'USER_ENTERED']);
    }
}

我想创建一个 colorLine() 函数。

这是我的第一次尝试:

 public function colorLine($line, $r, $g, $b, $a = 1) {
   $myRange = [
        'sheetId' => 1,
        'startRowIndex' => $line,
        'endRowIndex' => $line,
        'startColumnIndex' => 0,
        'endColumnIndex' => 1000,
    ];

    $requests = [
        new \Google_Service_Sheets_Request([
            'addConditionalFormatRule' => [
                'rule' => [
                    'ranges' => [ $myRange ],
                    'booleanRule' => [
                        'condition' => [
                            'type' => 'CUSTOM_FORMULA',
                            'values' => [ [ 'userEnteredValue' => '=1' ] ]
                        ],
                        'format' => [
                            'backgroundColor' => [ 'red' => $r, 'green' => $g, 'blue' => $b ]
                        ]
                    ]
                ],
                'index' => 1
            ]
        ])
    ];

    $batchUpdateRequest = new \Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
        'requests' => $requests
    ]);
    $response = $this->service->spreadsheets->batchUpdate($this->id,
        $batchUpdateRequest);
}

首先,我什至真的不明白我写的东西...另外,它说的是"Invalid requests[0].addConditionalFormatRule: No grid with id: 1",但它并没有那么糟糕,我不不认为它会完成我正在寻找的东西。

我认为它会创建一个 "conditional format",但我只想要一个背景...这个 API 对于简单的应用程序来说看起来非常复杂...

无论如何!如果有人能帮助我,我将不胜感激!

如果你真的不在乎解释,直接去最后一节:)

这可能不是最好的解决方案,但至少有效。

解决方案的解释(TL,NR):

我们需要什么?

  1. 我们想要的 RGBa 值
  2. 范围(sheetId,行索引,列 指数)
  3. 电子表格 ID。

现在,我们应该如何进行?好吧,以前的源代码 并没有那么糟糕 实际上...只需要稍微更改一下 :

  • 我们不想创建 ConditionalFormats,而是要更新单元格,所以我们应该使用“repeatCell”请求(我将解释为什么“ repeatCell" 而不是 "updateCell")
  • In this request,我们可以有 3 个参数:
    • 掩码字段(限制更新),
    • 范围
    • 单元格。那是 CellData object that can contain a "userEnteredFormat" (CellFormat) 现在 您可以访问背景颜色 属性!!

开始编码:

好的,让我们定义范围:

"start" 和 "end" 不能在同一位置(所以 -1 在开头,它只会改变一行)

    $myRange = [
        'sheetId' => $sheetId,
        'startRowIndex' => $line-1,
        'endRowIndex' => $line,
        'startColumnIndex' => 0,
        'endColumnIndex' => 17,
    ];

现在让我们定义颜色(每个分量必须介于 0 和 1 之间):

    $format = [
        "backgroundColor" => [
            "red" => $r,
            "green" => $g,
            "blue" => $b,
            "alpha" => $a,
        ],
    ];

就是这样,我们快准备好了!

我们只需要告诉服务我们想要一个“repeatCell”请求。不要忘记 "fields" 参数。如果不限制更新,单元格的所有数据都会改变,包括文字!在本例中,"fields" 的路径从 "cell" 开始,因此我们只需键入 'userEnteredFormat.backgroundColor'。然后使用之前创建的 $format 变量。

    $requests = [
        new \Google_Service_Sheets_Request([
            'repeatCell' => [
                'fields' => 'userEnteredFormat.backgroundColor',
                'range' => $myRange,
                'cell' => [
                    'userEnteredFormat' => $format,
                ],
            ],
        ])
    ];

好的!完毕。现在将这个(或这些)请求包含在批处理中:

    $batchUpdateRequest = new \Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
        'requests' => $requests
    ]);

最后,使用服务发送请求,包括电子表格 ID($this->id 在我的例子中)。

    $response = $this->service->spreadsheets->batchUpdate($this->id,
        $batchUpdateRequest);

完整的解决方案:

感谢阅读,这就是您的解决方案:

public function colorLine($line, $r, $g, $b, $a = 1.0, $worksheetName = null)
{
    if($r > 1) $r = Tools::rescale($r, 0, 255, 0, 1);
    if($g > 1) $g = Tools::rescale($g, 0, 255, 0, 1);
    if($b > 1) $b = Tools::rescale($b, 0, 255, 0, 1);
    if($a > 1) $a = Tools::rescale($a, 0, 255, 0, 1);

    $worksheetName = ($worksheetName ? : $this->defaultWorksheet);
    $sheetId = $this->getWorksheetId($worksheetName);

    $myRange = [
        'sheetId' => $sheetId,
        'startRowIndex' => $line-1,
        'endRowIndex' => $line,
        'startColumnIndex' => 0,
        'endColumnIndex' => 17,
    ];
    $format = [
        "backgroundColor" => [
            "red" => $r,
            "green" => $g,
            "blue" => $b,
            "alpha" => $a,
        ],
    ];

    $requests = [
        new \Google_Service_Sheets_Request([
            'repeatCell' => [
                'fields' => 'userEnteredFormat.backgroundColor',
                'range' => $myRange,
                'cell' => [
                    'userEnteredFormat' => $format,
                ],
            ],
        ])
    ];

    $batchUpdateRequest = new \Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
        'requests' => $requests
    ]);
    $response = $this->service->spreadsheets->batchUpdate($this->id,
        $batchUpdateRequest);
}

终于,我找到了一个可行的解决方案。

$sheetId = $service->spreadsheets->get($spreadsheetId, ['ranges' => 'worksheetname']);

//For range, end rows and end columns are not considered for updating. Index start from 0
//Here we are setting range for A3:E5 grid
$range = new Google_Service_Sheets_GridRange();
$range->setSheetId($sheetId->sheets[0]->properties->sheetId);
$range->setEndRowIndex(2);
$range->setEndRowIndex(5);
$range->setStartColumnIndex(0);
$range->setEndColumnIndex(5);

//set the color value in RGBA
$color = new Google_Service_Sheets_Color();
$color->setRed($red / 255);
$color->setGreen($green / 255);
$color->setBlue($blue / 255);
$color->setAlpha($alpha);

//cellFormat is used to set different properties of a cell
$cellFormat = new Google_Service_Sheets_CellFormat();

//textFormat is used to set different text formats like Bold
$textFormat = new Google_Service_Sheets_TextFormat();
$textFormat->setBold(true);
$cellFormat->setBackgroundColor($color);
$cellFormat->setTextFormat($textFormat);

//New cell class. Assign the cellFormat to it
$cell = new Google_Service_Sheets_CellData();
$cell->setUserEnteredFormat($cellFormat);

//repeatCell request is used to assign requests to range of cells
$repeatCell = new Google_Service_Sheets_RepeatCellRequest();
$repeatCell->setRange($range);

//Fields is used to specify which properties of a cell to update
//Here we are updating two properties. So both are specified and seperated by comma ,
$repeatCell->setFields('userEnteredFormat.textFormat.bold,userEnteredFormat.backgroundColor');

//Set repeatCellrequest to the requests class
$requests = new Google_Service_Sheets_Request();
$requests->setRepeatCell($repeatCell);

//requests are set to batchupdatespreadsheetrequest class
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
$batchUpdateRequest->setRequests($requests);

//Finally batchUpdate is called to update the format of cells
$response = $service->spreadsheets->batchUpdate($spreadsheetId, $batchUpdateRequest, []);

For more detailed video