如何在 Google 文档中选择复选框?

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

我是 Google Apps 脚本的新手,目前正在开发一个项目,我需要使用 Google Apps 脚本选择 Google 文档中的所有复选框,目的是确定它们是否已被选中,我将使用此信息来填充外部数据库。然而,我找到的大多数解决方案都与 Google Sheets 有关,而不是 Google Docs。

我尝试使用

getListItems()
方法来检索文档中的列表项,希望它也包含复选框。但是,它似乎只选择项目符号点,而不选择复选框。当我运行代码时,我在尝试访问
"TypeError: Cannot read properties of null (reading 'toString')"
的行上遇到错误
getGlyphType()

这是我尝试过的代码片段:

function getCheckboxValue() {
  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();

  const listItems = body.getListItems()
  
  for(let item of listItems){
    console.log(item.getGlyphType().toString())
  }
}

这就是返回的内容

4:47:46 PM  Notice  Execution started
4:47:46 PM  Info    BULLET
4:47:46 PM  Info    BULLET
4:47:46 PM  Info    BULLET
4:47:46 PM  Info    BULLET
4:47:46 PM  Info    BULLET
4:47:47 PM  Error   
TypeError: Cannot read properties of null (reading 'toString')
getCheckboxValue    @ Code.gs:8

我还添加了文档布局的图像以提供视觉表示:
Sample Doc with Bullets and Checkboxes

有没有办法使用 Google Apps 脚本选择 Google Docs 文档中的所有复选框?如果是这样,我该如何修改我的代码来实现这一目标?任何指导或替代方法将不胜感激。

javascript google-apps-script checkbox google-docs listitem
1个回答
-1
投票

我的发现表明只有复选框 ListItem 的

getGlyphType()
返回
null

enter image description here

因此,以下代码片段对我来说效果很好。但当然,这看起来并不理想

var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var list_items = body.getListItems();
  var checkboxItems = [];
  
  for (var i = 0; i < list_items.length; i++) {
    if (list_items[i].getGlyphType() == null) {
      checkboxItems.push(list_items[i]);
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.