javascript 获取Google云端硬盘文件夹中的最新文件

643ylb08  于 2023-04-19  发布在  Java
关注(0)|答案(2)|浏览(181)

我在我的Google App脚本中有以下几行,但File API现在已被弃用,我无法更新代码。
原始行是:

var folder = DocsList.getFolder('Folder Name');
var file = folder.getFilesByType(DocsList.FileType.SPREADSHEET)[0];
var filename = file.getName(); //and get its name
var fileId = file.getId(); // its ID
var fileurl = file.getUrl(); //and its url
var source = SpreadsheetApp.openById(fileId);`

我需要我的脚本去我的驱动器上的一个文件夹,在这个文件夹中获得最新的谷歌电子表格文件,并打开它。

ttcibm8c

ttcibm8c1#

下面是获取文件夹中最新文件的代码:

function getNewestFileInFolder() {
  var arryFileDates,file,fileDate,files,folder,folders,
      newestDate,newestFileID,objFilesByDate;

  folders = DriveApp.getFoldersByName('yourFolderName');  
  arryFileDates = [];
  objFilesByDate = {};
  
  while (folders.hasNext()) {
    folder = folders.next();
    
    files = folder.getFilesByType("application/vnd.google-apps.spreadsheet");//Change file type as needed
    fileDate = "";//Initialize variable to empty string
    
    while (files.hasNext()) {//If no files are found then this won't loop
      file = files.next();
      //Uncomment log statements for debugging
      //Logger.log('xxxx: file data: ' + file.getLastUpdated());
      //Logger.log('xxxx: file name: ' + file.getName());
      //Logger.log('xxxx: mime type: ' + file.getMimeType())
      //Logger.log(" ");
      
      fileDate = file.getLastUpdated();
      objFilesByDate[fileDate] = file.getId(); //Create an object of file names by file ID
      
      arryFileDates.push(file.getLastUpdated());
    }

    if (arryFileDates.length === 0) {//The length is zero so there is nothing
      //to do
      return;
    }

    arryFileDates.sort(function(a,b){return b-a});
   
    //Logger.log(arryFileDates);
    
    newestDate = arryFileDates[0];
    //Logger.log('Newest date is: ' + newestDate);
    
    newestFileID = objFilesByDate[newestDate];
    
    //Logger.log('newestFile: ' + newestFileID);
    //return newestFile;
    
    var ss = SpreadsheetApp.openById(newestFileID);
    //Logger.log('file name that is now open: ' + ss.getName());
  };
};
mzaanser

mzaanser2#

不用担心,您可以使用DriveApp来代替。请参阅此页面了解您可以在驱动器文件上使用的所有可能方法:https://developers.google.com/apps-script/reference/drive/drive-app
希望有帮助!

相关问题