我需要通过脚本将一些表插入Google文档,然后定期仅更新通过脚本插入的表。我不想修改没有脚本插入的其他表...只需更改脚本插入的那些表。但是,我看不到为每个表放置属性或唯一名称的方法。有办法吗?
var table = body.insertTable(insertPoint, [[row.join("")]]);
我相信您的目标如下。
var table = body.insertTable(insertPoint, [[row.join("")]]);
放置桌子。为此,这个答案如何?
遗憾的是,在当前阶段,Google文档中的表格不能具有唯一ID。这样,无法直接检索特定表。对于您的情况,为了实现上述目标,在此答案中,我想提出以下解决方法。
function putTable() {
const documentId = "###"; // Please set Document ID.
const uniqueIdOfTable = "tableId1"; // Please set the unique table ID. In this sample, "tableId1" is used.
const insertPoint = 1; // In this sample, "1" is the minumum size.
const row = ["a1", "b1", "c1"];
const body = DocumentApp.openById(documentId).getBody();
const table = body.insertTable(insertPoint, [[row.join("")]]);
const text = table.getPreviousSibling().asParagraph().appendText("\n" + uniqueIdOfTable);
text.setFontSize(1).setForegroundColor(text.getBackgroundColor() || "#ffffff");
}
tableId1
的唯一ID。并且唯一的ID被字体大小和字体颜色隐藏。function getTable(documentId, uniqueIdOfTable) {
const body = DocumentApp.openById(documentId).getBody();
const index = body.getChildIndex(body.findText(uniqueIdOfTable).getElement().getParent());
const element = body.getChild(index + 1);
return element.getType() === DocumentApp.ElementType.TABLE ? element.asTable() : null;
}
// Please run this function.
function main() {
const documentId = "###"; // Please set Document ID.
const uniqueIdOfTable = "tableId1"; // Please set the unique table ID. In this sample, "tableId1" is used.
const table = getTable(documentId, uniqueIdOfTable);
console.log(table.editAsText().getText())
}
main()
时,将使用tableId1
的唯一ID检索表。在这种情况下,getTable()
返回表对象。