Google表格-设置背景颜色

时间:2018-08-29 14:42:13

标签: php google-api-php-client google-sheets-api

我正在写一个以前由另一个开发人员持有的应用程序。经过某种处理后,他想用值填充Google表格文件。在他开始开发之前,他已经离开了,只剩下让我去了解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);
}

首先,我什至不真正了解我写的内容...而且,它的意思是“无效的请求[0] .addConditionalFormatRule:ID为1的无网格”,但是还不错,我认为它不会满足我的要求。

我认为它会创建“条件格式”,但是我只需要一个背景...对于简单的应用程序,此API看起来非常复杂...

无论如何!如果有人可以帮助我,我将非常感激!

2 个答案:

答案 0 :(得分:0)

如果您真的不关心解释,请转到最后一节:)

那可能不是最好的解决方案,但至少可以奏效。

解决方案的说明(TL,NR):

我们需要什么?

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

现在,我们应该如何进行?嗯,以前的源代码实际上并不是那么糟糕……只需要对其稍作更改即可:

  • 我们不想创建ConditionalFormats,而是要更新单元格,因此我们应该使用“ repeatCell ”请求(我将解释为什么使用“ repeatCell ” “ updateCell ”)
  • In this request,我们可以有3个参数:
    • 掩码字段(限制更新)
    • 范围
    • 单元格。这是一个CellData object,可以包含“ userEnteredFormat”(CellFormat现在,您可以访问backgroundColor属性!

开始编码:

好,让我们定义范围:

您不能在同一位置出现“开始”和“结束”(因此,在开始处有-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 ”请求。不要忘记“字段”参数。如果您不限制更新,则单元格的所有数据都会更改,包括文本!在这种情况下,“字段”的路径从“单元格”开始,因此我们只需键入'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);
}

答案 1 :(得分:0)

最后,我找到了一个可行的解决方案。

$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