I am trying to create an Apps Script that will auto-convert all gdoc files to docx files (and all gsheet files to xlsx files). Some parts of the puzzle are addressed here: Batch convert Google Docs files to Microsoft Word, however this creates a new file. I need to keep the URL/ID of the original file. I tried using "setContent" on the File API but that doesn't seem to handle blobs. So thats why I resorted to the advanced Drive API. However, I can't seem to get it to work properly. The filename is replaced, the contents are replaced, but the file stays Google Doc, even though I supply a Mime Type. Any ideas?
This is my code:
function convertGoogleDocsToMicrosoftWord() {
var folderId = "MY_FOLDER_ID"; // Note, eventually I would like to get this from the trigger event somehow so I would welcome ideas on this, too
var files = DriveApp.getFolderById(srcfolderId).getFilesByType(MimeType.GOOGLE_DOCS);
while (files.hasNext()) {
var file = files.next();
var contents = UrlFetchApp.fetch(
"https://docs.google.com/document/d/" + file.getId() + "/export?format=docx",
{
"headers": {Authorization: 'Bearer ' + ScriptApp.getOAuthToken()},
"muteHttpExceptions": true
}
).getBlob();
Drive.Files.update({
mimeType: MimeType.MICROSOFT_WORD,
title: file.getName() + '.docx'
}, file.getId(), contents);
}
}
Some further questions:
- assuming I can make this to work, can it update while the file is open?
- I would like to be able to launch this on trigger events... however standalone scripts can't seem to be able to get a ref to the current folder they are executed in and then recourse. Is this possible?