Как получить данные электронной таблицы Google из идентификатора листа (из gid) вместо идентификатора таблицы в php - PullRequest
0 голосов
/ 08 февраля 2019

У меня есть одна электронная таблица, и она содержит несколько листов в формате табуляции.

Мой код получает только первые данные таблицы, а у меня есть массив, содержащий все идентификаторы листа.

Мойпроблема в том, как мне получить все данные листа, так как у меня есть уникальный gid для всех.

Здесь SpreadSheet Id одинаков для всех листов, отличается только идентификатор листа (gid).

Iмного искал, я получил только данные из таблицы Id.

<?php
require __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Sheets API PHP Quickstart');
    $client->setScopes(Google_Service_Sheets::SPREADSHEETS_READONLY);
    $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;
}


// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Sheets($client);



$spreadsheetId = 'xxxxxxx--tttttttttttL_ttthhdfhdhshshshshhshsh-84';///random spread sheet id
$range = 'A:G';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();//getting first sheet data only


    $sheet_id = array();    
    // Load Google API library and set up client
    // You need to know $spreadsheetID (can be seen in the URL)
    $sheetService = $service;  
    $spreadSheet = $sheetService->spreadsheets->get($spreadsheetId);
    $sheets = $spreadSheet->getSheets();

    foreach($sheets as $sheet) {

    $sheet_id[] = $sheet->properties->sheetId;


    }


 ///$sheet_id   -- it will give all the id of sheets, I have 36 sheets in a single spreadsheet, so it's giving 36 ids in an array format

Любое предложение будет оценено.

Ответы [ 2 ]

0 голосов
/ 14 февраля 2019

После долгих исследований я получил решение и хотел бы опубликовать свое решение.

$client = $this->getClient();
$service = new Google_Service_Sheets($client);

// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/xxxxxx--yyyyyyyyyyyyyy_zzzzzzzzzzzzzzzz/edit

 //

 $spreadsheetId = 'xxxxxx--yyyyyyyyyyyyyy_zzzzzzzzzzzzzzzz';
  $sheet_id = array();    
    // Load Google API library and set up client
    // You need to know $spreadsheetID (can be seen in the URL)
    $sheetService = $service;  
    $spreadSheet = $sheetService->spreadsheets->get($spreadsheetId);
    $sheets = $spreadSheet->getSheets();

    foreach($sheets  as  $key=>$sheet) {

    // $sheet_id[$key]['gid'] = $sheet->properties->sheetId;
    // $sheet_id[$key]['title'] = $sheet->properties->title;


$range = $sheet->properties->title.'!A:G';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values[$sheet->properties->title] = $response->getValues();


    }

Здесь у нас есть только идентификатор таблицы, из которого мы можем получить заголовки всехлистов и из заголовка мы получим все детали:

$ range = $ sheet-> properties-> title. '! A: G';/// зациклить заголовок и получить значение всего листа

0 голосов
/ 13 февраля 2019

Я могу помочь вам с javascript - вам придется разработать любой php для себя.

Если у вас есть идентификатор листа, то легко вернуться к названию листа, а затемчтобы "получить" лист по имени.

1 - getSheets () - получает все листы в текущей электронной таблице.Отсюда вы можете найти имя листа и идентификатор каждого листа.

2 - Идентификатор получается с помощью getSheetId () - возвращает идентификатор листа, который вы можете сравнить ствой список

3 - имя листа получается с помощью getSheetName () - возвращает имя листа, которое можно использовать в методе getSheetByName.

4 - getSheetByName (name) - позволяет вам вернуть определенный лист с заданным именем.

В следующем примере получается объект, содержащий sheetIDs для ActiveSpreadsheet.Он проходит по этим листам, захватывая соответствующие SheetName и SheetID.Используя вложенный цикл, он просматривает мой список SheetID и сравнивает SheetID.Если SheetID совпадает, то код использует SheetName для доступа к листу по имени.Если идентификаторы SheetID не совпадают, они продолжаются через цикл nexted и так далее.

Я оставил несколько команд Logger в коде, чтобы OP мог проверять детали проверки в удобных точках в сценарии.

function so54586032() {

  // set up the spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // this is the sheet where I listed my SheetIDs
  var mainsheet = ss.getSheetByName("54586032");

  // calculate the number of IDs 
  var Avals = mainsheet.getRange("A1:A").getValues();
  var Alast = Avals.filter(String).length;
  //Logger.log("DEBUG: Number of SheetIDs in my list: " + Alast); //DEBUG

  // get the list of all sheets in this spreadsheet
  var sheets = ss.getSheets();
  //calculate the number of sheets
  var sheetslength = sheets.length
  //Logger.log("DEBUG: Number of actual sheets in this spreadsheet: " + sheetslength); //DEBUG

  // LOOP through the actual sheets
  for (var i = 0; i < sheets.length; i++) {
    //Logger.log("DEBUG: i: " + i + ", sheet name: " + sheets[i].getName() + ", sheet ID: " + sheets[i].getSheetId()); // DEBUG

    // loop through the list of sheets 
    for (var z = 0; z < Alast; z++) {
      //Logger.log("DEBUG: z: " + z + ", sheet ID: " + Avals[z][0]); //DEBUG

      // test if this shhetID equals the next number in my list
      if (sheets[i].getSheetId() == Avals[z][0]) {
        //Logger.log("DEBUG: Match: " + sheets[i].getSheetId() + " to " + Avals[z][0]); //DEBUG
        // do something
      } else {
        //Logger.log("DEBUG: No Match"); //DEBUG
      };
    }

  }

}

Мой список, содержащий соответствующие SheetID
List of Sheet IDs

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...