Google Sheets API: Create or move Spreadsheet into Folder

前端 未结 4 2089

Is it possible to create a Spreadsheet in a specified Folder or do I have to use the Drive API to move it afterwards?

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-04 01:07

    Use the drive API to create an empty sheet and open it using the sheets api:

    function getClient()
    {
        $client = new \Google_Client();
    
        putenv(
            'GOOGLE_APPLICATION_CREDENTIALS='.__DIR__."/config/google-creds.json"
        );
        $client = new \Google_Client();
        $client->setScopes(
            [
                \Google_Service_Drive::DRIVE,
                \Google_Service_Storage::CLOUD_PLATFORM,
                'https://www.googleapis.com/auth/spreadsheets',
            ]
        );
        $client->useApplicationDefaultCredentials();
    
        return $client;
    }
    
    // Get the API client and construct the service object.
    $client = getClient();
    $service = new Google_Service_Drive($client);
    
    $ROOT_FOLDER_ID='you-must-set-this-to-your-folder-id';
    // create the empty sheet:
    
    $googleServiceDriveDriveFile = new \Google_Service_Drive_DriveFile();
    $googleServiceDriveDriveFile->setMimeType(
        'application/vnd.google-apps.spreadsheet')
        ;
    $googleServiceDriveDriveFile->setName('Test');
    $googleServiceDriveDriveFile->setParents([$ROOT_FOLDER_ID]);
    $res  = $service->files->create($googleServiceDriveDriveFile);
    
    // print the id of the file we just made
    print 'Created file with id : ' . $res->getId() . "\n";
    
    // Print the names and IDs for up to 10 files.
    $optParams = array(
        'pageSize' => 10,
        'fields'   => 'nextPageToken, files(id, name)',
        'q' => "'$ROOT_FOLDER_ID' in parents"
    );
    
    $results = $service->files->listFiles($optParams);
    
    if (count($results->getFiles()) == 0) {
        print "No files found.\n";
    } else {
        print "Files:\n";
        foreach ($results->getFiles() as $file) {
            printf("%s (%s)\n", $file->getName(), $file->getId());
        }
    }
    // fetch the sheet you created and edit it.
    $service = new Google_Service_Sheets($client);
    $sheet = $service->spreadsheets->get($res->getId());
    
    print "Fetched sheet with name: " . $sheet->getSpreadsheetUrl() . "\n";
    

提交回复
热议问题