You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Docs插件使用Apps Script无法访问.docx文件问题求助

异常原因说明

DocumentApp服务仅支持原生Google Docs格式的文档操作,你打开的.docx格式文件属于第三方格式,未转换为原生格式前无法直接调用getBody()等方法读取内容,就会抛出该不可访问异常。

获取当前打开文档ID的两种方法

  • 服务端直接获取
    你已经通过DocumentApp.getActiveDocument()拿到了当前文档实例,直接调用getId方法即可获取ID,不会触发异常:
var doc = DocumentApp.getActiveDocument();
var currentDocId = doc.getId();
  • 前端从URL提取
    如果需要在插件前端UI中获取ID,可通过父窗口URL匹配提取,Google Docs的URL规则固定为https://docs.google.com/document/d/[文档ID]/xxx,提取代码如下:
// 插件前端JS代码
const docUrl = window.parent.location.href;
const docId = docUrl.match(/\/d\/([a-zA-Z0-9-_]+)/)[1];

异常解决方案

方案1:直接读取docx文本内容(无需转换文件,推荐)

无需转换为原生Gdoc格式,调用Drive API直接导出docx文件为纯文本即可拿到内容,操作步骤:

  1. 在Apps Script编辑器左侧「服务」栏添加「Drive API」服务
  2. 使用如下代码读取内容:
function getDocxContent(docId) {
  return Drive.Files.export(docId, "text/plain");
}

调用该方法传入文档ID即可直接拿到正文内容,不需要生成额外的转换文件,适合仅需读取展示的场景。

方案2:转换为原生Google Docs格式

如果后续还需要对文档做编辑操作,可将docx转换为原生格式,代码如下:

function convertToNativeGdoc(docId) {
  const originalFile = DriveApp.getFileById(docId);
  const convertedFile = Drive.Files.copy(
    {
      title: `${originalFile.getName()}(转换完成)`,
      mimeType: "application/vnd.google-apps.document"
    },
    docId
  );
  // 转换完成后即可用DocumentApp操作
  const convertedDoc = DocumentApp.openById(convertedFile.id);
  const bodyContent = convertedDoc.getBody().getText();
  return bodyContent;
}

权限说明

以上方案需要在Apps Script项目的appsscript.json中添加对应权限,示例如下:

"oauthScopes": [
  "https://www.googleapis.com/auth/documents",
  "https://www.googleapis.com/auth/drive.readonly"
]

内容的提问来源于stack exchange,提问作者Mohd Nowman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 15:54:02