Google Sheets API: Create or move Spreadsheet into Folder

前端 未结 4 2059

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

    Depends on how you want to use and how do you create your Spreadsheet, it is possible to create Spreadsheet like so.

     function create_ss_in_folder(folder, name) {
      var ss = SpreadsheetApp.create(name);
      var id = ss.getId();
      var file = DriveApp.getFileById(id);
      var folder = get_folder_by_name(folder);
      folder.addFile(file);
      DriveApp.getRootFolder().removeFile(file);
      return id;
    }
    

    Again with not much info i do not know why would you create Spreadsheets manually when there is programmatic way to do it.

    Some helpful links:

    https://developers.google.com/apps-script/reference/drive/folder

    https://developers.google.com/apps-script/advanced/drive

    Update:

      //Move it to desired folder
      var fileID = 'Your file ID'
      var folderID = 'Folder ID'
      var file = DriveApp.getFileById(fileID).getName()
      var folder = DriveApp.getFolderById(folderID)
      var newFile = file.makeCopy(file, folder)
    
      // This will remove it from root.
      DriveApp.getFileById(fileID).setTrashed(true)
    

提交回复
热议问题