【问题标题】:How to create a folder and rename the file name of a downloaded file in spreadsheet using google script如何使用谷歌脚本在电子表格中创建文件夹并重命名下载文件的文件名
【发布时间】:2016-04-09 18:35:03
【问题描述】:

我是一名学生,我对谷歌应用环境特别是谷歌脚本非常陌生。所以这是我的问题,我正在尝试从外部链接下载文件并将其保存到谷歌驱动器。但是该文件被保存在我的谷歌驱动器的默认文件夹中。我想要的只是自动创建一个文件夹(如果不存在)并自动重命名文件名。 评论将不胜感激。

 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);
    }

【问题讨论】:

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


    【解决方案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();
    

    }

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

    解释:

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

    在你的情况下,你可以下载你想要的文件,它会自动获得一个 ID。获取此 ID,然后将其复制(我不确定您是否可以移动文件,我认为您必须将它们复制)到文件夹中。

    【讨论】:

    • 您好,我还有一个问题要问。所以这是我需要在现有文件夹中创建文件的事情,我该怎么做?你能帮我吗?我尝试使用相同的方法,但总是收到此错误“TypeError: Cannot find function getFiles in object FolderIterator.”
    • 文件夹迭代器(getFolders)只获取文件夹,不获取文件。如果要获取特定文件夹中的特定文件,则必须先获取文件夹,然后再获取文件。因此,您必须将 ID 存储在某个位置,用于文件夹和文件。
    猜你喜欢
    • 1970-01-01
    • 2015-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    • 2015-07-13
    • 2018-12-23
    • 1970-01-01
    相关资源
    最近更新 更多