Cannot hide gridlines Google Spreadsheet API PHP - php

I am trying to hide all gridlines from a file I just created with Google Sheets API, I am using the following code:
$service = $this->GoogleServiceSheets();
$sheetID = null;
$worksheetSheets = $service->spreadsheets->get($fileID)->sheets;
foreach($worksheetSheets as $sheet){
$sheetID = $sheet->properties['sheetId'];
break;
}
$service = $this->GoogleServiceSheets();
$requests = [
new \Google_Service_Sheets_Request([
'updateDimensionProperties' => [
'range'=> new \Google_Service_Sheets_DimensionRange([
'sheetId' => $sheetID,
'dimension' => 'COLUMNS',
'startIndex' => 0,
'endIndex' => 1000
]),
'properties'=> new Google_Service_Sheets_DimensionProperties([
"hideGridlines"=> True,
]),
'fields' => 'hideGridlines'
]
])
];
$batchUpdateRequest = new \Google_Service_Sheets_BatchUpdateSpreadsheetRequest(['requests' => $requests]);
$service->spreadsheets->batchUpdate($fileID, $batchUpdateRequest);
But does not hide, instead gives me an error.
What I am doing wrong?

In order to hide the grid line of the Google Spreadsheet with Sheets API, UpdateSheetPropertiesRequest of batchUpdate is used. Unfortunately, updateDimensionProperties cannot achieve this. I think that this is the reason of your issue. In order to achieve your goal, when your script is modified, it becomes as follows.
Modified script:
In this modification, your $requests is modified as follows.
$requests = [
new \Google_Service_Sheets_Request([
'updateSheetProperties' => [
'properties' => [
'sheetId' => $sheetID,
'gridProperties' => [
'hideGridlines' => true
],
],
'fields' => 'gridProperties.hideGridlines'
],
])
];
Note:
In this modification, it supposes that your $service = $this->GoogleServiceSheets(); and $sheetID are valid values. And also, it supposes that you have already been able to get and put values for Google Spreadsheet using Sheets API. Please be careful this.
Reference:
UpdateSheetPropertiesRequest

Related

How to apply cell format using Google Sheets api v4 in php?

I'm new to this API. For example like, how to align the text? How to set the length of the cell? Thank you in advance.
$client = getClient();
$service = new Google_Service_Sheets($client);
try{
$values = [["",""];
$body = new Google_Service_Sheets_ValueRange([
'values' => $values
]);
$params = [
'valueInputOption' => 'USER_ENTERED'
];
//executing the request
$result = $service->spreadsheets_values->update($spreadsheetId, $range,
$body, $params);
printf("%d cells updated.\n", $result->getUpdatedCells());
return $result->getUpdatedCells();
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}
}
this column
From it is the column width that i want to change, and also i want to align the text horizontal direction. For alignment example, i want to align only the table header text to be center., I believe your goal is as follows.
You want to reflect the alignment at the 1st row and the column width of all columns.
You want to achieve this using googleapis for PHP.
You have already been able to get and put values to Spreadsheet using Sheets API.
In this case, how about the following sample script?
Sample script:
$client = getClient(); // This is from your script.
$spreadsheet_id = "###"; // please set Spreadsheet ID.
$sheet_id = "0"; // please set Sheet ID.
$column_width = 200; // Please set the column width you want.
$service = new Google_Service_Sheets($client);
$requests = [
new \Google\Service\Sheets\Request([
"repeatCell" => [
"range" => [
"sheetId" => $sheet_id,
"startRowIndex" => 0,
"endRowIndex" => 1,
],
"cell" => [
"userEnteredFormat" => ["horizontalAlignment" => "CENTER"],
],
"fields" => "userEnteredFormat.horizontalAlignment",
],
]),
new \Google\Service\Sheets\Request([
"updateDimensionProperties" => [
"range" => [
"sheetId" => $sheet_id,
"startIndex" => 0,
"dimension" => "COLUMNS",
],
"properties" => ["pixelSize" => $column_width],
"fields" => "pixelSize",
],
]),
];
$batchUpdate = new \Google\Service\Sheets\BatchUpdateSpreadsheetRequest(["requests" => $requests]);
$service->spreadsheets->batchUpdate($spreadsheet_id, $batchUpdate);
When this script is run, the text alignment at the 1st row is changed to "CENTER" and the column width of all columns is changed to 200 pixels. If you want to change the column width, please modify $column_width.
References:
Method: spreadsheets.batchUpdate
RepeatCellRequest
UpdateDimensionPropertiesRequest

Google spreadsheet API with PHP - how to insert a row with data to beginning

I have this code which inserts a blank row near the top of a Google Sheet.
But how can I insert data in this row?
$service = new Google_Service_Sheets($client);
$dr = new Google_Service_Sheets_DimensionRange();
$dr->setSheetId(0);//first sheet/tab of spreadsheet file
$dr->setDimension('ROWS');
$dr->setStartIndex(1);
$dr->setEndIndex(2);
$ins = new Google_Service_Sheets_InsertDimensionRequest();
$ins->setRange($dr);
$ins->setInheritFromBefore(false);
$ssr = new Google_Service_Sheets_Request();
$ssr->setInsertDimension($ins);
$busr = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
$busr->setRequests([$ssr]);
$response = $service->spreadsheets->batchUpdate($spreadsheetId, $busr, []);
Resolved the issue with the following code:
$request = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
'requests' => [
'insertDimension' => [
'range' => [
'startIndex' => 1,
'endIndex' => count($array)+1,
'dimension' => 'ROWS',
'sheetId' => 0
]
]
]
]);
$result = $service->spreadsheets->batchUpdate($spreadsheetId, $request);

Formatting cells background and bold in google sheet (php)

I'm trying to change the background color and the bold value of a couple of cells in my spreadsheet. I know I have a working service because I'm doing a spreadsheets_values update right before and it works.
Changing values works so I'm guessing it must be something with my config. I dont get any errors, the $result variable remains empty. Any ideas would be appreciated, thanks.
// known to work from changing the values
$client = getClient();
$service = new Google_Service_Sheets($client);
$spreadsheetId = 'MY SPREADSHEET ID';
// new code
$r = $g = $b = 0.5;
$a = 1;
$myRange = [
//'sheetId' => 0, // can be omitted because I'm working on the first sheet
'startRowIndex' => 5,
'endRowIndex' => 10,
//'startColumnIndex' => 0, // can be omitted because default is 0
'endColumnIndex' => 5,
];
$format = [
'backgroundColor' => [
'red' => $r,
'green' => $g,
'blue' => $b,
'alpha' => $a,
],
'textFormat' => [
'bold' => true
]
];
$requests = [
new Google_Service_Sheets_Request([
'repeatCell' => [
'fields' => 'userEnteredFormat.backgroundColor, userEnteredFormat.textFormat.bold',
'range' => $myRange,
'cell' => [
'userEnteredFormat' => $format,
],
],
])
];
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
'requests' => $requests
]);
$result = $service->spreadsheets->batchUpdate($spreadsheetId, $batchUpdateRequest);
SOLUTION:
I made 2 mistakes here:
1) i thought error reporting was on, but it was not. #greybeard got me looking for that and after that I got the following error (this might help others):
Uncaught Google_Service_Exception: { "error": { "code": 400, "message": "Invalid requests[0].repeatCell: No grid with id: 1"
2) as you can see in the error above my grid id is rejected. this is due to the fact that I confused sheetId with sheet index. google sheets actually have a "real" id that you can get by the following request
$sheetId = $service->spreadsheets->get($spreadsheetId);
This returns an array with an object which holds the sheetIds. For the sheet with index 0 this would be
$sheetId = $sheetId->sheets[0]->properties->sheetId;
To directly access only a certain sheet and not the whole spreadsheet you can add the 'ranges' property
$sheetId = $service->spreadsheets->get($spreadsheetId, ['ranges' => 'NAME_OF_SHEET']);
so the full script would be:
$client = getClient(); // this calls my custom function that does the authentication
$service = new Google_Service_Sheets($client);
$spreadsheetId = 'MY SPREADSHEET ID';
// get sheetId of sheet with index 0
$sheetId = $service->spreadsheets->get($spreadsheetId);
$sheetId = $sheetId->sheets[0]->properties->sheetId;
// set colour to a medium gray
$r = $g = $b = 0.5;
$a = 1;
// define range
$myRange = [
'sheetId' => $sheetId, // IMPORTANT: sheetId IS NOT the sheets index but its actual ID
'startRowIndex' => 5,
'endRowIndex' => 10,
//'startColumnIndex' => 0, // can be omitted because default is 0
'endColumnIndex' => 5,
];
// define the formatting, change background colour and bold text
$format = [
'backgroundColor' => [
'red' => $r,
'green' => $g,
'blue' => $b,
'alpha' => $a,
],
'textFormat' => [
'bold' => true
]
];
// build request
$requests = [
new Google_Service_Sheets_Request([
'repeatCell' => [
'fields' => 'userEnteredFormat.backgroundColor, userEnteredFormat.textFormat.bold',
'range' => $myRange,
'cell' => [
'userEnteredFormat' => $format,
],
],
])
];
// add request to batchUpdate
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
'requests' => $requests
]);
// run batchUpdate
$result = $service->spreadsheets->batchUpdate($spreadsheetId, $batchUpdateRequest);

Firebase Update Multiple Items

How can I update multiple items on firebase with just one request?
I can not let my system wait to complete multiple requests, so I need to update them with just one.
Current Firebase Data:
PHP Code:
$data = [
'mydata-1' => [
'position' => 1,
],
'mydata-2' => [
'position' => 2,
],
];
$client = new \GuzzleHttp\Client();
$response = $client->put(FIREBASE_ENDPOINT . '/data', [
'json' => $data,
]);
Expected Firebase Data:
Problem:
The request subscribe all my data and I lose the title field.
I also tried PATCH request, but I got the same response.
Based on Frank van Puffelen comment:
$data = [
'mydata-1/position' => 1,
'mydata-2/position' => 2,
];
$client = new \GuzzleHttp\Client();
$response = $client->patch(FIREBASE_ENDPOINT . '/data', [
'json' => $data,
]);
Documentation:
https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html

Google spreadsheet, how to protect Cell?

I create excel file and proteced some field in this file. In Office excel all fine my some cell locked for edit, begin I upload my excel file in google drive with convert - true (Whether to convert this file to the corresponding Google Docs format. (Default: false)) But in google spread sheet I can edit locked cell, how to locked in google spread sheet some cell ?
create excel file
$phpExcel = new \PHPExcel();
$ews = $phpExcel->getSheet(0);
$ews->setTitle(Reports::LIST_AOG);
$ews->getProtection()->setSheet(true);
$ews
->getStyle('E6:F36')
->getProtection()->setLocked(
\PHPExcel_Style_Protection::PROTECTION_UNPROTECTED
);
and now I can edit only E6:F36 cell in my file in computer, then upload in google drive
$insertArray = [
'mimeType' => $fileUpload->getMimeType(),
'uploadType' => 'media',
'data' => file_get_contents($fileUpload),
'convert' => true
];
$service = new \Google_Service_Drive($client->getGoogleClient());
$file = new \Google_Service_Drive_DriveFile();
$file->setTitle($nameFile);
$file->setMimeType($fileUpload->getMimeType());
try {
$createdFile = $service->files->insert($file, $insertArray);
$spreadsheetId = $createdFile->getId();
} catch (\Exception $e) {
$view = $this->view((array)GoogleDriveController::ERROR_OCCURRED . $e->getMessage(), 400);
return $this->handleView($view);
}
I fing for google spreadsheet api bundle asimlqt/php-google-spreadsheet-client but not find how to protected
$serviceRequest = new DefaultServiceRequest($arrayAccessTokenClient['access_token']);
ServiceRequestFactory::setInstance($serviceRequest);
$spreadsheetService = new SpreadsheetService();
$spreadsheet = $spreadsheetService->getSpreadsheetById($spreadsheetId);
$worksheetFeed = $spreadsheet->getWorksheets();
$cellFeed = $worksheet->getCellFeed();
$cellFeed->editCell(1, 1, 'developer');
$cellFeed->editCell(1, 2, 'hors');
$cellFeed->editCell(10, 2, 'sum');
or how to protected cell with asimlqt/php-google-spreadsheet-client ?
and In google spread sheet I can any edit any cell (((( Who knows hot to protected cell in google spreat sheet ?
UPDATE
I read Google Sheets API and try create request, this I have
$arrayAccessTokenClient = json_decode($client->getGoogleClient()->getAccessToken(), true);
$serviceRequest = new DefaultServiceRequest($arrayAccessTokenClient['access_token']);
ServiceRequestFactory::setInstance($serviceRequest);
$spreadsheetService = new SpreadsheetService();
$spreadsheet = $spreadsheetService->getSpreadsheetById($spreadsheetId);
$worksheetFeed = $spreadsheet->getWorksheets();
$worksheet = $worksheetFeed->getByTitle(Reports::LIST_AOG);
$addProtectedRange['addProtectedRange'] = [
'protectedRange' => [
'range' => [
'sheetId' => $worksheet->getGid(),
'startRowIndex' => 3,
'endRowIndex' => 4,
'startColumnIndex' => 0,
'endColumnIndex' => 5,
],
'description' => "Protecting total row",
'warningOnly' => true
]
];
$guzzle = new Client();
$putTeam = $guzzle
->post('https://sheets.googleapis.com/v4/spreadsheets/'.$spreadsheetId.':batchUpdate?key='.$arrayAccessTokenClient['access_token'],
[],
json_encode($addProtectedRange)
)
->send()
->getBody(true);
$answer = json_decode($putTeam, true);
But have
Client error response
[status code] 401
[reason phrase] Unauthorized
[url] https://sheets.googleapis.com/v4/spreadsheets/1M_NFvKMZ7Rzbj9ww86AJRMto1UesIy71840r2sxbD5Y:batchUpdate?key=myAccessToken
Early I have Google Api Clien with access token and I can change cell and update with google spread sheet and work fine but https://sheets.googleapis.com/v4/spreadsheets/'.$spreadsheetId.':batchUpdate?key='.$arrayAccessTokenClient['access_token'],
return 401 and I not understand why and how to correct. Help
I think google spreadsheets allow the editing of protected MSExcel sheets the moment they become Google docs. The rules for MSExcel doesn't always apply to Google Sheets. Reading from Adding Named or Protected Ranges:
The following spreadsheets.batchUpdate request contains two request
objects. The first gives the range A1:E3 the name "Counts". The second
provides a warning-level protection to the range A4:E4. This level
protection still allows cells within the range to be edited, but
prompts a warning prior to making the change.
This thread also shares the same view.
However, if it's a google spreadsheet file you want to protect, check this guide.
I read documentation and
$addProtectedRange['requests'] = [
'addProtectedRange' => [
'protectedRange' => [
'range' => [
'sheetId' => $worksheetGid,
'startRowIndex' => $startRowIndex,
'endRowIndex' => $endRowIndex,
'startColumnIndex' => $startColumnIndex,
'endColumnIndex' => $endColumnIndex,
],
'description' => "Protecting total row",
'warningOnly' => false,
'editors' => [
'users' => [
"shuba.ivan.vikt#gmail.com"
]
]
],
]
];
This file_get_contents variant, because Guzzle not returned json response from google, like this:
{
"protectedRangeId": number,
"range": {
object(GridRange)
},
"namedRangeId": string,
"description": string,
"warningOnly": boolean,
"requestingUserCanEdit": boolean,
"unprotectedRanges": [
{
object(GridRange)
}
],
"editors": {
object(Editors)
},
}
I create new question for this for Guzzle reasponse
This is variant for update protected edit cell
$addProtectedRangeJson = json_encode($addProtectedRange);
$url = 'https://sheets.googleapis.com/v4/spreadsheets/' . $spreadsheetId . ':batchUpdate';
$opts = array('http' =>
array(
'method' => 'POST',
'header' => "Content-type: application/json\r\n" .
"Authorization: Bearer $arrayAccessTokenClient\r\n",
'content' => $addProtectedRangeJson
)
);
$context = stream_context_create($opts);
$response = file_get_contents($url, FALSE, $context);
$answer = json_decode($response, TRUE);
$addProtectedRangeUpdate['requests'] = [
'updateProtectedRange' => [
'protectedRange' => [
'protectedRangeId' => $protectedRangeId,
'warningOnly' => false,
'editors' => [
'users' => [
"shuba.ivan.vikt#gmail.com"
]
]
],
'fields' => "namedRangeId,warningOnly,editors"
]
];
$addProtectedRangeUpdateJson = json_encode($addProtectedRangeUpdate);
$optsUpdate = array('http' =>
array(
'method' => 'POST',
'header' => "Content-type: application/json\r\n" .
"Authorization: Bearer $arrayAccessTokenClient\r\n",
'content' => $addProtectedRangeUpdateJson
)
);
$contextUpdate = stream_context_create($optsUpdate);
$responseUpdate = file_get_contents($url, FALSE, $contextUpdate);
$answerUpdate = json_decode($responseUpdate, TRUE);
and this is Guzzle, but Guzzle without google json response this is bad I wait maybe who know what is it problem, because standard php function file_get_contents work very well and I have json google response. But without response this variant work normal, cell protected in spread sheet
$guzzle = new Client();
$postCell = $guzzle
->post('https://sheets.googleapis.com/v4/spreadsheets/' . $spreadsheetId . ':batchUpdate',
[],
$addProtectedRangeJson
)
->addHeader('Authorization', 'Bearer ' . $arrayAccessTokenClient)
->addHeader('Content-type', 'application/json')
;
$postCell
->send()
->getBody(true)
;
$contents = (string) $postCell->getBody();// get body that I post -> my request, not response
$contents = $postCell->getBody()->getContents();// not find getContents, ask me did you mean to call getContentMd5
$answer = json_decode($postCell->getResponse()->getBody(), true);

Categories