Google Sheets API: Create or move Spreadsheet into Folder

前端 未结 4 2082

Is it possible to create a Spreadsheet in a specified Folder or do I have to use the Drive API to move it afterwards?

4条回答
  •  既然无缘
    2021-01-04 00:48

    Slightly modified version of the method given by @ukaric. This creates a new Form (can be any doc type you need) in the same folder as the current spreadsheet. This can also be used for moving files around, then just replace the creation part with getting a reference to the target file.

    function createInCurrentFolder() {
      // Create a new form in drive root
      var form = FormApp.create("New_Form");
      var formFile = DriveApp.getFileById(form.getId())
    
      // Get the parent folders of the open document
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var ssFile = DriveApp.getFileById(ss.getId());
      var ssParents = ssFile.getParents();
    
      // Check if we have a parent and
      // assume the first parent to be the current folder
      if (ssParents.hasNext()){
        var parentFolder = ssParents.next();
    
        // Check for root folder
        if (parentFolder.getId() == DriveApp.getRootFolder().getId()) return;
    
        // Add the created form to current folder
        // and remove it from root folder
        parentFolder.addFile(formFile);
        DriveApp.removeFile(formFile);
      }
    }
    

提交回复
热议问题