Falves
Falves

Reputation: 37

Google Apps Scripts: How to save files from root to a specific folder?

I'm starting to learn google apps script and suffering a little, :S.

So, when I run this function:

function importXLSX(){
  var files = DriveApp.getFolderById('0B5HXuvZIdqQ3bWlKNXFXZzhIcmc').searchFiles('title contains ".xlsx"');
    while(files.hasNext()){
      var xFile = files.next();
      var name = xFile.getName();
         if (name.indexOf('.xlsx')){ 
            var ID = xFile.getId();
            var xBlob = xFile.getBlob();
            var newFile = { title : name+'_converted',
                 key : ID,
            }
            file = Drive.Files.insert(newFile, xBlob, {
            convert: true
            });
         }
       }
    }

The files converteds are set in Drive's root, but I´d like that

When I run the code, the files are saved in the root folder but I would like them to be saved to a specific folder, like "Converteds", so if anyone knows how to solve it, I would be very grateful!

This is a reference link about the function: Convert all xls files available in a folder into "Google Doc Spreadsheets"?

Thanks!

Upvotes: 0

Views: 2772

Answers (2)

Tanaike
Tanaike

Reputation: 201358

Since you use Drive API, you can directly create a file to the specific folder.

I added parents: [{"id": "### Folder ID ###"}] to newFile. Please change ### Folder ID ### to the specific folder and try this.

Modified script :

function importXLSX(){
  var files = DriveApp.getFolderById('0B5HXuvZIdqQ3bWlKNXFXZzhIcmc').searchFiles('title contains ".xlsx"');
  while(files.hasNext()) {
    var xFile = files.next();
    var name = xFile.getName();
    if (name.indexOf('.xlsx')) { 
      var ID = xFile.getId();
      var xBlob = xFile.getBlob();
      var newFile = {
        title : name+'_converted',
        key : ID,
        parents: [{"id": "### Folder ID ###"}]
      }
      file = Drive.Files.insert(newFile, xBlob, {convert: true});
    }
  }
}

If you want to retrieve folder ID from folder name. Please use following script.

var folderId = DriveApp.getFoldersByName("### Folder name ###").next().getId();

If I misunderstand your question, I'm sorry.

Upvotes: 6

TheAddonDepot
TheAddonDepot

Reputation: 8964

First you need to get the Folder id (right-click the folder in Google Drive and check its share options by clicking "Get Shareable Link", the string at the tail-end of the share URL is the folder's id) and then for each file you convert add the file to the target folder.

var folder = DriveApp.getFolderById([folder-id]);

while(files.hasNext()) {
    var file = files.next();
    ...
    ...
    folder.addFile(file);
}

And that should do the trick!

Upvotes: 0

Related Questions