Skip to content

Instantly share code, notes, and snippets.

@thehelvetian
Last active October 31, 2021 20:04
Show Gist options
  • Save thehelvetian/2e94d60b796735b167dfb1c7560049ae to your computer and use it in GitHub Desktop.
Save thehelvetian/2e94d60b796735b167dfb1c7560049ae to your computer and use it in GitHub Desktop.
Add a new row to a spreadsheet using Google Sheets API v4
<?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;
}
@neri4488
Copy link

This is how simply I did it, creating record on google sheet with range from A to K

public function newRow($record = []){

        $newRange = "A:K";

        $body = new Google_Service_Sheets_ValueRange([
            'range' => $newRange,
            'values' => ['values' => $record],
        ]);

$service = new Google_Service_Sheets($client);

        $newRow = $service->spreadsheets_values->append('SPREAD_SHEET_ID_HERE',$newRange,$body,['valueInputOption' => 'USER_ENTERED']);
        return response()->json($newRow->toSimpleObject());
    }

@appimatic
Copy link

this was super helpful to me as well - thanks for being straightforward with your presentation - something that is lacking with a lot of Google API documentation

@IcedElect
Copy link

Perfect! Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment