如何在Google电子表格中插入列?

时间:2017-07-31 18:28:36

标签: php google-sheets google-api-php-client

我想将新数据添加到工作表的开头(开头)。所以我必须在工作表中添加一个新的列A1。但我找不到PHP的任何API示例。

现在我用这个附加数据:

$body   = new Google_Service_Sheets_ValueRange(['values' => $values]);
$result = $service->spreadsheets_values->append($new_sheet_id, 'A1:E1', $body, $options); // appent the data to the spreadsheet

感谢。

UPD: 这是我找到的

/* insert columns */
$requests = new Google_Service_Sheets_Request(array(
    'insertDimension' => array(
        'range' => array(
            'sheetId' => 0,
            'dimension' => "COLUMNS",
            'startIndex' => 0,
            'endIndex' => 5
        )
    )
));
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array(
    'requests' => $requests
));
$result = $service->spreadsheets->batchUpdate($new_sheet_id, $batchUpdateRequest);
/* insert columns */

1 个答案:

答案 0 :(得分:2)

我认为使用Spreadsheet API是不可能的。我一直在研究这种可能性,到目前为止我看不出怎么做。有一个替代解决方案,但要求您使用Google Apps Script Execution API。如果解决方案合适,请随意实施。请按照以下步骤操作:

  1. 创建一个新的电子表格并将其命名为您想要的任何名称。
  2. 填写电子表格,使其看起来与下图相同 enter image description here
  3. 转到“工具>脚本编辑器”
  4. 打开脚本编辑器
  5. 将项目命名为您想要的任何内容,如下图所示 enter image description here
  6. 删除“Code.gs”中的所有内容并粘贴以下内容:

    function insertColumn(vals) {
    
        var ss = SpreadsheetApp.getActiveSpreadsheet();
        var sheet = ss.getSheets()[0];
    
        // This inserts a column in the first column position
        sheet.insertColumnBefore(1);  
    
        //This set the values in the cells of the first column inserted
        var range = sheet.getRange("A1:A5");
        range.setValues(vals);
    
    }
    
  7. 现在,转到API管理器,选择您的项目并启用API,如下图所示 enter image description here

  8. 转到项目设置并复制项目编号,如下图所示 enter image description here

  9. 返回步骤3中说明并在步骤4中显示的脚本编辑器。单击“资源>云平台项目”

  10. 将项目编号粘贴到“在此输入项目编号”字段中,然后单击“设置项目”。见下图。 enter image description here

  11. 您将看到一个确认窗口。确认更改并等待其完成。

  12. 在项目编辑器中,转到“发布>部署为API可执行文件”。键入一个版本,然后单击“部署”。见下图 enter image description here

  13. 它会显示更多信息,然后您应该看到: enter image description here

  14. 请复制当前API ID ,然后确保保存项目更改。

  15. 创建一个新的PHP文件并粘贴以下内容:

    <?php session_start(); 
    
    //INCLUDE PHP CLIENT LIBRARY
    require_once 'vendor/autoload.php';
    
    //scope required to modify the spreadsheet
    $scopes = array("https://www.googleapis.com/auth/spreadsheets");
    
    // Create client object
    $client = new Google_Client(); 
    $client->setRedirectUri('http://'.$_SERVER['HTTP_HOST'].'/index.php');
    $client->setAuthConfig("client_secret.json");
    $client->setScopes($scopes);
    
    if( isset($_SESSION["access_token"]) && ($_SESSION["access_token"]) ) {
    
        $client->setAccessToken($_SESSION["access_token"]);    
        $service = new Google_Service_Script($client);
    
        //Here goes the script Id you copied on step 13
        $scriptId = 'XXX-OROcbUXO78URUxxxLYqFdOk6teXXX';
    
        $values = array( 
            array("Email"),
            array("jonsnow@email.com"),
            array("aryastark@email.com"),
            array("sansastark@email.com"),
            array("cerseilanister@email.com")
        );
    
        $params = array($values);
    
        // Create an execution request object.
        $request = new Google_Service_Script_ExecutionRequest();
        $request->setFunction('insertColumn');
        $request->setParameters($params);
        $request->setDevMode(true); //required to work with parameters
    
        try {
        // Make the API request.
            $response = $service->scripts->run($scriptId, $request);
    
            if ($response->getError()) {
            // The API executed, but the script returned an error.
    
            // Extract the first (and only) set of error details. 
            // The values of this object are the script's 'errorMessage'
            // and 'errorType', and an array of stack trace elements.
            $error = $response->getError()['details'][0];
            printf("Script error message: %s\n", $error['errorMessage']);
    
                if (array_key_exists('scriptStackTraceElements', $error)) {
                    // There may not be a stacktrace if the script didn't start executing.
                    print "Script error stacktrace:\n";
                    foreach($error['scriptStackTraceElements'] as $trace) {
                        printf("\t%s: %d\n", $trace['function'], $trace['lineNumber']);
                    }
                }
    
            } else {
            // The structure of the result will depend upon what the Apps Script
            // function returns.
            $resp = $response->getResponse();    
            var_dump($resp);          
    
            }
        } catch (Exception $e) {
            // The API encountered a problem before the script started executing.
            echo 'Caught exception: ', $e->getMessage(), "\n";
        }    
    
    } else {
    
        if( !isset($_GET["code"]) ){
    
            $authUrl = $client->createAuthUrl();
            header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
    
        } else {
    
            $client->authenticate($_GET['code']);
            $_SESSION['access_token'] = $client->getAccessToken();
    
            $redirect_uri = 'http://'.$_SERVER['HTTP_HOST'] .'/index.php';
            header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    
        }
    
    }
    
    ?>
    
  16. 运行PHP脚本,然后查看Spreadhsheet中的结果。你应该看到如下。 enter image description here

  17. 如您所见,在开头插入了一列,并且也填写了值。我希望这对你或其他人有所帮助。