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

2024-04-17

我想将新数据添加到工作表的开头(开头)。所以我必须在工作表中添加一个新的 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

Thanks.

更新: 这是我发现的

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

我相信电子表格 API 不可能做到这一点。我一直在研究这种可能性,但到目前为止我还不知道如何做到这一点。有一个替代解决方案,但要求您使用Google Apps 脚本执行 API https://developers.google.com/apps-script/guides/rest/api。如果解决方案合适,请随时实施。按着这些次序:

  1. 创建一个新的电子表格并将其命名为您想要的名称。
  2. Fill out the spreadsheet so it looks the same as the image below enter image description here
  3. 转到“工具 > 脚本编辑器”打开脚本编辑器
  4. Name the project anything you want as you see in the image below enter image description here
  5. 删除“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. Now, go to the API manager, select your project and enable the API, like in the image below enter image description here

  7. Go to your project settings and copy the Project Number, as in the image below enter image description here

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

  9. Paste the project number in the field that reads "Enter Project Number here" and then click on "Set Project". See image below. enter image description here

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

  11. Inside the project editor, go to "Publish > Deploy as API Executable". Type a version and click on "Deploy". See image below enter image description here

  12. It will show you a couple more of info messages and then you should see this: 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] /cdn-cgi/l/email-protection"),
            array("[email protected] /cdn-cgi/l/email-protection"),
            array("[email protected] /cdn-cgi/l/email-protection"),
            array("[email protected] /cdn-cgi/l/email-protection")
        );
    
        $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. Run the PHP script and then look at the result in your Spreadhsheet. You should see as below. enter image description here

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Google 电子表格中插入列? 的相关文章

随机推荐

  • 从 Storyboard 转到 XIB

    我有一个故事板视图控制器 它是我的应用程序中的第一个屏幕 该应用程序的其余部分是使用 xib 设计的 我想从故事板 VC 中的按钮转到 XIB 文件 我知道如何从 xib 到故事板执行此操作 但是这个怎么样 提前致谢 从 xib 到故事板
  • 初始化顺序问题

    给出代码示例 class B Some contents class C private B b class A private B b C c 类 C 有一个对 b 的引用 因此需要用它来初始化 类 A 包含 B 的实例和 C 的实例 我
  • Facebook javascript API 中的分页是如何工作的?

    我正在尝试使用 javascript sdk 恢复我的 Facebook 新闻源中上周的帖子 我能够获得第一页 但随后 我不知道如何继续迭代其他页面 我用下面的代码尝试过 loadPosts bind click function FB a
  • undefined 不是一个函数(评估属性[typeof Symbol === "function"?Symbol.iterator:"@@iterator"]()') React Native

    以前运行良好 但在更新一些项目依赖项后突然出现此错误 它来自渲染的组件slate js对象 我不是渲染编辑器而是渲染文本 我读到这个错误可以通过更新来解决babel preset react native 但我的已经是最新的了 我也导入过b
  • 如何在 Mac OS X 上以 root 身份运行脚本? [关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 我应该在 Mac OS X 终端上输入什么才能以 root 身份运行脚本 与任何基于 UNIX 的环境一样 您可以使用sudo http xkcd c
  • SVG 渐变颜色

    Hi I m working with SVG here I trying to add the gradient to SVG like this 白色和灰色渐变 但我无法实现所需的输出 谁能指出我正确的方向
  • 如何在引导日期选择器中突出显示特定日期?

    我正在使用引导日期选择器 我需要突出显示一些随机日期 例如 我需要突出显示 1 3 8 20 21 16 26 30 等日期 您能告诉我如何在引导日期选择器中突出显示这些随机日期吗 根据 Amphetamachine 的建议在 bootst
  • 信任 Google API 响应对象和所有权

    我已经在我的网络应用程序中成功实现了 Google Login 使用适用于客户端 Web 应用程序的 OAuth 2 0 https developers google com identity protocols OAuth2UserAg
  • 如何在 Python 中运行 .exe 文件

    我正在尝试在 python2 7 中运行 exe 文件 我已经尽了一切努力来搜索它 这是我尝试过的一些代码 subprocess Popen r C Programs Files Internet Explorer iexplore exe
  • 调试时 VS2012 的 VSIX 扩展未运行

    我在 Visual Studio 2012 中创建了一个新的 VSIX 扩展项目 并编写了一个 MEF 分类器 作为测试 该分类器应该简单地突出显示 mylang文件 以下是我的 NET 4 5 代码的相关部分 internal stati
  • 如何通过 powershell 或 C# 使用本地 IP 远程更新 azure webapp 防火墙

    如何使用本地 PC IP 地址远程更新我的 azure webapp 防火墙 以便通过 powershell 或 C 进行管理 我已经查看了文档 但我只能从实际服务器本身找到如何操作 而不能远程操作 我可以让 Visual Studio 弹
  • 可绘制资源中带有形状的文本

    我可以在可绘制资源中创建文本形状吗 我在谷歌上搜索了很多 但什么也没找到 这是我的绘图文件
  • 退出和中止有什么区别?

    The abort http ruby doc org core 2 1 1 Kernel html method i abort文件说abort will 通过调用 Kernel exit false 立即有效地终止执行 立即 到底是什么
  • 如何根据内容调整QTableView的高度?

    在我的布局中 动态生成的 QTableView 似乎已调整大小以仅显示一行 我想让表视图的容器有一个滚动条 而不是单个表视图 它应该显示完整的内容 显然 Qt 没有为此内置任何东西 您需要手动计算和设置大小 这就是我垂直调整大小的方法 Qt
  • XMLSerializer.Serialize 上的 .NET OutOfMemoryException

    我有一个网站 每当它到达我的代码中的以下位置时 就会抛出 OutOfMemoryException XmlSerializer xs new XmlSerializer t xoverrides 看到只有在网络服务器上时才会发生这种情况 我
  • 使用 Thrift 通过共享内存进行 IPC 通信

    我找不到关于如何使用 apache thrift 通过共享内存进行 ipc 通信的足够示例 我的目标是在 thrift 的帮助下序列化现有的类 然后通过共享内存发送到另一个进程 在该进程中我在 thrift 的帮助下再次反序列化它 现在我正
  • 如何循环访问 IP 地址范围?

    我想在 IP 地址范围上执行一组网络任务 一旦范围大于 C 类网络 我就无法枚举该范围内的所有主机 我希望能够使用网络掩码迭代网络的所有主机255 255 240 0 From 192 168 0 100 To 192 168 10 100
  • LinqToExcel:Excel 列中的不同值

    对于各位专家来说 这可能是一件非常简单的事情 但我对 C 4 和 INTEROP 并不熟悉 因此 我很困惑 这是我的问题 我有一个包含重复数据的 Excel 列 我想将其修剪为仅具有唯一值 数据如下所示 ColA ColB 10 Adam
  • 角度表单验证 ng-disabled 不起作用

    我正在尝试在我的博客文章表单中使用角度表单验证 更具体地说是禁用 ng 的表单 由于某些原因 我无法弄清楚提交按钮没有被禁用 除非所有三个输入字段都有效 否则它应该被禁用 谢谢您的帮助 这是我的博客模板 div div class cont
  • 如何在 Google 电子表格中插入列?

    我想将新数据添加到工作表的开头 开头 所以我必须在工作表中添加一个新的 A1 列 但我找不到任何 PHP 的 API 示例 现在我用这个附加数据 body new Google Service Sheets ValueRange value