如何在 Apps 脚本中获取 Google 文档中下拉列表的值?

Mar*_*tin 4 google-docs google-apps-script

Google 文档现在支持下拉输入 ( Insert > Dropdown)。我正在使用 Apps 脚本访问 Google 文档,并且想要获取下拉列表的值。

我已阅读Get Google "pills" value as Plain text from Google docs with Google Apps Script,但不幸的是此解决方案不起作用。

但是,当在我的 Apps 脚本中获取该元素时,该元素似乎不受支持。

const statusCell = table.getRow(1).getCell(1);
const p = statusCell.getChild(0).asParagraph();
const c = p.getChild(0);
console.log("---> " + c);
console.log("tpe: " + c.getType());
// ---> UnsupportedElement
// tpe: UNSUPPORTED
Run Code Online (Sandbox Code Playgroud)

如果我用纯文本替换单元格的内容,那么一切正常。我只遇到下拉菜单的问题。

是否可以从 Apps 脚本获取 Google 文档中下拉列表的值?

Tan*_*ike 6

我相信您的目标如下。

\n
    \n
  • 您想要检索表格单元格的值。
  • \n
  • 表格单元格的值是智能芯片的下拉列表。
  • \n
\n

问题和解决方法:

\n

不幸的是,现阶段Google Apps Script似乎还没有内置方法可以直接检索智能芯片下拉列表的值。当getType()使用时,UNSUPPORTED会返回,正如您在评论中已经提到的那样。而且,即使使用 Google Docs API,"content": "\xee\xa4\x87\\n",也会返回。在这种情况下,我建议将此问题报告给 Google 问题跟踪器作为未来的请求。

\n

针对以上情况,我想提出一个解决方法。在此解决方法中,Google 文档将转换为 DOCX 数据。并且,DOCX 数据被转换为 Google 文档。通过这种转换,可以检索智能芯片的文本。当这个流程反映在脚本中时,就会变成如下所示。

\n

示例脚本:

\n

请将以下脚本复制并粘贴到 Google 文档的脚本编辑器中。并且,请在高级 Google 服务中启用 Drive API

\n
function myFunction() {\n  const doc = DocumentApp.getActiveDocument();\n  const id = doc.getId();\n  const url = "https://docs.google.com/feeds/download/documents/export/Export?exportFormat=docx&id=" + id;\n  const blob = UrlFetchApp.fetch(url, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } }).getBlob();\n  const tempFileId = Drive.Files.insert({ title: "temp", mimeType: MimeType.GOOGLE_DOCS }, blob).id;\n  const tempDoc = DocumentApp.openById(tempFileId);\n  const table = tempDoc.getBody().getTables()[0];\n  for (let r = 0; r < table.getNumRows(); r++) {\n    const row = table.getRow(r);\n    for (let c = 0; c < row.getNumCells(); c++) {\n      const cell = row.getCell(c);\n      console.log({ row: r, col: c, text: cell.getText() });\n    }\n  }\n\n  // DriveApp.getFileById(tempFileId).setTrashed(true); // If you want to delete the tempolary document, please use this.\n  // DriveApp.createFile(); // This is used for automatically detecting the scope by the script editor.\n}\n
Run Code Online (Sandbox Code Playgroud)\n
    \n
  • 运行此脚本时,可以检索具有智能芯片下拉列表的表格文本。
  • \n
\n

测试:

\n

在此输入图像描述

\n

当这个脚本对上述文档进行测试时,得到以下结果。

\n
{ row: 0, col: 0, text: \'sample1\' }\n{ row: 0, col: 1, text: \'sample2\' }\n{ row: 0, col: 2, text: \'sample3\' }\n{ row: 1, col: 0, text: \'sample3\' }\n{ row: 1, col: 1, text: \'sample2\' }\n{ row: 1, col: 2, text: \'sample1\' }\n
Run Code Online (Sandbox Code Playgroud)\n

笔记:

\n
    \n
  • 当然,我认为通过解析DOCX数据,您也可以从表中检索值。但是,我想,当可以使用文档服务(DocumentApp)时,使用它时,脚本会更简单。所以,我建议从DOCX转换为Document。
  • \n
\n