google-apps-scriptgoogle-sheetsgoogle-drive-apidelete-filefile-conversion

Script to convert .XLSX to Google Sheet and move converted file


I know it is possible to convert excel files to Google Sheets using script and drive API, but I'm looking for script to convert the excel sheet and move the converted file to a different folder.

So the required steps are as follows:

  1. Convert excel (.xls/.xlsx) to Google Sheet from FolderA.
  2. Move converted file from FoldarA to FolderB.
  3. Delete original excel file from FolderA
  4. Hopefully step 3 avoids this, but avoid duplicating already converted file.

The excel files are being pasted into a local folder that is being synced to google drive, and the files are no larger than 3mb. The current script is as follows. This is converting the files but placing them in the root folder, and will duplicate the conversion when the script runs again.

 function importXLS(){
  var files = DriveApp.getFolderById('1hjvNIPgKhp2ZKIC7K2kxvJjfIeEYw4BP').searchFiles('title != "nothing"');
  while(files.hasNext()){
    var xFile = files.next();
    var name = xFile.getName();
    if (name.indexOf('.xlsx')>-1){ 
      var ID = xFile.getId();
      var xBlob = xFile.getBlob();
      var newFile = { title : name+'_converted',
                     key : ID
                    }
      file = Drive.Files.insert(newFile, xBlob, {
        convert: true
      });
    }
  }
}

Solution

  • If my understanding correct, how about this modification? In this modification, I modified your script.

    Modification points:

    Modified script:

    Before you use this script, please enable Drive API at Advanced Google services.

    function importXLS(){
      var folderBId = "###"; // Added // Please set the folder ID of "FolderB".
    
      var files = DriveApp.getFolderById('1hjvNIPgKhp2ZKIC7K2kxvJjfIeEYw4BP').searchFiles('title != "nothing"');
      while(files.hasNext()){
        var xFile = files.next();
        var name = xFile.getName();
        if (name.indexOf('.xlsx')>-1){ 
          var ID = xFile.getId();
          var xBlob = xFile.getBlob();
          var newFile = {
            title : name+'_converted',
            parents: [{id: folderBId}] //  Added
          };
          file = Drive.Files.insert(newFile, xBlob, {
            convert: true
          });
          // Drive.Files.remove(ID); // Added // If this line is run, the original XLSX file is removed. So please be careful this.
        }
      }
    }
    

    Note:

    References: