首页 > 解决方案 > Google Sheets API 中是否有访问脚本编辑器的方法?

问题描述

例如,我想编写一个(例如 Python)程序来生成 Google 表格,然后将一些自定义 .gs 代码写入附加到该表格的 Apps 脚本中,然后使用定义的公式将值写入表格本身应用脚本。我目前做的是使用工具>脚本编辑器,然后手动复制粘贴相关的应用程序脚本代码。

标签: google-sheets-api

解决方案


正如@Tanaike 所提到的,您可以使用Apps Script API添加容器绑定脚本

(选项 1:在脚本内容中手动编写函数)

该怎么办:

  1. 使用projecs.create方法创建一个容器绑定脚本。

要设置容器绑定脚本,您需要将电子表格文件 id 分配给parentId参数

样品请求正文:

{
  "title": "new",
  "parentId": "spreadsheet file id"
}
  1. 在projecs.create方法的项目响应体中获取新创建的容器绑定脚本 id 。

示例响应正文:

{
  "scriptId": "newly created script id",
  "title": "new",
  "parentId": "spreadsheet file id",
  "createTime": "2020-12-25T23:33:48.026Z",
  "updateTime": "2020-12-25T23:33:48.026Z"
}
  1. 使用projects.updateContent方法更新新创建的绑定脚本的内容并包含您的函数。

样品请求正文:

{
  files: [{
      name: 'hello',
      type: 'SERVER_JS',
      source: 'function helloWorld() {\n  console.log("Hello, world!");\n}'
    }, {
      name: 'appsscript',
      type: 'JSON',
      source: "{\"timeZone\":\"America/New_York\",\"" +
      "exceptionLogging\":\"CLOUD\"}"
    }]
}

(选项 2:复制现有脚本并将其粘贴为绑定脚本)

  1. 创建一个包含您的自定义函数的独立脚本。
  2. 使用projects.getContent获取新创建的独立脚本项目内容,这将返回一个内容资源

scriptId可以在文件 -> 项目属性下的独立脚本项目中看到

  1. 使用projecs.create方法创建一个容器绑定脚本。

要设置容器绑定脚本,您需要将电子表格文件 id 分配给parentId参数

样品请求正文:

{
  "title": "new",
  "parentId": "spreadsheet file id"
}
  1. 在projecs.create方法的项目响应体中获取新创建的容器绑定脚本 id 。

示例响应正文:

{
  "scriptId": "newly created script id",
  "title": "new",
  "parentId": "spreadsheet file id",
  "createTime": "2020-12-25T23:33:48.026Z",
  "updateTime": "2020-12-25T23:33:48.026Z"
}
  1. 使用projects.updateContent方法更新新创建的绑定脚本的内容。

将步骤 2 中返回的内容资源用作请求正文。确保根据步骤 4 中获取的新创建的绑定脚本 id 替换脚本 id。


示例独立脚本:

在此处输入图像描述

变通办法的示例结果:

在此处输入图像描述


您现在可以在 Google 表格中使用自定义功能

在此处输入图像描述


推荐阅读