2017-07-31 92 views
2

我想添加新的数据到工作表的开始(开始)。所以我必须添加一个新的列A1到工作表。但是我找不到任何使用PHP的API示例。如何在Google电子表格中插入一列?

现在我这个附加数据:

$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 */ 

回答

0

我认为这是不可能的电子表格API。我一直在研究这种可能性,到目前为止我看不到如何做到这一点。有一种替代解决方案,但要求您使用Google Apps Script Execution API。如果解决方案合适,请随时实施。请按照下列步骤操作:

  1. 创建一个新的电子表格并将其命名为任何您想要的名称。
  2. 填写电子表格,所以它看起来下同 enter image description here
  3. 打开脚本编辑器中的图像进入“工具>脚本编辑器”
  4. 名称你想要的项目什么,你在下面的图片中看到的 enter image description here
  5. 删除everyting你有内部 “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); 
    
    } 
    
  6. 现在,到了API人几岁,选择您的项目并启用该API,就像下面的图片 enter image description here

  7. 转到您的项目设置和图像复制项目编号,如下 enter image description here

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

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

  10. 您会看到一个确认窗口。确认更改并等待它完成。

  11. 在项目编辑器中,转到“Publish> Deploy as API Executable”。输入一个版本并点击“部署”。见下面 enter image description here

  12. 像它会告诉你的信息的消息一对夫妇,然后你会看到如下: enter image description here

  13. 请复制当前API ID,然后请务必保存项目变化。

  14. 创建一个新的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("[email protected]"), 
         array("[email protected]"), 
         array("[email protected]"), 
         array("[email protected]") 
        ); 
    
        $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)); 
    
        } 
    
    } 
    
    ?> 
    
  15. 运行PHP脚本,然后看看结果就在你的Spreadhsheet。你应该看到如下。 enter image description here

正如你可以看到,有一列被插在开头和值分别填写了。我希望这对你或其他人有帮助。

相关问题