Google 工作表 API 中是否有访问脚本编辑器的方法?

Is there a way in the Google Sheets API to access the script editor?

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

如@Tanaike 所述,您可以使用 Apps Script API to add container-bound script

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

做什么:

  1. 创建一个 container-bound script using projecs.create 方法。

To set a container-bound script, you need to assign the spreadsheet file id to the parentId parameter

示例请求正文:

{
  "title": "new",
  "parentId": "spreadsheet file id"
}
  1. project response body of projecs.create方法中获取新创建的container-boundscript 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. 创建一个 standalone script 将包含您的自定义函数。
  2. 使用projects.getContent which will return a content resource
  3. 获取新创建的独立脚本项目内容

scriptId can be seen in your standalone script project under File -> Project Properties

  1. 创建一个 container-bound script using projecs.create 方法。

To set a container-bound script, you need to assign the spreadsheet file id to the parentId parameter

示例请求正文:

{
  "title": "new",
  "parentId": "spreadsheet file id"
}
  1. project response body of projecs.create方法中获取新创建的container-bound脚本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返回的content resource作为请求体。请务必根据步骤 4 中获取的新创建的绑定脚本 ID 替换脚本 ID。


示例独立脚本:

解决方法的示例结果:


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