Google Spreadsheets: Adding Columns using the GData API - php

Currently, newly created Google spreadsheets seem to default to having 20 columns.
I am able to create new column headers through the cell feed, but only for those existing 20 columns. Beyond that, I cannot create new columns, much less new column headers, as I get the following error:
Expected response code 200, got 403It looks like someone else already deleted this cell.
Using the Zend GData API, this is what I'm doing:
<?php
/*
* Given:
*
* $columnNames, e.g. array('FirstName', 'LastName', 'DateOfBirth')
* $lastColumnOnSpreadsheet, e.g. 20
* $spreadsheetService
* $spreadsheetKey
* $worksheetId
*/
foreach ($columnNames as $columnName)
{
if (!array_key_exists($columnName, $columnsAlreadyOnSpreadsheet))
{
$spreadsheetService->updateCell(1 /* first row */,
++$lastColumnOnSpreadsheet,
$columnName,
$spreadsheetKey,
$worksheetId);
}
}
?>
So, beyond $lastColumnOnSpreadsheet being 19, I get the aforementioned error. Currently, the only workaround is to manually insert columns to the right, one by one, which, besides being tedious, kind of destroys the purpose of automation via GData.
Is it possible to insert columns via the GData API? If so, how, in particular through the Zend framework?

Java/.net: This shows how to set the size of the sheet, you can use it to append rows and cols
https://developers.google.com/google-apps/spreadsheets/
But I found the OAuth hard. For OAuth I used the GDrive tutorial "DrEdit", is the best OAuth tutorial I have seen.

Related

How to merge two cell in google sheet using PHP API?

How to merge two cell in google sheet using google spreadsheet api (PHP) ?
For someone looking for solution to do merging using google spreadsheet API in PHP, then you can follow as below, but please note for this code to run you must be using Google Sheet API PHP SDK. Also you must declare these classes used in this code in your class or php file at the top using use keyword.
####### Set the Grid Range in sheet ########
$rangeinst = new Google_Service_Sheets_GridRange();
$rangeinst->setSheetId($setSheetId); //set your sheet id here
$rangeinst->setStartRowIndex(0); //start row
$rangeinst->setEndRowIndex(2); //end row
$rangeinst->setStartColumnIndex(0); //start column
$rangeinst->setEndColumnIndex(4); //end column
########## Set Grid range object in merging #########
$merge = new Google_Service_Sheets_MergeCellsRequest();
$merge->setMergeType('MERGE_COLUMNS'); //Can be MERGE_ROWS or MERGE_ALL for more you can check https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#GridRange
$merge->setRange($rangeinst);
//update the sheet with merge request object
$requestMergeBody = new Google_Service_Sheets_Request();
$requestMergeBody->setMergeCells($merge);
$mergerequestBatchBody = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
$mergerequestBatchBody->setRequests($requestMergeBody);
$service->spreadsheets->batchUpdate($spreadsheetId, $mergerequestBatchBody); //$spreadsheetId is different than sheet id (a sheet index) so don't confuse with these two terms,
//spreadsheetId will be your whole spreadsheet unique Id that you can found in your share url of spreadsheet and will look something like this 1Mbd5MsTixm5SE0HHl0-yVqj_4ENwijSdNm5OAiG4pN0

When I try to programmatically add a chart to a google spreadsheet, the api v4 fails with Google_Service_Exception about a grid id

I played around with the google sheets api v4 because it looks quite interesting with the ability to also render charts. I'm using the google api client for php.
First of all I created me a new spreadsheet with two sheets and filled in data on the first sheet. This worked as expected.
Then I wanted to render a chart, based on the data on the first sheet, on the second sheet. I wanted to start of the easy way with a Pie Chart because you only have one data series there.
I always end up with the following error message:
"message": "Invalid requests[0].addChart: No grid with id: 1"
The only id that I set is the one for the charts anchor cell for the second sheet I already created:
$googleSheetsSheetGridCoordinate = new Google_Service_Sheets_GridCoordinate();
$googleSheetsSheetGridCoordinate->setSheetId(1);
$googleSheetsSheetGridCoordinate->setColumnIndex(0);
$googleSheetsSheetGridCoordinate->setRowIndex(0);
$googleSheetsSheetOverlayPosition = new Google_Service_Sheets_OverlayPosition();
$googleSheetsSheetOverlayPosition->setAnchorCell($googleSheetsSheetGridCoordinate);
$googleSheetsSheetOverlayPosition->setHeightPixels(500);
$googleSheetsSheetOverlayPosition->setWidthPixels(700);
Taking a look into the spreadsheet, there is a sheet with id: 1 and it has also the type grid, so i have no idea what the problem might be here.
Update Here is the post Body of my addChart request:
{
"requests":[
{
"addChart":{
"chart":{
"spec":{
"title":"Pie Chart",
"pieChart":{
"legendPosition":"BOTTOM_LEGEND",
"domain":{
"sourceRange":{
"sources":[
{
"endRowIndex":3,
"sheetId":0,
"startColumnIndex":0,
"startRowIndex":2
}
]
}
},
"series":{
"sourceRange":{
"sources":{
"endRowIndex":4,
"sheetId":0,
"startColumnIndex":0,
"startRowIndex":3
}
}
}
}
},
"position":{
"overlayPosition":{
"heightPixels":500,
"widthPixels":700,
"anchorCell":{
"columnIndex":0,
"rowIndex":0,
"sheetId":1
}
}
}
}
}
}
]
}
When I compare it with the example, the only one I could find that covers adding charts, https://codelabs.developers.google.com/codelabs/sheets-api/#9, it looks correct to me.
Ok, I found out the solution.
I was thinking that the sheetId is the index of the sheet, but it's an id a sheet gets once it is created.
So the solution is to get the correct ids:
$sourceId = $googleSheetsSpreadsheet->getSheets()[0]->getProperties()->getSheetId();
$targetId = $googleSheetsSpreadsheet->getSheets()[1]->getProperties()->getSheetId();
Those ids are generated when you upload the spreadsheet, so afaik it is not possible yet to create a sheet with its charts in one create request, but you have to create the sheets you need first and then you can add the charts in another request.

Google Sheets API (PHP) Batch Update

I would like to use the Google Sheets API Batch Update because the calls to update individual cells are extremely slow. The problem is that cells that have no data do not come back as part of a cell feed, so I do not have the necessary edit URL to include those cells in the Batch Update. I have seen reference to a "return-empty" parameter in the Google .NET API which will supposedly return all cells, even empty cells, in a cell feed, but I cannot find any reference to that for the "Protocol" API I am using in PHP (here is an example of a reference to the "return-empty" parameter: Writing to an empty cell in Google Spreadsheets). Does anyone know how to get the cell feed request to return all cells (including empty cells)? Or am I doomed to using the abysmally slow cell update requests?
Quick Hack
If you're using the same API I am, then in googlespraedsheet/api.php at line 152 after
$cellRangeCriteriaQuerystringList = [];
You can add:
$cellRangeCriteriaQuerystringList[] = "return-empty=true";
Better Way
There's a better way, which I have added in my own fork. I created a pull request.
If you work with my fork (or if the pull request is accepted), then you can just add 'returnEmpty' => true to your $cellRange. For example:
$cellList = $spreadsheetAPI->getWorksheetCellList(
$spreadsheetKey,
$worksheetID,
['rowStart' => $rowStart,
'rowEnd' => $rowEnd,
'returnEmpty' => true]);

Where does the Share button in Google Glass send the data?

I'm just starting to explore the functionalities of Google Glass.
What I'm trying to do is a simple Glassware that receives a video from the user, when the default 'Share' function is used.
I have seen the Quickstart project guide and I managed to upload my video in the python demo project; I also managed to implement the example PHP project code in my server.
However, I still can't figure out what exactly is happening where i tap the "Share" button on my Glass: where is sent the data? To my Glassware, to the generic Mirror API, or somewhere else? I suppose the Share function is doing something similar to what is described in the media upload page, but it's not clear how.
The code of the demo project seems to update the timeline event when I upload a picture/video; but if I'm not wrong, this code is just updating an already existing item with the "I have received your data!" caption.
(I'll report here the relevant code from the Google's notify.php sample: )
switch ($request['collection']) {
case 'timeline':
// Verify that it's a share
foreach ($request['userActions'] as $i => $user_action) {
if ($user_action['type'] == 'SHARE') {
$timeline_item_id = $request['itemId'];
$timeline_item = $mirror_service->timeline->get($timeline_item_id);
// Patch the item. Notice that since we retrieved the entire item above
// in order to access the caption, we could have just changed the text
// in place and used the update method, but we wanted to illustrate the
// patch method here.
$patch = new Google_TimelineItem();
$patch->setText("PHP Quick Start got your photo! " .
$timeline_item->getText());
$mirror_service->timeline->patch($timeline_item_id, $patch);
break;
}
}
...
Where and when is actually received the video? I need to know this in order to perform additional operations when I receive the data.
The shared picture or video is downloaded through the download_attachment function in mirror-client.php of the Quickstart PHP project.
Here is the function:
/**
* Download an attachment's content.
*
* #param string item_id ID of the timeline item the attachment belongs to.
* #param Google_Attachment $attachment Attachment's metadata.
* #return string The attachment's content if successful, null otherwise.
*/
function download_attachment($item_id, $attachment) {
$request = new Google_HttpRequest($attachment->getContentUrl(), 'GET', null, null);
$httpRequest = Google_Client::$io->authenticatedRequest($request);
if ($httpRequest->getResponseHttpCode() == 200) {
return $httpRequest->getResponseBody();
} else {
// An error occurred.
return null;
}
}

Using Google Analytics API with PHP

I am using the Google Analytics PHP class to get data from Google Analytics.
http://code.google.com/p/gapi-google-analytics-php-interface/wiki/GAPIDocumentation
I would like to get a report of "Bounce Rate" For "Top Contnet".
The thing is I am not familiar with the terminology.
When I am trying to get a "content" report or "topcontent" or "top_content" it says that there in no such metric. I simply don't know the right expressions.
Does anyone know where can I find a list of all expressions? metrics & dimensions?
Thanks.
Top content isn't a metric, it's just a list of the pages on your site with the highest number of page views.
The metric you're looking for is 'entranceBounceRate' and the dimension is 'pagePath'. You want to get the bounce rate for the top X most visited pages on your site, so you'll want to limit your results and sort the results by '-pageviews' (pageviews descending).
If you want to get the bounce rate for the top 10 most viewed pages on your site, your query should look like this:
$ga = new gapi('email#yourdomain.com','password');
$ga->requestReportData(145141242,array('pagePath'),array('entranceBounceRate','pageviews'),array('-visits'),null,null,null,10);
The Google Analytics Export API has a data feed query explorer that should help you out considerably when using GAPI:
http://code.google.com/apis/analytics/docs/gdata/gdataExplorer.html
Also, here's a list of all available dimensions and metrics you can pull from the API:
http://code.google.com/apis/analytics/docs/gdata/gdataReferenceDimensionsMetrics.html
Definitely read over the GAPI documentation:
http://code.google.com/p/gapi-google-analytics-php-interface/wiki/GAPIDocumentation
If you would like to get the global Bounce Rate for the last 30days (by default), here is how. Very simple once you know it.
//Check Bounce Rate for the last 30 days
$ga = new gapi(ga_email, ga_password);
$ga->requestReportData(145141242, NULL ,array('bounces', 'visits'));
$data = round(($ga->getBounces() / $ga->getVisits()) * 100) . "%";
Note that the GAPI has a bug, they mention the dimension parameter is optional (2nd parameter) but it's not. You have to open the gapi.class.php file and patch line 128 with this:
//Patch bug to make 2nd parameter optional
if( !empty($dimensions) ) {
$parameters['dimensions'] = 'ga:'.$dimensions;
} else {
$parameters['dimensions'] = '';
}

Categories