Search code examples
excelgoogle-apps-scriptgoogle-drive-apims-officegoogle-docs

Converting Microsoft Office docs in Google Drive to analog Google Docs files


I'm trying to convert all Office files (ex. Word docs, Excel spreadsheets, PowerPoint presentations, etc.) in a folder on my Google Drive into their google doc equivalents.

I'm using the Advanced Drive Service in Google Apps Script to perform this task.

My implementation is below:

function convert() {

 var targetFolder_1 = DriveApp.getFoldersByName('Office Folder'); 
 var targetFolder =  targetFolder_1.next();                       
 var folderGoogify_1 = DriveApp.getFoldersByName('Empty Folder');
 var folderGoogify = folderGoogify_1.next();  
 var counter = 0; 

 var files = targetFolder.getFiles(); 
 var folderID = targetFolder.getId();

 while (files.hasNext()) {

   var nextFile = files.next();
   var blob = nextFile.getBlob();
   var fileName = nextFile.getName();

    var file = {
      title: fileName,
      "parents": [{
        "kind": "drive#parentReference",
        "id": folderID
      }]
    };

      file = Drive.Files.insert(file, blob, {
      convert: true
       });

     counter++;
     folderGoogify.addFile(file);
 }
}

However, at the last line I receive the following error:

Cannot convert [object Object] to File.

How can I adapt my code so that the converted file is recognized as a File, and not an Object?


Solution

  • Modification points :

    1. The response of Drive.Files.insert() is JSON data. This is not file. So such error occurs. When you see the file using Logger.log(file), you can see the JSON data.
    2. In this case, "parents": [{id: folderid}] is folderGoogify.
    3. You can directly create the converted files to the specific folder using Drive API. It is not necessary to use addFile().

    The modified script reflected them is as follows.

    Modified script :

    function convert() {
      var targetFolder_1 = DriveApp.getFoldersByName('Office Folder');
      var targetFolder =  targetFolder_1.next();
      var folderGoogify_1 = DriveApp.getFoldersByName('Empty Folder');
      var folderGoogify = folderGoogify_1.next();
      var counter = 0; 
      var files = targetFolder.getFiles();
      while (files.hasNext()) {
        var nextFile = files.next();
        var blob = nextFile.getBlob();
        var fileName = nextFile.getName();
        var file = {
          title: fileName,
          "parents": [{"id": folderGoogify.getId()}],
          "kind": "drive#parentReference",
        };
        counter++;
        file = Drive.Files.insert(file, blob, {convert: true});
      }
    }
    

    If I misunderstand your question, I'm sorry.