Home > Mobile >  How to apply cell format using google sheets api v4 in php?
How to apply cell format using google sheets api v4 in php?

Time:10-14

Im new to this API. for example like, how to allign the text? how to set the length of the cell? Thank you in advance.

    $client = getClient();
    $service = new Google_Service_Sheets($client);
    try{

    $values = [["",""];


    $body = new Google_Service_Sheets_ValueRange([
        'values' => $values
    ]);
    $params = [
        'valueInputOption' => 'USER_ENTERED'
    ];
    //executing the request
    $result = $service->spreadsheets_values->update($spreadsheetId, $range,
    $body, $params);
    printf("%d cells updated.\n", $result->getUpdatedCells());
    return $result->getUpdatedCells();
}
catch(Exception $e) {
        // TODO(developer) - handle error appropriately
        echo 'Message: ' .$e->getMessage();
      }
}

this column

CodePudding user response:

From it is the column width that i want to change, and also i want to align the text horizontal direction. For alignment example, i want to align only the table header text to be center., I believe your goal is as follows.

  • You want to reflect the alignment at the 1st row and the column width of all columns.
  • You want to achieve this using googleapis for PHP.
  • You have already been able to get and put values to Spreadsheet using Sheets API.

In this case, how about the following sample script?

Sample script:

$client = getClient(); // This is from your script.

$spreadsheet_id = "###"; // please set Spreadsheet ID.
$sheet_id = "0"; // please set Sheet ID.
$column_width = 200; // Please set the column width you want.
$service = new Google_Service_Sheets($client);

$requests = [
    new \Google\Service\Sheets\Request([
        "repeatCell" => [
            "range" => [
                "sheetId" => $sheet_id,
                "startRowIndex" => 0,
                "endRowIndex" => 1,
            ],
            "cell" => [
                "userEnteredFormat" => ["horizontalAlignment" => "CENTER"],
            ],
            "fields" => "userEnteredFormat.horizontalAlignment",
        ],
    ]),
    new \Google\Service\Sheets\Request([
        "updateDimensionProperties" => [
            "range" => [
                "sheetId" => $sheet_id,
                "startIndex" => 0,
                "dimension" => "COLUMNS",
            ],
            "properties" => ["pixelSize" => $column_width],
            "fields" => "pixelSize",
        ],
    ]),
];
$batchUpdate = new \Google\Service\Sheets\BatchUpdateSpreadsheetRequest(["requests" => $requests]);
$service->spreadsheets->batchUpdate($spreadsheet_id, $batchUpdate);
  • When this script is run, the text alignment at the 1st row is changed to "CENTER" and the column width of all columns is changed to 200 pixels. If you want to change the column width, please modify $column_width.

References:

  • Related