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
如果我用纯文本替换单元格的内容,那么一切正常。我只有下拉菜单有问题。
是否可以从 Apps 脚本获取 Google 文档中下拉菜单的值?
最佳答案
我相信你的目标如下。
- 您想检索表格单元格的值。
- 表格单元格的值是智能芯片的下拉列表。
问题和解决方法:
遗憾的是,目前阶段,似乎没有Google Apps Script内置的直接获取智能芯片下拉列表值的方法。当使用 getType()
时,返回 UNSUPPORTED
正如您在评论中已经提到的那样。而且,即使使用 Google Docs API,也会返回 "content": "\n",
。在这种情况下,我想建议将此报告给 Google 问题跟踪器作为 future 的请求。
针对以上情况,我想提出一个workaround。在此解决方法中,Google 文档被转换为 DOCX 数据。并且,DOCX 数据被转换为 Google 文档。通过这种转换,可以检索智能芯片的文本。当这个流程反射(reflect)在脚本中时,它变成如下。
示例脚本:
请将以下脚本复制并粘贴到 Google 文档的脚本编辑器中。而且,please enable Drive API at Advanced Google services .
function myFunction() {
const doc = DocumentApp.getActiveDocument();
const id = doc.getId();
const url = "https://docs.google.com/feeds/download/documents/export/Export?exportFormat=docx&id=" + id;
const blob = UrlFetchApp.fetch(url, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } }).getBlob();
const tempFileId = Drive.Files.insert({ title: "temp", mimeType: MimeType.GOOGLE_DOCS }, blob).id;
const tempDoc = DocumentApp.openById(tempFileId);
const table = tempDoc.getBody().getTables()[0];
for (let r = 0; r < table.getNumRows(); r++) {
const row = table.getRow(r);
for (let c = 0; c < row.getNumCells(); c++) {
const cell = row.getCell(c);
console.log({ row: r, col: c, text: cell.getText() });
}
}
// DriveApp.getFileById(tempFileId).setTrashed(true); // If you want to delete the tempolary document, please use this.
// DriveApp.createFile(); // This is used for automatically detecting the scope by the script editor.
}
- 运行此脚本时,可以检索具有智能芯片下拉列表的表格的文本。
测试:
当此脚本针对上述文档进行测试时,得到以下结果。
{ row: 0, col: 0, text: 'sample1' }
{ row: 0, col: 1, text: 'sample2' }
{ row: 0, col: 2, text: 'sample3' }
{ row: 1, col: 0, text: 'sample3' }
{ row: 1, col: 1, text: 'sample2' }
{ row: 1, col: 2, text: 'sample1' }
备注:
- 当然,我认为通过解析 DOCX 数据,您还可以从表中检索值。但是,我认为当可以使用文档服务(DocumentApp)时,使用它时,脚本会更简单。因此,我建议从 DOCX 转换为文档。
关于google-apps-script - 如何在 Apps 脚本中获取 Google 文档中下拉菜单的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72914087/