如何使用谷歌脚本在电子表格中创建文件夹并重命名下载文件的文件名

时间:2016-04-08 07:37:34

标签: google-apps-script google-sheets google-drive-api

我是一名学生,我对谷歌应用程序环境非常陌生,特别是google脚本。所以这就是我的问题,我试图从外部链接下载文件并将其保存到谷歌硬盘。但该文件正保存在我的谷歌硬盘的默认文件夹中。我想要的是自动创建一个文件夹(如果不存在)并自动重命名文件名。 评论将受到高度赞赏。

 function downloadFile(){
    var sh = SpreadsheetApp.getActiveSheet();
    var url = sh.getRange('B1').getValue();
    var user = "testestest";
    var password = "testtesttest";
    var headers = {
            "Accept": "application/xml",
            "Content-Type": "application/xml",
            "Authorization": "Basic "+ Utilities.base64Encode(user+":"+password)
    };

      var options = {
            "method" : "get",
            "headers" : headers 
      };

      var response = UrlFetchApp.fetch(url,options).getBlob();
      var file = DriveApp.createFile(response);
      Logger.log(file);
    }

1 个答案:

答案 0 :(得分:1)

以下是我编写的用于创建文件夹的代码的一部分,如果它不存在:

var inFolder = DriveApp.getFileById(sheetId).getParents().next().getId();
// this line gets the sheet (the document I am working on), then gets its parent folder and stores its ID.

  // Logger.log("inFolder : " + inFolder);
var folders = DriveApp.getFolderById(inFolder).getFolders();
// we now retrieve all folders in the previously located folder
while(folders.hasNext()){
// we now cycle through all the found folders
var folder = folders.next();
// we get the next folder
var folderName = folder.getName();
// we get its name
if(folderName == "Retenues"){
  var retenuesFolderId = folder.getId();
// if there is a folder with the name, it means that this folder exists.
  var folderExists = true;
  // Logger.log("Le dossier existe déjà."); 
 } 
}

if(folderExists != true){
var retenuesFolderId = DriveApp.getFolderById(inFolder).createFolder("Retenues").getId();

}

编辑:我在上面的代码中添加了一些注释。

说明:

该脚本首先找到我的电子表格在我的云端硬盘中的位置。然后它将列出工作表所在文件夹中的所有现有文件夹。它将检查是否存在具有特定名称的现有文件夹。如果没有,它将创建它,然后将文件放入其中。

在您的情况下,您可以只下载所需的文件,它会自动获取ID。获取此ID,并复制(我不确定您是否可以移动文件,我认为您必须将它们复制)到文件夹中。