使用 Google Apps 脚本从 Google 文档获取 Google "pills" 纯文本值

Get Google "pills" value as Plain text from Google docs with Google Apps Script

我正在尝试提取 Google 文档中新功能的价值:“药丸”(不确定这个名称)。

我正在使用 Google 应用程序脚本解析文档中的 table。当我到达该行时(见图),我得到 null。我不知道我应该如何 运行 将此值作为纯文本获取。

我 运行 在 returns null:

得到的代码
Logger.log(table.getCell(i, 1).getText())
> null

如何才能得到“药丸”的实际价值?

我认为从你提供的图像来看,它是智能芯片,它可能是 Class 日期,而且,它似乎被放入“B”列的单元格中。不幸的是,不能使用 getText() 直接检索。我认为这就是您遇到问题的原因。

但是,2021 年 8 月 23 日添加了 3 个 Class 检索智能芯片的方法。您可以使用这些 Class 方法检索值。如果要检索值,下面的示例脚本怎么样?

示例脚本:

当使用您的示例图片table时,一个简单的示例脚本如下。

const cell = table.getCell(i, 1); // This is from your script.

const p = cell.getChild(0).asParagraph();
const c = p.getChild(0);
if (c.getType() == DocumentApp.ElementType.DATE) {
  const value = c.asDate().getDisplayText();
  console.log(value)
} else if (c.getType() == DocumentApp.ElementType.TEXT) {
  const value = c.asText().getText();
  console.log(value)
}

或者,如果您的单元格有多个段落,您还可以使用以下示例脚本。

const cell = table.getCell(i, 1);  // This is from your script.

for (let j = 0; j < cell.getNumChildren(); j++) {
  const p = cell.getChild(j).asParagraph();
  for (let k = 0; k < p.getNumChildren(); k++) {
    const c = p.getChild(k);
    if (c.getType() == DocumentApp.ElementType.DATE) {
      const value = c.asDate().getDisplayText();
      console.log(value)
    } else if (c.getType() == DocumentApp.ElementType.TEXT) {
      const value = c.asText().getText();
      console.log(value)
    }
  }
}
  • getDisplayText() 更改为 getTimestamp() 时,可以检索 Date 对象而不是字符串值。

参考文献: