我如何唯一地标识已插入的表?

问题描述 投票:0回答:1

我需要通过脚本将一些表插入Google文档,然后定期仅更新通过脚本插入的表。我不想修改没有脚本插入的其他表...只需更改脚本插入的那些表。但是,我看不到为每个表放置属性或唯一名称的方法。有办法吗?

var table = body.insertTable(insertPoint, [[row.join("")]]);

google-apps-script google-docs
1个回答
2
投票

我相信您的目标如下。

  • 您要使用Google Apps脚本检索特定表。
  • 您想使用var table = body.insertTable(insertPoint, [[row.join("")]]);放置桌子。
  • 表的位置和顺序已更改。

为此,这个答案如何?

问题和解决方法:

遗憾的是,在当前阶段,Google文档中的表格不能具有唯一ID。这样,无法直接检索特定表。对于您的情况,为了实现上述目标,在此答案中,我想提出以下解决方法。

  • 插入表格后,文本将作为唯一ID添加到表格的上侧。显然,通过将字体颜色修改为与背景颜色相同并将字体大小修改为1,可以隐藏唯一ID。
  • 检索表时,使用唯一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被字体大小和字体颜色隐藏。

用于使用唯一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()返回表对象。

注意:

  • 这是一个简单的示例脚本,用于说明解决方法。因此,请根据您的实际情况对此进行修改。
© www.soinside.com 2019 - 2024. All rights reserved.