создать копию таблицы Google Doc, используя PHP API

0

Я хочу создать копию листа excel google doc с помощью PHP API. Я вижу код Java, но не PHP-код вообще :(

На самом деле у меня уже есть лист excel на Google Диске, который я хочу показать на веб-сайте, я уже успел в нем, но проблема в том же файле видна всем, и если один пользователь меняет файл и в то же время тот же пользователь может видеть который изменяется, поскольку он синхронизируется с приложением Google.

Поэтому я решил, что решение состоит в том, что я могу создать копию листа и показать каждому пользователю два разных экземпляра с помощью PHP API.

===============

Отредактированный код

  function copyFile($service, $originFileId, $copyTitle) {
      $copiedFile = new Google_DriveFile();
      $copiedFile->setTitle($copyTitle);
      try {
        $arr['convert'] =   false;
        $arr['visibility']  =   'default';
        return $service->files->copy($originFileId, $copiedFile,$arr);
      } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
      }
      return NULL;
    }

    function insertPermission($service, $fileId, $value, $type, $role) {
      $newPermission = new Google_Permission();
      $newPermission->setValue($value);
      $newPermission->setType($type);
      $newPermission->setRole($role);
      try {
        return $service->permissions->insert($fileId, $newPermission);
      } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
      }
      return NULL;
    }



    function updateRevision($service, $fileId, $revisionId) {
      try {
        // First retrieve the revision from the API.
        $revisions =    $service->revisions;
        $revision = $revisions->get($fileId, $revisionId);
        echo '<pre>';print_r($revision);
        $revision->setPinned(true);
        return $revisions->update($fileId, $revisionId, $revision);
      } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
      }
      return NULL;
    }
    function updateRevision1($service, $fileId, $revisionId) {
          $patchedRevision = new Google_Revision();
          $patchedRevision->setPublished(true);
          $patchedRevision->setPublishAuto(true);
          $patchedRevision->setPublishedOutsideDomain(true);
          try {
            return $service->revisions->patch($fileId, $revisionId, $patchedRevision);
          } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
          }
          return NULL;
        }


    require_once 'google-api-php-client/src/Google_Client.php';
    require_once 'google-api-php-client/src/contrib/Google_DriveService.php';


    $client = new Google_Client();
    // Get your credentials from the console
    $client->setClientId('clientid');
    $client->setClientSecret('secret');
    $client->setScopes(array('https://www.googleapis.com/auth/drive'));
    $client->setRedirectUri('redirecturi');

    $service = new Google_DriveService($client);
    if(!isset($_GET['code']) ) {
    $authUrl = $client->createAuthUrl();
    header('location: '.$authUrl );
    die;
    }
    else{
        $authCode = $_GET['code'];

        // Exchange authorization code for access token
        $accessToken = $client->authenticate($authCode);
        $client->setAccessToken($accessToken);
        $new_file   =   copyFile($service,'fileid','Baby Schema');
        echo 'file=<pre>';print_r($new_file);
        $permission  = insertPermission($service,$new_file['id'],'me','anyone','writer'); 
        echo 'permission=<pre>';print_r($permission); 
        $revision   =   updateRevision1($service, $new_file['id'], '1');
        echo 'pub=<pre>';print_r($revision); 
    }

Код работает абсолютно идеально, но он не делает то, что я хочу.

Вышеупомянутый код выполняет эти задачи

1) I have one spreadsheet on [email protected]
2) I am creating copy when [email protected] login to my abc.com website.
3) I am setting copy to be public on web.
4) Making copy to be published on web.

Теперь у меня проблема.

1) In the spreadsheet there are 5 sheets out of them 2 are editable and rest 3 are protected so no one can see my formulas.
2) When copy is created by [email protected] then he becomes the owner of file while file is on [email protected] while I want Owner to be bhuvneshgupta not bhuvnesh.gupta because I don't want to show formulas to any one not even bhuvnesh.gupta when file is opened on web.
3) I want to protect 3 sheets of spreadsheet to everyone.

Я использую этот способ для вызова spreadесете в Интернете.

<iframe width="100%" height="600" src="https://docs.google.com/spreadsheets/d/fileid/edit?usp=sharing;&rm=minimal"></iframe>

Пожалуйста, помогите мне, ребята. Это последняя точка моего проекта.

Пожалуйста, помогите мне, ребята.

Заранее спасибо!

Теги:
excel
google-docs
google-api-php-client

1 ответ

0

Ссылка на API-интерфейс google содержит код Php для копирования файлов.

/**
  * Copy an existing file.
  *
  * @param Google_DriveService $service Drive API service instance.
  * @param String $originFileId ID of the origin file to copy.
  * @param String $copyTitle Title of the copy.
  * @return DriveFile The copied file. NULL is returned if an API error occurred.
  */
 function copyFile($service, $originFileId, $copyTitle) {
   $copiedFile = new Google_DriveFile();
   $copiedFile->setTitle($copyTitle);
   try {
     return $service->files->copy($originFileId, $copiedFile);
   } catch (Exception $e) {
     print "An error occurred: " . $e->getMessage();
   }
   return NULL;
 }

Он находится здесь: https://developers.google.com/drive/v2/reference/files/copy#try-it

  • 0
    Да, я прошел через это только сейчас. Но я застрял на этой переменной $ service. Пожалуйста, помогите мне в этом.
  • 0
    Посмотрите, поможет ли это: developers.google.com/drive/web/quickstart/quickstart-php Если ответ решил вашу проблему, примите его с зеленой галочкой. Благодарю.
Показать ещё 3 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню