【问题标题】:Unable to access .docx file in Google Docs Add-on无法访问 Google Docs Add-on 中的 .docx 文件
【发布时间】:2022-01-04 10:43:33
【问题描述】:

我正在使用 Appsscript 开发一个 Google Docs 插件,它会读取 Google Docs 的正文并将其显示在插件 UI 中。

要访问 Google 文档,我使用以下代码:

var doc = DocumentApp.getActiveDocument();
var body = doc.getBody().getText();

代码是 Google Docs 文件的工作文件。

然后,我尝试读取 .docx 文件的文本或正文,但出现以下异常:

异常:文档不可访问。请稍后再试。 Exception Picture

我查看了 StackOverflow 上提供的各种解决方案,但无法获得解决方案。 StackOverflow 上的答案说要将 .docx 文件转换为 doc 文件。但是,我不能这样做,因为我无法获取打开文档的“ID”。

如果有人建议我如何获取打开的文档的 ID 或如何从浏览器 URL 获取文档的 ID 或如何解决此异常,我将不胜感激。

提前致谢。

【问题讨论】:

  • 无法读取微软文档,需要先转换成谷歌文档。
  • 获取ID,使用DocumentApp.getActiveDocument().getId()
  • 等一下...打开的 .docx 文件似乎根本没有脚本功能imgur.com/Fpmk0ap.png您究竟是如何尝试运行您的代码以及从哪里得到异常消息的?
  • 是的,我需要先将其转换为 Google 文档,但我无法获取文档的 ID。我在getActiveDocument() 方法中遇到错误。 @DarpanSanghavi @Yuri
  • @YuriKhristich 我需要您发布的代码。您能否在此处或在我的电子邮件中提供相同的代码? nowman.work@gmail.com

标签: google-apps-script add-on google-workspace-add-ons


【解决方案1】:

如果你有一个 URL,也许你可以通过这种方式获得一个 ID:

var url = 'https://docs.google.com/document/d/1BxECZrrIQpKFJYN5zHUeUDxeEiB8NjEb/edit'

var id = url.split('/')[5]

console.log(id) // output: 1BxECZrrIQpKFJYN5zHUeUDxeEiB8NjEb

然后您可以通过 ID 获取带有DriveApp 的文件并将其转换为 Google doc。新的例子是如何做到的:

Converting MS Word files (saved in Drive) to Google Docs using app script

如果您有 .docx 文件的 URL(我不清楚您的问题),代码可能是这样的:

function main() {
  var url = 'https://docs.google.com/document/d/abcd123456789/edit';
  var id = url.split('/')[5];
  var doc_file = convert_docx_to_google_doc(id);
  var doc = DocumentApp.openById(doc_file.id);
  var text = doc.getBody().getText(); // <--- contents of the doc file is here

  console.log(text);

  DriveApp.getFileById(doc_file.id).setTrashed(true); // delete the doc file
}


// you need to enable Advanced Drive API Service

function convert_docx_to_google_doc(id) {
  var docx = DriveApp.getFileById(id);
  var folder = docx.getParents().next();
  
  var google_doc = Drive.Files
    .insert(Drive.newFile(), docx.getBlob(), {convert:true});
  
  // it saves the file next to the original one in the same folder
  // it's not necessary if you don't need the file
  DriveApp.getFileById(google_doc.id)
    .setName(docx.getName().replace(/\.docx$/,'')).moveTo(folder);

  return google_doc; // return the google doc file
}

【讨论】:

  • 我没有 URL,也找不到从 Docs Add-on 获取 URL 的任何方法。如果您能建议我一种获取 .docx 文件的 URL 或 ID 的方法,将会很有帮助。 @尤里
  • 您是否在 Google Doc App 的浏览器中将 .docx 作为打开的文档?你是怎么打开的?
  • .docx 文件在“Google Docs App”中打开。这是共享文件,有人与我共享。我正在开发扩展 Google Docs 的工作区插件。 @尤里
  • 供参考。我在上面的主要问题中添加了一张图片。请检查一下。 @尤里
  • docx的打开过程到底是怎样的?请描述步骤。
猜你喜欢
  • 1970-01-01
  • 2021-04-30
  • 2021-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
  • 1970-01-01
相关资源
最近更新 更多