Last active
October 31, 2021 20:04
-
-
Save thehelvetian/2e94d60b796735b167dfb1c7560049ae to your computer and use it in GitHub Desktop.
Add a new row to a spreadsheet using Google Sheets API v4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This is a proof of concept. In real life you would split up the various parts and allow for different cell value | |
* types. Also read Leviscowles1986's comment below: | |
* https://gist.github.com/thehelvetian/2e94d60b796735b167dfb1c7560049ae#gistcomment-1822986 | |
* | |
* @param array $ary_values An array containing the cell values | |
* @return bool Request status | |
*/ | |
function addRowToSpreadsheet($ary_values = array()) { | |
// Set up the API | |
$client = new Google_Client(); | |
$client->setAuthConfigFile(KEYS_PATH.'/client_secret.json'); // Use your own client_secret JSON file | |
$client->addScope(Google_Service_Sheets::SPREADSHEETS); | |
$accessToken = 'ACCESS_TOKEN'; // Use your generated access token | |
$client->setAccessToken($accessToken); | |
$sheet_service = new Google_Service_Sheets($client); | |
// Set the sheet ID | |
$fileId = 'SPREADHEET_FILE_ID'; // Copy & paste from a spreadsheet URL | |
// Build the CellData array | |
$values = array(); | |
foreach( $ary_values AS $d ) { | |
$cellData = new Google_Service_Sheets_CellData(); | |
$value = new Google_Service_Sheets_ExtendedValue(); | |
$value->setStringValue($d); | |
$cellData->setUserEnteredValue($value); | |
$values[] = $cellData; | |
} | |
// Build the RowData | |
$rowData = new Google_Service_Sheets_RowData(); | |
$rowData->setValues($values); | |
// Prepare the request | |
$append_request = new Google_Service_Sheets_AppendCellsRequest(); | |
$append_request->setSheetId(0); | |
$append_request->setRows($rowData); | |
$append_request->setFields('userEnteredValue'); | |
// Set the request | |
$request = new Google_Service_Sheets_Request(); | |
$request->setAppendCells($append_request); | |
// Add the request to the requests array | |
$requests = array(); | |
$requests[] = $request; | |
// Prepare the update | |
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array( | |
'requests' => $requests | |
)); | |
try { | |
// Execute the request | |
$response = $sheet_service->spreadsheets->batchUpdate($fileId, $batchUpdateRequest); | |
if( $response->valid() ) { | |
// Success, the row has been added | |
return true; | |
} | |
} catch (Exception $e) { | |
// Something went wrong | |
error_log($e->getMessage()); | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Perfect! Thank you