首页 > 解决方案 > 创建一个 Table 对象并稍后附加它

问题描述

您知道如何在普通的 Web DOM 中创建一个 HTML 元素,然后将其添加到 DOM 中吗?

我想在 Google Apps Script 中做同样的事情,特别是对于 Google Docs。也就是说,我想创建Table对象,我们称之为table,而不使用Body.appendTable(). 然后稍后我想在他们的 API 中添加 -- 这确实Body.appendTable(table)存在。

问题是,我没有看到任何类似createTable()的方法。

我试过的

显然,简单地使用new也不起作用:

var table = new Table();
var table = new Document.Table();
var table = new GoogleAppsScript.Document.Table();

各自的结果是:

ReferenceError: "Table" is not defined.
ReferenceError: "Document" is not defined.
ReferenceError: "GoogleAppsScript" is not defined.

(我根据https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/google-apps-script/google-apps-script.document.d.ts尝试了最后一个。)

或者,如果我知道Table界面的路径,它可能会起作用。不过,也不是这样:

var table = new DocumentApp.Document.Table();

...因为这会产生:

TypeError: Cannot read property "Table" from undefined.

(这是有道理 DocumentApp的。没有Document钥匙。)

动机:

我知道我可以创建一个临时文档,然后向其中添加一个临时表,然后将其删除。

但这意味着脚本可能在任何地方死亡,用户都必须自己手动清理这个临时文档。

标签: google-apps-scriptgoogle-docs-api

解决方案


您可以创建一个二维数组var table =[[]]。然后根据需要进行修改。Body.appendTable(array)接受一个字符串数组。

或者,Body.appendTable()返回一个表对象,您可以稍后对其进行修改/移动。


推荐阅读