Search code examples
pythongoogle-apps-scriptfile-conversion

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


I'm stuck with something and can't find a solution to it. Is there a way to convert MS Word files stored in Google Drive to Google Docs using the file urls or ids? I currently have a spreadsheet with the urls to the files. Alternatively, a python script could be used too. Any help or idea would be appreciated! Thanks!


Solution

  • It can be done pretty easy. Here is the script for Spreadsheet App (not Python, though):

    function main() {
    
      var ids = [
        '1MSZwvWwZFwiS0LfDYpUL9vvKXCvbeZkO',
        '1BxECZrrIQpKFJYN5zHUeUDxeEiB8NjEb'
      ];
    
      for (var id of ids)  convert_docx_to_google_doc(id);
    
    }
    
    function convert_docx_to_google_doc(id) {
      var docx       = DriveApp.getFileById(id);
      var folder     = docx.getParents().next();
      var blob       = docx.getBlob();
      var new_file   = Drive.newFile(); // Enable the Advanced Drive API Service
      var google_doc = Drive.Files.insert(new_file, blob, {convert:true});
      
      DriveApp.getFileById(google_doc.id)
        .setName(docx.getName()
        .replace(/\.docx$/,''))
        .moveTo(folder);
    }
    

    It takes the array of IDs and saves the docx files as google docs into the same original folders. And removes the '.docx' extensions from the names of google docs files.

    But are you sure you need it? Google Docs can open and save MS Word documents natively.