phpgoogle-sheetsgoogle-apigoogle-sheets-api

Google Sheets API - Bolding and Highlighting text


I am using the Google Sheet API. My code is working as expected. Now though, I want to add some bolding, highlighting, etc. I have reviewed other pieces of code but I am not fully understanding how to do this. Thank you!!

$service = new \Google_Service_Sheets($client);
$spreadsheetId = 'xxxxxxx';
$spreadsheet = $service -> spreadsheets -> get($spreadsheetId);
$result = $db -> query("SELECT * from xxxxxx");
$oldref = '1';
if ($result -> num_rows > 0) {
  $rows = array();
  $i = 0;
  while ($row = $result -> fetch_assoc()) {
    $i++;
    if ($oldref != $row['refnumber']) {
  ///////////////////////////////////////////////////
 ////this is where I want to BOLD the $row['refnumber'] value.//////       
 $newRow = [$row['refnumber']];
  array_push($rows, $newRow);       
    }
  
  }
  $valueRange = new \Google_Service_Sheets_ValueRange();
  $valueRange -> setValues($rows);
  $range = 'Sheet1';
  $options = ['valueInputOption' => 'USER_ENTERED'];
  $service -> spreadsheets_values -> update($spreadsheetId, $range, $valueRange, $options);

}

Solution

  • From this is where I want to BOLD the $row['refnumber'] value. in your script, I guessed that you wanted to set the bold to all values of $rows. In this case, how about the following modification?

    In order to change the text format of the cell, "Method: spreadsheets.batchUpdate" is used.

    Modified script:

    Before you use this script, please set $sheetId. In your script, from $range = 'Sheet1';, the sheet ID is the sheet ID of "Sheet1".

    From:

    $service -> spreadsheets_values -> update($spreadsheetId, $range, $valueRange, $options);
    

    To:

    $service -> spreadsheets_values -> update($spreadsheetId, $range, $valueRange, $options);
    
    // --- I added the below script.
    $sheetId = 0; // Please set your sheet ID.
    $startRow = 0;
    $rowLength = count($rows);
    $colLength = count($rows[0]);
    $requests = [new \Google\Service\Sheets\Request([
        "repeatCell" => [
            "cell" => ["userEnteredFormat" => ["textFormat" => ["bold" => true]]],
            "range" => [
                "sheetId" => $sheetId,
                "startRowIndex" => $startRow,
                "endRowIndex" => $startRow + $rowLength,
                "startColumnIndex" => 0,
                "endColumnIndex" => $colLength,
            ],
            "fields" => "userEnteredFormat",
        ],
    ])];
    $req = new \Google\Service\Sheets\BatchUpdateSpreadsheetRequest(["requests" => $requests]);
    $service->spreadsheets->batchUpdate($spreadsheetId, $req);
    

    References: