使用google-api-php-client(第2版,无需作曲家)更新特定的Google电子表格中的值

时间:2018-11-19 20:24:08

标签: php mysql google-api-php-client worksheet

对于以下代码,我正在使用https://github.com/googleapis/google-api-php-client库(客户要求-此库必须在没有作曲家的情况下使用)。

所以现在要满足要求--我的客户想要将数据行从mysql更新到google spreadsheed(将是任何工作表,例如工作表1或工作表2)。

我也面临发布多个行和单元格的问题。

db.php code
<?php
$servername = "localhost";
$username = "newuser";
$password = "password";
$db = "google_sheet";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM   table2";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    $rowData = mysqli_fetch_all($result);
} else {
    echo "No records in table";
}

/* $rowData contains below array 
array (size=4)
  0 => 
    array (size=3)
      0 => string 'XXX' (length=3)
      1 => string 'Developer' (length=9)
      2 => string 'IT' (length=2)
  1 => 
    array (size=3)
      0 => string 'YYY' (length=3)
      1 => string 'QA' (length=2)
      2 => string 'IT' (length=2)
  2 => 
    array (size=3)
      0 => string 'ZZZ' (length=3)
      1 => string 'Developer' (length=9)
      2 => string 'IT' (length=2)
  3 => 
    array (size=3)
      0 => string 'AAA' (length=3)
      1 => string 'Developer' (length=9)
      2 => string 'IT' (length=2) */

注意-这是我的完整代码,除了凭据和电子表格ID(出于安全原因已更改)。

<?php
//echo phpinfo();
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
include_once "examples/templates/base.php";
require_once 'autoload.php';
include 'db.php';

$client_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'; //Client ID
$service_account_name = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'; //Email Address
$key_file_location = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';

echo pageHeader("Service Account Access");
if (strpos($client_id, "googleusercontent") == false || !strlen($service_account_name) || !strlen($key_file_location)) {
    echo missingServiceAccountDetailsWarning();
    exit;
}

$client = new Google_Client();
$client->setApplicationName("Sheets API Testing");
$service = new Google_Service_Drive($client);


if (isset($_SESSION['service_token'])) {
    $client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
        $service_account_name, array('https://www.googleapis.com/auth/drive', 'https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive.apps.readonly'), $key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();

// Get access token for spreadsheets API calls
$resultArray = json_decode($_SESSION['service_token']);
$accessToken = $resultArray->access_token;

// The file ID was copied from a URL while editing the sheet in Chrome
$fileId = '1JfnVnz8TxxxxxxxxxxxxxxxxxxxxxxxxxxA'; //change for security reasons

function updateFile($service, $fileId, $newTitle, $newDescription, $newMimeType = null, $rowData, $newRevision, $currentRow) {
    try {
        // First retrieve the file from the API.
        $file = $service->files->get($fileId);

        // File's new metadata.
        $file->setTitle($newTitle);
        $file->setDescription($newDescription);
        $file->setMimeType($newMimeType);
        // File's new content.
        //        foreach ($rowData as $row) {
        $additionalParams = array(
            'newRevision' => $newRevision,
            'data' => $rowData,
            'mimeType' => $newMimeType,
            'uploadType' => 'multipart',
            'convert' => true,
        );
        // Send the request to the API.
        $updatedFile = $service->files->update($fileId, $file, $additionalParams);
        return $updatedFile;
        //        }
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

$currentRow = 1;
foreach ($rowData as $row) {
    $responseData = updateFile($service, $fileId, 'Update G Excel', 'Update GG Excel Desc', 'text/csv', $row, true, $currentRow);
    var_dump($responseData);
    $currentRow++;
    die;
}

以上代码仅适用于工作表1的A1单元。我需要更新多个单元和行。但是我没有得到任何有用的文档。任何帮助将不胜感激。

当前输出为-第一页第一行中只有一个单元格被更新。

预期输出为-类似于

Name    Role        Department
XXX     Developer   IT
YYY     QA          IT
ZZZ     Developer   IT
AAA     Developer   IT

0 个答案:

没有答案