I'm using Google's Client API via Composer (https://packagist.org/packages/google/apiclient) and I have successfully authenticated and received an access token.
I am trying to add a row to a Google sheet in my drive, but I can't find any relevant documentation that specifically addresses PHP.
Here's what I've got so far:
$service = new Google_Service_Sheets($a4e->google); // my authenticated Google client object
$spreadsheetId = "11I1xNv8cHzBGE7uuZtB9fQzbgrz4z7lIaEADfta60nc";
$range = "Sheet1!A1:E";
$valueRange= new Google_Service_Sheets_ValueRange();
$service->spreadsheets_values->update($spreadsheetId,$range,$valueRange);
This returns the following error:
Fatal error: Uncaught exception 'Google_Service_Exception' with message '{ "error": { "code": 400, "message": "Invalid valueInputOption: INPUT_VALUE_OPTION_UNSPECIFIED", "errors": [ { "message": "Invalid valueInputOption: INPUT_VALUE_OPTION_UNSPECIFIED", "domain": "global", "reason": "badRequest" } ], "status": "INVALID_ARGUMENT" } } ' in /usr/share/nginx/vendor/google/apiclient/src/Google/Http/REST.php
I'm stuck as to the format of the "Google_Service_Sheets_ValueRange()" object, and also how to append a row to the end of the sheet, rather than having to specify a particular range.
I would greatly appreciate any help with this issue.
I had the same problem, there is a lack of documentation about this. But I found a solution. Here is a working example:
// ...
// Create the value range Object
$valueRange= new Google_Service_Sheets_ValueRange();
// You need to specify the values you insert
$valueRange->setValues(["values" => ["a", "b"]]); // Add two values
// Then you need to add some configuration
$conf = ["valueInputOption" => "RAW"];
// Update the spreadsheet
$service->spreadsheets_values->update($spreadsheetId, $range, $valueRange, $conf);
I think it's weird syntax, and I did not found clear documentation about it, I just tried some combination and now it works! Not sure it's the right way, hope it could help.
There is a new append method:
(I am using a service account.)
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setSubject($delegated_user);
$client->addScope(Google_Service_Sheets::SPREADSHEETS);
$service = new Google_Service_Sheets($client);
$range = 'Sheet1!A:E';
$values = [
["a", "b", "C", "D", "E"]
];
$body = new Google_Service_Sheets_ValueRange([
'values' => $values
]);
$params = [
'valueInputOption' => "RAW"
];
$result = $service->spreadsheets_values->append($spreadsheet_id, $range, $body, $params);
$client = $this->getClient();
$service = new Google_Service_Sheets($client);
$spreadsheetId = '1bFh8FYeez6c1snPCHZF_olsHOLRqEENJbChLKbE9xg0';
$range = 'A1:S1';
$values = [
['col 1', 'col 2', 'col 3'],
['col 1', 'col 2', 'col 3'],
['col 1', 'col 2', 'col 3']
];
$requestBody = new Google_Service_Sheets_ValueRange(array(
'values' => $values
));
$params = [
'valueInputOption' => 'RAW'
];
print_r($requestBody);
$response = $service->spreadsheets_values->update($spreadsheetId, $range, $requestBody, $params);
Related
I'm new to this API. For example like, how to align 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
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:
Method: spreadsheets.batchUpdate
RepeatCellRequest
UpdateDimensionPropertiesRequest
I have this code which inserts a blank row near the top of a Google Sheet.
But how can I insert data in this row?
$service = new Google_Service_Sheets($client);
$dr = new Google_Service_Sheets_DimensionRange();
$dr->setSheetId(0);//first sheet/tab of spreadsheet file
$dr->setDimension('ROWS');
$dr->setStartIndex(1);
$dr->setEndIndex(2);
$ins = new Google_Service_Sheets_InsertDimensionRequest();
$ins->setRange($dr);
$ins->setInheritFromBefore(false);
$ssr = new Google_Service_Sheets_Request();
$ssr->setInsertDimension($ins);
$busr = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
$busr->setRequests([$ssr]);
$response = $service->spreadsheets->batchUpdate($spreadsheetId, $busr, []);
Resolved the issue with the following code:
$request = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
'requests' => [
'insertDimension' => [
'range' => [
'startIndex' => 1,
'endIndex' => count($array)+1,
'dimension' => 'ROWS',
'sheetId' => 0
]
]
]
]);
$result = $service->spreadsheets->batchUpdate($spreadsheetId, $request);
$range = "2020!A92:L92";
$valueRange= new Google_Service_Sheets_ValueRange();
$valueRange->setValues(["values" => ["updatetest1", "updatetest2", "updatetest3", "updatetest4", "updatetest5", "updatetest6", "updatetest7", "updatetest8", "updatetest9", "updatetest10", "updatetest11", "updatetest12"]]);
$conf = ["valueInputOption" => "RAW"];
$service->spreadsheets_values->update($spreadsheetId, $range, $valueRange, $conf);
I have this snippet, but the problem is tha I need to modify B92, F92 and G92 only, so I would need to update those with the values updatetest2, updatetest6 and updatetest7. I could call it three times, but there's probably a better way. I know there's \Google_Service_Sheets_BatchUpdateSpreadsheetRequest, but the documentation is pretty parse.
https://developers.google.com/resources/api-libraries/documentation/sheets/v4/php/latest/class-Google_Service_Sheets_BatchUpdateSpreadsheetRequest.html#$responseIncludeGridData
$data = [];
array_push(
$data,
new Google_Service_Sheets_ValueRange([
'range' => 'B92',
'values' => [["BATCHUPDATE"]]
])
);
array_push(
$data,
new Google_Service_Sheets_ValueRange([
'range' => 'E92',
'values' => [["BATCHUPDATE"]]
])
);
array_push(
$data,
new Google_Service_Sheets_ValueRange([
'range' => 'F92',
'values' => [["BATCHUPDATE"]]
])
);
$body = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
"valueInputOption" => "RAW",
"data" => $data
]);
$result = $service->spreadsheets->batchUpdate($spreadsheetId, $body);
I also tried the following and I am getting:
PHP Fatal error: Uncaught Google\Service\Exception: {
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"valueInputOption\"
: Cannot find field.\nInvalid JSON payload received. Unknown name \"data\": Cann
ot find field.",
"errors": [
{
"message": "Invalid JSON payload received. Unknown name \"valueInputOpti
on\": Cannot find field.\nInvalid JSON payload received. Unknown name \"data\":
Cannot find field.",
"reason": "invalid"
}
],
"status": "INVALID_ARGUMENT"
}
}
The error you are receiving is due to the fact that the spreadsheets.batchUpdate request does not expect a field named valueInputOption.
However, since you want to update the values from a sheet, you should use the
spreadsheets.values.batchUpdate request and make the following change:
$body = new Google_Service_Sheets_BatchUpdateValuesRequest([
"valueInputOption" => "RAW",
"data" => $data
]);
For further use, if needed, you can easily simulate the Sheets API requests by making use of the "Try this API!" from the documentation pages.
Reference
Class Google_Service_Sheets_BatchUpdateValuesRequest;
Sheets API spreadsheets.values.batchUpdate.
I am using the following code in a PHP server to update values in cells A4 & A7 of a Google Sheet:
$values = array(
array('1234'),
array('abcd')
);
$range = array(array('Sheet1!A4'),array('Sheet1!A7'));
$data = [];
$data[] = new Google_Service_Sheets_ValueRange([
'range' => $range,
'values' => $values
]);
// Additional ranges to update ...
$body = new Google_Service_Sheets_BatchUpdateValuesRequest([
'valueInputOption' => $valueInputOption,
'data' => $data
]);
$result = $service->spreadsheets_values->batchUpdate($spreadsheetId, $body);
On running this request, the following error is received:
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"range\" at 'data[0]': Proto field is not repeating, cannot start list.",
"errors": [
{
"message": "Invalid JSON payload received. Unknown name \"range\" at 'data[0]': Proto field is not repeating, cannot start list.",
"reason": "invalid"
}
],
"status": "INVALID_ARGUMENT"
}
}
What is the correct way to make a Google Sheets API request to update multiple discontinuous cells at once in PHP?
Solved the issue by posting the data in the following format:
$data = [
[
'range'=> 'Sheet1!A4',
'values'=> array(
array('1234')
)
],[
'range'=> 'Sheet1!A7',
'values'=> array(
array('abcd')
)
]
];
// Additional ranges to update ...
$body = new Google_Service_Sheets_BatchUpdateValuesRequest([
'valueInputOption' => 'USER_ENTERED',
'data' => $data
]);
$result = $service->spreadsheets_values->batchUpdate($spreadsheetId, $body);
Trying to add data to a Google Sheet via the Google Sheets API and the BatchUpdate method, but I get this error (don't know what it refers to)
> PHP Fatal error: Uncaught Google\Service\Exception: { "error": {
> "code": 400,
> "message": "Invalid JSON payload received. Unknown name \"\": Root element must be a message.",
> "errors": [
> {
> "message": "Invalid JSON payload received. Unknown name \"\": Root element must be a message.",
> "reason": "invalid"
> }
> ],
> "status": "INVALID_ARGUMENT" } }
Here's my new code:
$spreadsheetId = 'myspreadsheetid';
$client = new Google_Client();
$client->setAuthConfig('mycredntials.json');
$client->setApplicationName('Sheet Automation');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$service = new Google_Service_Sheets($client);
$range = 'A2:L';
$valueInputOption = 'USER_ENTERED';
$body = new Google_Service_Sheets_ValueRange([
'values' => $row1
]);
$params = [
'valueInputOption' => $valueInputOption
];
$result = $service->spreadsheets_values->append($spreadsheetId, $range, $body, $params);
EDIT:
The data I get from the database is put into an array ($row1) that when echoed looks like this:
(
[cdr_id] => myid
[calldate] => 2021-05-27
[src] => mysource
[accountcode] => myaccountcode
[userfield] => disposition
[ivr_std_txn_full] =>
)
I then grab that info and use implode to put it all in one line (this may be the issue)
echo $line1 = implode(',', $row1)
I tried setting the values to be appended to both $row1 and $line1, but still get the payload issue.
in my condition, its because some data have null value, so make sure data you want send not null, you can change it to empty string or other.
example :
[ivr_std_txn_full] => null
change to :
[ivr_std_txn_full] => ''
The solution was pretty simple once I finally figured it out. If you won't be putting the values in manually and instead have an array filled with data you just need to reference each key in the array instead of just the array.
The request body ended up looking like this:
$body = new Google_Service_Sheets_ValueRange([
//'values' => $row1
'values' =>
[
[
$row1['cdr_id'], $row1['calldate'], $row1['src'], $row1['accountcode'], $row1['userfield'], $row1['ivr_std_txn_full']
]
]
]);
$params = [
'valueInputOption' => $valueInputOption
];
$result = $service->spreadsheets_values->append($spreadsheetId, $range, $body, $params);