title: How to update file contents from gdoc to docx
body: <p>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: <a href="https://stackoverflow.com/questions/46822740/batch-convert-google-docs-files-to-microsoft-word">Batch convert Google Docs files to Microsoft Word</a>, however this creates a new file. I need to keep the URL/ID of the original file. I tried using &quot;setContent&quot; 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?</p>
  <p>This is my code:</p>
  <pre><code>function convertGoogleDocsToMicrosoftWord() {
    var folderId = &quot;MY_FOLDER_ID&quot;; // 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(
          &quot;https://docs.google.com/document/d/&quot; + file.getId() + &quot;/export?format=docx&quot;,
          {
            &quot;headers&quot;: {Authorization: 'Bearer ' + ScriptApp.getOAuthToken()},
            &quot;muteHttpExceptions&quot;: true
          }
        ).getBlob();
  
      Drive.Files.update({
        mimeType: MimeType.MICROSOFT_WORD,
        title: file.getName() + '.docx'
      }, file.getId(), contents);
    }
  }
  </code></pre>
  <p>Some further questions:</p>
  <ul>
  <li>assuming I can make this to work, can it update while the file is open?</li>
  <li>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?</li>
  </ul>