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

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

Related

GAPI - Google Analytics Sampling.

I am using the GAPI API to access Google Analytics rather than do it myself directly (I know slightly lazy...). I've had a look at the class file but I can't see any built-in function for checking sampling. I was wondering if anyone who has used it has found a way to check if the results being returned are being sampled.
This is the code I am using.
$this->load->config('gapi');
$params = array('client_email' => $this->config->item('account_email'),
'key_file' => $this->config->item('p12_key'));
$this->load->library('gapi', $params);
$this->gapi->requestReportData(
$this->config->item('ga_profile_id'), //reportID
array('date', 'transactionId', 'campaign'), //Dimensions
array('transactionRevenue'), //Metrics
'', //Sort Metric
'medium==email', //Filters
date('Y-m-01'), //Start Date
date('Y-m-d'), //End Date
1,
500
);
$results = $this->gapi->getResults();
My plan is to run the report for a given date range, check to see if the data is sampled and if true, split the query into small parts to get around it.
The v3 API has 2 sampling-related response fields:
Sample Size: number of data entries used
Sample Space: number of data entries available
So if you do Sample Size / Sample Space you have your sampling ratio.
The v4 API has the same but named differently:
samplesReadCounts: number of data entries used
samplingSpaceSizes: number of data entries available
So if you do samplesReadCounts / samplingSpaceSizes you have your sampling ratio.
If gapi doesn't expose these fields in the response, then you should change API client (eg use the official client)

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]);

Google Spreadsheets: Adding Columns using the GData API

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.

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