Convert docx file to Google Docs and place in same folder

Viewed 227

I need to convert docx files inside a folder and place the created GDocs file beside the .docx as the same name without .docx extension

I do not want to use folder.addFile(doc);DriveApp.getRootFolder().removeFile(doc) because its a overhead and I want to place the file in the folder itself rather than creating the converted file in root and then moving it besides docx.

I have tried with

function myFunction() {
  var docx = DriveApp.getFilesByName('Dummy.docx').next();
  var newDoc = Drive.newFile();
  var blob =docx.getBlob();
  var file=Drive.Files.insert(newDoc,blob,{convert:true});
  DocumentApp.openById(file.id).setName(docx.getName());  
}
2 Answers

I believe your goal as follows.

  • You want to convert DOCX file to Google Document.
  • You want to put the converted Google Document to the same folder of the DOCX file.
  • You want to set the filename of Google Document by removing the extension of the filename of the DOCS file.

Modification points:

  • In this case, I would like to propose to use the method of "Files: copy" of Drive API. By this, the converted Google Document has been automatically renamed as the filename without the extension of .docx. And, the converted Google Document is put to the same folder with the DOCX file. I thought that this situation might be suitable for achieving your goal.

When your script is modified, it becomes as follows.

Modified script:

Before you use this, please confirm whether Drive API is enabled at Advanced Google services, again.

function myFunction() {
  var file = DriveApp.getFilesByName('Dummy.docx');
  if (!file.hasNext()) return;
  var document = Drive.Files.copy({}, file.next().getId(), {convert: true});
  var doc = DocumentApp.openById(document.id);
}

Reference:

You can specify the folder where the file should be created using its metadata:

function myFunction() {
  // Set target Folder
  var folderID = 'FOLDER_ID';
  
  // Get .docx based on its name
  var docx = DriveApp.getFolderById(folderID).getFilesByName('Dummy.docx').next();
  
  // Specify file name and parent folder
  var fileMetadata = {
    title: docx.getName(),
    parents: [{id: folderID}]
  };
  
  // Convert .docx to Docs
  Drive.Files.insert(fileMetadata, docx.getBlob(), {convert:true});
  
  // Send .docx to Trash
  docx.setTrashed(true);
}

For this to work, you need to enable the Drive advanced services: https://developers.google.com/apps-script/advanced/drive

Related