I want to add new data to the start (beginning) of the sheet. So I have to add a new column A1 to the sheet. But I can't find any API example with PHP.
Now I am appending the data with this:
$body = new Google_Service_Sheets_ValueRange(['values' => $values]);
$result = $service->spreadsheets_values->append($new_sheet_id, 'A1:E1', $body, $options); // appent the data to the spreadsheet
Thanks.
UPD:
here is what I have found
/* insert columns */
$requests = new Google_Service_Sheets_Request(array(
'insertDimension' => array(
'range' => array(
'sheetId' => 0,
'dimension' => "COLUMNS",
'startIndex' => 0,
'endIndex' => 5
)
)
));
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array(
'requests' => $requests
));
$result = $service->spreadsheets->batchUpdate($new_sheet_id, $batchUpdateRequest);
/* insert columns */
I believe it is not possible with the Spreadsheet API. I've been studying the possibility and so far I can't see how to do that. There is an alternate solution but requires you to use the Google Apps Script Execution API. Please feel free to implement if the solution is suitable. Follow these steps:
- Create a new spreadsheet and name it whatever you want.
- Fill out the spreadsheet so it looks the same as the image below
- Open the script editor by going to "Tools > Script Editor"
- Name the project anything you want as you see in the image below
Delete everyting you have inside "Code.gs" and paste the following:
function insertColumn(vals) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// This inserts a column in the first column position
sheet.insertColumnBefore(1);
//This set the values in the cells of the first column inserted
var range = sheet.getRange("A1:A5");
range.setValues(vals);
}
Now, go to the API manager, select your project and enable the API, like in the image below
Go to your project settings and copy the Project Number, as in the image below
Return to the script editor explained on step 3 and shown on step 4. Click on "Resources > Cloud Platform Project"
Paste the project number in the field that reads "Enter Project Number here" and then click on "Set Project". See image below.
You will get a confirmation window. Confirm the change and wait for it to finish.
Inside the project editor, go to "Publish > Deploy as API Executable". Type a version and click on "Deploy". See image below
It will show you a couple more of info messages and then you should see this:
Please copy the Current API ID and then make sure to save the project changes.
Create a new PHP file and paste the following:
<?php session_start();
//INCLUDE PHP CLIENT LIBRARY
require_once 'vendor/autoload.php';
//scope required to modify the spreadsheet
$scopes = array("https://www.googleapis.com/auth/spreadsheets");
// Create client object
$client = new Google_Client();
$client->setRedirectUri('http://'.$_SERVER['HTTP_HOST'].'/index.php');
$client->setAuthConfig("client_secret.json");
$client->setScopes($scopes);
if( isset($_SESSION["access_token"]) && ($_SESSION["access_token"]) ) {
$client->setAccessToken($_SESSION["access_token"]);
$service = new Google_Service_Script($client);
//Here goes the script Id you copied on step 13
$scriptId = 'XXX-OROcbUXO78URUxxxLYqFdOk6teXXX';
$values = array(
array("Email"),
array("jonsnow@email.com"),
array("aryastark@email.com"),
array("sansastark@email.com"),
array("cerseilanister@email.com")
);
$params = array($values);
// Create an execution request object.
$request = new Google_Service_Script_ExecutionRequest();
$request->setFunction('insertColumn');
$request->setParameters($params);
$request->setDevMode(true); //required to work with parameters
try {
// Make the API request.
$response = $service->scripts->run($scriptId, $request);
if ($response->getError()) {
// The API executed, but the script returned an error.
// Extract the first (and only) set of error details.
// The values of this object are the script's 'errorMessage'
// and 'errorType', and an array of stack trace elements.
$error = $response->getError()['details'][0];
printf("Script error message: %s\n", $error['errorMessage']);
if (array_key_exists('scriptStackTraceElements', $error)) {
// There may not be a stacktrace if the script didn't start executing.
print "Script error stacktrace:\n";
foreach($error['scriptStackTraceElements'] as $trace) {
printf("\t%s: %d\n", $trace['function'], $trace['lineNumber']);
}
}
} else {
// The structure of the result will depend upon what the Apps Script
// function returns.
$resp = $response->getResponse();
var_dump($resp);
}
} catch (Exception $e) {
// The API encountered a problem before the script started executing.
echo 'Caught exception: ', $e->getMessage(), "\n";
}
} else {
if( !isset($_GET["code"]) ){
$authUrl = $client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://'.$_SERVER['HTTP_HOST'] .'/index.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
?>
Run the PHP script and then look at the result in your Spreadhsheet. You should see as below.
As you can see, a column was inserted at the beginning and the values were filled out too. I hope this is helpful somehow to you or someone else.