Search code examples
phpgoogle-apigoogle-api-php-clientgoogle-sheets-api

How to merge cells using the PHP version of the Google Sheet API v4


I've succesfully set up my credentials and access following the Quickstart guide & the API v4 documentation.

Everything works great, I successfully tried to:

  • Update the spreadsheet title
  • Read/write values in each cell
  • etc.

However I keep getting the following error while trying to merge some cells:

Fatal error: Uncaught Google_Service_Exception: { "error": { "code": 400, "message": "Invalid JSON payload received. Unknown name \"merge_type\" at 'requests': Cannot find field.\nInvalid JSON payload received. Unknown name \"range\" at 'requests': Cannot find field.", "errors": [ { "message": "Invalid JSON payload received. Unknown name \"merge_type\" at 'requests': Cannot find field.\nInvalid JSON payload received. Unknown name \"range\" at 'requests': Cannot find field.", "domain": "global", "reason": "badRequest" } ], "status": "INVALID_ARGUMENT" } }

Source code:

<?php

include_once(__DIR__.'/vendor/autoload.php');
include_once(__DIR__.'/client.php');

$id_spreadsheet = '12xymzMe8OLbX9vw84'; // My spreadsheet ID (redacted for Stackoverflow)

/* Retrieve the API access */
$service = new Google_Service_Sheets(getClient());

/* Merge header columns */
$range = new Google_Service_Sheets_GridRange();
$range->setStartRowIndex(0);
$range->setEndRowIndex(1);
$range->setStartColumnIndex(1);
$range->setEndColumnIndex(24);
$range->setSheetId(0);

$request = new Google_Service_Sheets_MergeCellsRequest();
$request->setMergeType('MERGE_COLUMNS');
$request->setRange($range);

$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(['requests' => $request]);
$response = $service->spreadsheets->batchUpdate($id_spreadsheet, $batchUpdateRequest);
echo '<pre>', var_export($response, true), '</pre>', "\n";

Solution

  • If you've not resolved this issue, the problem is in the request you are sending, try to set your request in Google_Service_Sheets_BatchUpdateSpreadsheetRequest setRequests method

    $batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
    $batchUpdateRequest->setRequests($request);
    $response = $service->spreadsheets->batchUpdate($id_spreadsheet, $batchUpdateRequest);
    echo '<pre>', var_export($response, true), '</pre>', "\n";