簡體   English   中英

如何在 PHP 中使用 API v4 保護 Google Sheets 中的范圍?

[英]How to protect range in Google Sheets using API v4 in PHP?

我正在以編程方式制作一些投票收集統計表。 我的下一步是弄清楚如何使用 API 保護某些單元格不被編輯。 在這個例子中,我實際上想繼續保護前三列。 我一直無法找到這方面的文檔。 非常感謝任何幫助。

<?php
/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

include_once __DIR__ . '/includes/google/vendor/autoload.php';

$client = getClient();

$service = new Google_Service_Sheets($client);

// TODO: Assign values to desired properties of `requestBody`:
//$requestBody = new Google_Service_Sheets_Spreadsheet();
$spreadsheet = new Google_Service_Sheets_Spreadsheet([
    'properties' => [
        'title' => 'US Senate 2'
    ]
]);

$spreadsheet = $service->spreadsheets->create($spreadsheet, [
    'fields' => 'spreadsheetId'
]);

$fileId=$spreadsheet->spreadsheetId;

echo $fileId;


// TODO: Change code below to process the `response` object:
echo '<pre>', var_export($spreadsheet, true), '</pre>', "\n";


//Give permissions
/*
$client2 = new \Google_Client();
$client2->setApplicationName('Give permissions');
$client2->setScopes([\Google_Service_Drive::DRIVE]);
$client2->setAccessType('offline');
$client2->setAuthConfig('../credentials.json');
$client2->setPrompt('select_account consent');
$service2 = new Google_Service_Drive($client2);
$newPermission = new Google_Service_Drive_Permission();
$newPermission->setEmailAddress("user@example.com");
$newPermission->setType('user');
$newPermission->setRole('writer');
$fileId=$spreadsheet->spreadsheetId;
$service2->permissions->create($fileId, $newPermission);
*/


//Add data from the dataTables
$client3 = new \Google_Client();
$client3->setApplicationName('Add data from datatables');
$client3->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
$client3->setAccessType('offline');
$client3->setAuthConfig('credentials.json');
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
    $accessToken = json_decode(file_get_contents($tokenPath), true);
    $client3->setAccessToken($accessToken);
}
$service3 = new Google_Service_Sheets($client3);
$spreadsheetId = $fileId;
$range = 'Sheet1';


$headers = array(
  "Candidate",
  "Election",
  "Id",
  "Votes"
);

$row1[]="Collins";
$row1[]="US Senate";
$row1[]="1010010";
$row1[]="0";

$values = [
    $headers,
    $row1,
    // Additional rows ...
];

$body = new Google_Service_Sheets_ValueRange([
    'values' => $values
]);
$params = [
    'valueInputOption' => 'RAW'
];
$insert = [
    "insertDataOption" => "INSERT_ROWS"
];
$result = $service3->spreadsheets_values->append(
    $spreadsheetId,
    $range,
    $body,
    $params,
    $insert
);
echo "<a href='https://docs.google.com/spreadsheets/d/".$fileId."' target='_blank'>https://docs.google.com/spreadsheets/d/".$fileId."</a>";


function getClient()
{
    $redirect_uri = 'http://localhost:8000/' . $_SERVER['PHP_SELF'];

    $client = new Google_Client();
    $client->setApplicationName('Google Sheets API PHP Quickstart');
    //$client->setScopes(Google_Service_Sheets::SPREADSHEETS_READONLY);
    $client->addScope("https://www.googleapis.com/auth/drive");
    $client->addScope("https://www.googleapis.com/auth/drive.file");
    $client->addScope("https://www.googleapis.com/auth/spreadsheets");
    $client->setRedirectUri($redirect_uri);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}

我相信你的目標和你的情況如下。

  • 您想使用 googleapis for php 保護 Google 電子表格中工作表的“A”、“B”和“C”列。
  • 您可以使用 Sheets API 獲取和放置 Google 電子表格的值。

修改點:

  • 在這種情況下,請使用“addProtectedRange”和 Sheets API 中的“spreadsheets.batchUpdate”方法。

修改后的腳本:

$spreadsheetId = "###"; // please set Spreadsheet ID.
$sheetId = "###"; // Please set sheet ID.
$requests = [
    new Google_Service_Sheets_Request([
        'addProtectedRange' => [
            'protectedRange' => [
                'range' => [
                    'sheetId' => $sheetId,
                    'startRowIndex' => 0,
                    'startColumnIndex' => 0,
                    'endColumnIndex' => 3,
                ],
                'description' => 'sample description'
            ]
        ]
    ])
];
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
  'requests' => $requests
]);
$result = $service3->spreadsheets->batchUpdate($spreadsheetId, $batchUpdateRequest);
  • 運行上述腳本時, $spreadsheetId$sheetId “A”到“C”列受到保護。

筆記:

  • $service3來自您的腳本。
  • 請將范圍設置為 GridRange。 參考
  • 在上面的腳本中,編輯器是所有者。

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM