Home > OS >  Unable to access .docx file in Google Docs Add-on
Unable to access .docx file in Google Docs Add-on

Time:12-03

I am developing a Google Docs Add-on using Appsscript which reads the body of the Google Docs and displays it in the add-on UI.

To access the Google doc I am using the the following code:

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

The code was working file for Google Docs files.

Then, I tried reading the text or body of .docx file and I got the following exception:

Exception: The document is inaccessible. Please try again later. Exception Picture

I looked into the various solutions given on StackOverflow but couldn't get the resolution. The answers on StackOverflow says to convert the .docx file into doc file. However, I couldn't do so as I am unable to get the "ID" of opened document.

I will be grateful if anyone suggests me how to get the ID of the opened document or how to get the ID of document from the browser URL or how to resolve this exception.

Thanks in advance.

CodePudding user response:

If you have a URL, probably you can get an ID this way:

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

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

console.log(id) // output: 1BxECZrrIQpKFJYN5zHUeUDxeEiB8NjEb
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Then you can get the file by ID with DriveApp and convert it into Google doc. The fresh example how it can be done is here:

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

If you have the URL of a .docx file (it's not clear to me from your question) the code could be something like this:

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
}
  • Related