谷歌表格API -插入一行与PHP


Google Sheets API - Insert a row with PHP

所以我创建了一个电子表格类,它是我在网上找到的几个解决方案的组合,用于使用PHP访问Google Sheets API。它的工作原理。

class Spreadsheet {
    private $token;
    private $spreadsheet;
    private $worksheet;
    private $spreadsheetid;
    private $worksheetid;
    private $client_id = '<client id>';
    private $service_account_name = '<service_account>';  // email address
    private $key_file_location = 'key.p12'; //key.p12
    private $client;
    private $service;
    public function __construct() {
        $this->client = new Google_Client();
        $this->client->setApplicationName("Sheets API Testing");
        $this->service = new Google_Service_Drive($this->client);
        $this->authenticate();
    }
    public function authenticate()
    {
        if (isset($_SESSION['service_token'])) {
            $this->client->setAccessToken($_SESSION['service_token']);
        }
        $key  = file_get_contents($this->key_file_location);
        $cred = new Google_Auth_AssertionCredentials(
            $this->service_account_name,
            array('https://www.googleapis.com/auth/drive', 'https://spreadsheets.google.com/feeds'),            $key
        );
        $this->client->setAssertionCredentials($cred);
        if ($this->client->getAuth()->isAccessTokenExpired()) {
            $this->client->getAuth()->refreshTokenWithAssertion($cred);
        }
        $_SESSION['service_token'] = $this->client->getAccessToken();
        // Get access token for spreadsheets API calls
        $resultArray = json_decode($_SESSION['service_token']);
        $this->token = $resultArray->access_token;
    }
    public function setSpreadsheet($title) {
        $this->spreadsheet = $title;
        return $this;
    }
    public function setSpreadsheetId($id) {
        $this->spreadsheetid = $id;
        return $this;
    }
    public function setWorksheet($title) {
        $this->worksheet = $title;
        return $this;
    }
    public function insert() {
        if (!empty($this->token)) {
            $url = $this->getPostUrl();
        } else {
            echo "Authentication Failed";
        }
    }
    public function add($data) {
        if(!empty($this->token)) {
            $url = $this->getPostUrl();
            if(!empty($url)) {
                $columnIDs = $this->getColumnIDs();
                if($columnIDs) {
                    $fields = '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended">';
                    foreach($data as $key => $value) {
                        $key = $this->formatColumnID($key);
                        if(in_array($key, $columnIDs)) {
                            $fields .= "<gsx:$key><![CDATA[$value]]></gsx:$key>";
                        }
                    }
                    $fields .= '</entry>';
                    $headers = [
                        "Authorization" => "Bearer $this->token", 
                        'Content-Type' => 'application/atom+xml'
                    ];
                    $method = 'POST';
                    $req = new Google_Http_Request($url, $method, $headers, $fields);
                    $curl = new Google_IO_Curl($this->client);
                    $results = $curl->executeRequest($req);
                    var_dump($results);
                }
            }
        }
    }
    private function getColumnIDs() {
        $url = "https://spreadsheets.google.com/feeds/cells/" . $this->spreadsheetid . "/" . $this->worksheetid . "/private/full?max-row=1";
        $headers = array(
            "Authorization" => "Bearer $this->token",
            "GData-Version: 3.0"
        );
        $method = "GET";
        $req = new Google_Http_Request($url, $method, $headers);
        $curl = new Google_IO_Curl($this->client);
        $results = $curl->executeRequest($req);
        if($results[2] == 200) {
            $columnIDs = array();
            $xml = simplexml_load_string($results[0]);
            if($xml->entry) {
                $columnSize = sizeof($xml->entry);
                for($c = 0; $c < $columnSize; ++$c) {
                    $columnIDs[] = $this->formatColumnID($xml->entry[$c]->content);
                }
            }
            return $columnIDs;
        }
        return "";
    }
    private function getPostUrl() {
        if (empty($this->spreadsheetid)){
            #find the id based on the spreadsheet name
            $url = "https://spreadsheets.google.com/feeds/spreadsheets/private/full?title=" . urlencode($this->spreadsheet);
            $method = 'GET';
            $headers = ["Authorization" => "Bearer $this->token"];
            $req = new Google_Http_Request($url, $method, $headers);
            $curl = new Google_IO_Curl($this->client);
            $results = $curl->executeRequest($req);          
            if($results[2] == 200) {
                $spreadsheetXml = simplexml_load_string($results[0]);
                if($spreadsheetXml->entry) {
                    $this->spreadsheetid = basename(trim($spreadsheetXml->entry[0]->id));
                    $url = "https://spreadsheets.google.com/feeds/worksheets/" . $this->spreadsheetid . "/private/full";
                    if(!empty($this->worksheet)) {
                        $url .= "?title=" . $this->worksheet;
                    }
                    $req = new Google_Http_Request($url, $method, $headers);
                    $response = $curl->executeRequest($req);
                    if($response[2] == 200) {
                        $worksheetXml = simplexml_load_string($response[0]);
                        if($worksheetXml->entry) {
                            $this->worksheetid = basename(trim($worksheetXml->entry[0]->id));
                        }
                    }
                }
            }           
        }

        if(!empty($this->spreadsheetid) && !empty($this->worksheetid)) {
            return "https://spreadsheets.google.com/feeds/list/" . $this->spreadsheetid . "/" . $this->worksheetid . "/private/full";
        }
        return "";
    }
    private function formatColumnID($val) {
        return preg_replace("/[^a-zA-Z0-9.-]/", "", strtolower($val));
    }
}

然后使用这个测试php文件向电子表格添加行:

$Spreadsheet = new Spreadsheet();
$Spreadsheet->
    setSpreadsheet("test spreadsheet")->
    setWorksheet("Sheet1")->
    add(array("name" => "Cell 1", "email" => "Cell 2"));

有了这个,我可以删除一行/更新一行和追加一行。然而,我需要它的主要原因是插入一行。有人想出办法了吗?任何语言都可以,尽管我更喜欢php解决方案。

您可以使用HTTPS GET或POST请求从PHP调用Apps Script独立脚本。PHP可以进行GET或POST请求,而Apps Script显然可以使用SpreadsheetApp服务在任何地方插入行。你可能还想在Apps Script代码中使用Content Service来获得代码完成的返回确认。

您可能希望使用POST请求以获得更好的安全性。同样,你可以使用Apps Script作为PHP和电子表格之间的中介。Apps脚本文件中的doPost()将需要一个事件处理程序,通常分配给字母"e":

doPost(e) {
  //Get e and retrieve what the code should do
  //Insert the row
};

同样,参见这个答案:

Stackoverflow -从外部URL

调用自定义GAS函数