Monday, July 28, 2014

Save a File or Spreadsheet in a Specific Folder of GDrive

Here is a quick code snippet to help you understand how to save a spreadsheet into a specific folder on Google drive.

In order to create a file in a folder, you will need to find the parent folder and pass it to the DriveApp when you create the file. Normally, file paths are in the form of "/path/to/file/file.js", so it makes sense to keep that same construct when saving files to GDrive. The following code accepts the full file path and creates a new file in that folder.

The next obvious question is how to create a spreadsheet. Unfortunately, you can't create it using the DriveApp, you need to use the SpreadsheetApp. Also, since the spreadsheet app cannot create files in a folder, you will need to create the spreadsheet, then move it to the correct folder. I usually create a separate function with similar logic to find the correct folder, then update the create logic to use SpreadsheetApp instead of DriveApp. See the second function for an example.

Thanks,
Russ

/******************************************
* Create File in a Specific Folder Path
* Version 1.0 
* Created By: Russ Savage
* FreeAdWordsScripts.com
******************************************/
function createFile(filePath) {
  var pathArray = filePath.trim().split('/');
  var folder;
  for(var i in pathArray) {
    var parentName = pathArray[i];
    if(!parentName || parentName === '') { continue; } // in the root folder
    // source: http://goo.gl/P0LQ86
    if(filePath.indexOf(parentName, filePath.length - parentName.length) !== -1) {
      // This is creating the actual file
      if(folder) {
        if(folder.getFilesByName(parentName).hasNext()) {
          Logger.log('Using existing file: '+parentName);
          return folder.getFilesByName(parentName).next();
        }
        return folder.createFile(parentName,'');
      } else {
        if(DriveApp.getRootFolder().getFilesByName(parentName).hasNext()) {
          Logger.log('Using existing file: '+parentName);
          return DriveApp.getRootFolder().getFilesByName(parentName).next();
        }
        return DriveApp.getRootFolder().createFile(parentName,'');
      }
    }
    if(!folder && !DriveApp.getRootFolder().getFoldersByName(parentName).hasNext()) {
      Logger.log('Creating folder: '+parentName);
      folder = DriveApp.getRootFolder().createFolder(parentName);
    } else if(folder && !folder.getFoldersByName(parentName).hasNext()) {
      Logger.log('Creating folder: '+parentName);
      folder = folder.createFolder(parentName);
    } else {
      Logger.log('Using existing folder: '+parentName);
      folder = (!folder) ? DriveApp.getRootFolder().getFoldersByName(parentName).next() 
                         : folder.getFoldersByName(parentName).next();
    }
  }
  // Should never get here
  throw "Invalid file path: "+filePath;
}
And to create a spreadsheet:
/******************************************
* Create Spreadsheet in a Specific Folder Path
* Version 1.0 
* Created By: Russ Savage
* FreeAdWordsScripts.com
******************************************/
function createSpreadsheet(filePath) {
  var pathArray = filePath.trim().split('/');
  var folder;
  for(var i in pathArray) {
    var parentName = pathArray[i];
    if(!parentName || parentName === '') { continue; } // in the root folder
    // source: http://goo.gl/P0LQ86
    if(filePath.indexOf(parentName, filePath.length - parentName.length) !== -1) {
      // This is creating the actual file
      if(folder) {
        if(folder.getFilesByName(parentName).hasNext()) {
          Logger.log('Using existing file: '+parentName);
          var file = folder.getFilesByName(parentName).next();
          return SpreadsheetApp.openById(file.getId());
        }
        // creates in folder
        var spreadsheet = SpreadsheetApp.create(parentName);
        var file = DriveApp.getRootFolder().getFilesByName(parentName).next();
        folder.addFile(file);
        DriveApp.getRootFolder().removeFile(file);
        return spreadsheet;
      } else {
        if(DriveApp.getRootFolder().getFilesByName(parentName).hasNext()) {
          Logger.log('Using existing file: '+parentName);
          var file = DriveApp.getRootFolder().getFilesByName(parentName).next();
          return SpreadsheetApp.openById(file.getId());
        }
        // creates in root folder
        return SpreadsheetApp.create(parentName);
      }
    }
    if(!folder && !DriveApp.getRootFolder().getFoldersByName(parentName).hasNext()) {
      Logger.log('Creating folder: '+parentName);
      folder = DriveApp.getRootFolder().createFolder(parentName);
    } else if(folder && !folder.getFoldersByName(parentName).hasNext()) {
      Logger.log('Creating folder: '+parentName);
      folder = folder.createFolder(parentName);
    } else {
      Logger.log('Using existing folder: '+parentName);
      folder = (!folder) ? DriveApp.getRootFolder().getFoldersByName(parentName).next() 
                         : folder.getFoldersByName(parentName).next();
    }
  }
  // Should never get here
  throw "Invalid file path: "+filePath;
}

10 comments:

  1. replica cartier watches is the renowned French jeweller and watchmaker with a history of pioneering design and a drive for excellence. The replica calibre de cartier watchesfirst references to Cartier wristwatches date back to 1888. Late in the 19th century it was pocket and chatelaine watches that were most popular, but Louis Cartier saw a future in timepieces that could be worn on the wrist.

    ReplyDelete
  2. Allassignmenthelp is the favorite choice of students all over the world for getting best assignment help Australia from experts. Some of the possible causes they choose Australian assignment help service from us is on-time delivery and 24*7 hours availability. Also, they prefer us as the student assignment online website for the best assignment help, because they found the best assignment writing experts team which can accomplish their need of online assignment help Melbourne like services.

    ReplyDelete
  3. To get the correct of How many pages is 1000 words, keep the essential pointers in your mind. For experts’ answer on this question, use assignment help services and connect with professionals.
    1000 words to pages
    1000 words is how many pages

    ReplyDelete
  4. Inexorable stuff by incredible writers. If you guys unable to tackle your boring and tedious instant essay and looking for instant essay help service then hire instant essay writers. instant essay help
    instant essay writer
    essay writer singapore
    essay help singapore
    cheap essay help
    best essay help

    ReplyDelete
  5. SingaporeAssignmentHelp.com tries to provide excellent your assignment help support to its customers and university students. The best way to know about our writing skills and style is to look through assignment samples. Our expert writers are all about know assignment subjects If you need help with assignment then you can easily buy our assignment. Just select the topic and Buy an assignment sample.

    ReplyDelete
  6. Irelandassignmenthelp.com is now available 24*7 for Ireland students so get ready for better assignment help dublin at lowest cost with highly qualified expert writers.

    ReplyDelete
  7. I'm really impressed about the info you provide in your articles. I must say am highly overwhelmed by your whole story. It’s not easy to get such quality information online nowadays. I look forward to staying here for a long time.
    essay writing service
    pay someone to take my class online

    ReplyDelete
  8. How many pages is 1000 words? Students these days are overloaded with the task of assignments, projects, etc. and they have to make use of MS word, google docs, or content writing websites to write down the academic content. Other than students, people, these days are indulged in content writing activities such as articles or blogs. Words limit is one of the benchmarks which must be followed while making assignments or writing blogs and articles. One question always pops up in the minds of students and content writers that how many pages are required to write 1000 words.

    1000 words to pages?
    how many pages is 500 words?
    how many pages is 1000 words double spaced?
    Pages of 500 words?

    ReplyDelete
  9. The India Assignment writers
    at Assignmentworkhelp are the most reliable writers India. They are so dynamic in nature as they have studied throughout in India and they understand the education system. We offer tailored assignment solutions to the students based on their specific requirements and you can trust Assignmentworkhelp as the best Indian writers in Australia for high-quality assignments at affordable pricing. The writers are recognized for expertise in preparing assignments for the subjects which are taught in Australian Universities.
    assignment help india
    assignment writing service in india

    ReplyDelete