在特定的Google驱动器文件夹中搜索最新文件

时间:2019-05-13 01:33:27

标签: javascript google-apps-script

我对使用JavaScript进行编码非常陌生,我正在尝试编写一个脚本,该脚本可在Google驱动器的文件夹中找到最新的csv文件,并将内容复制到数据最后一行下方的现有工作表中。

我收到一条错误消息,指出以下内容:

TypeError:在对象中找不到函数hasNext函数Fri May 10 2019 16:42:55 GMT + 1000(AEST)。 (第11行,文件“代码”)

任何帮助将不胜感激!

代码:

   function getCSV() {
var fSource = DriveApp.getFolderById('1mwVqOXikSBh4mcr4iowzJTa4ZvNnzO12'); //       reports_folder_id = id of folder where csv reports are saved
var fi = fSource.getFilesByType('text/csv');// latest       report file

  let lastUpdatedFile = null;
while(fi.hasNext()){
 if(!lastUpdatedFile){ //Checks if we didn't assign anything to lastUpdatedFile
   lastUpdatedFile = fi.next();
 }else{
  var currentFile = fi.next();
  //lastUpdatedFile is older than the current file
  //set lastUpdatedFile to the current file
  if(lastUpdatedFile.getLastUpdated() < currentFile.getLastUpdated()){
    lastUpdatedFile = currentFile;
  }
 }
}
var ss    =SpreadsheetApp.openById('1W2-83TlLONomkcKtaH6f0Zcm4G9jJ1DdWn9BXBhKo2s'); //      data_sheet_id = id of spreadsheet that holds the data to be updated with new      report data
var sd = SpreadsheetApp.getActiveSpreadsheet();
var s = SpreadsheetApp.getActiveSheet();
var target = new Array()
var sSheet = SpreadsheetApp.getActiveSpreadsheet();
sheet = SpreadsheetApp.setActiveSheet(sSheet.getSheets()[0]);

if ( fi.hasNext()) {
var file = fi.next();
var csvData = Utilities.parseCsv(file.getBlob().getDataAsString());

var sheet = ss.getSheets()[0];
var lastrow = s.getLastRow();
s.getRange(lastrow + 1, 1, csvData.length, csvData[0].length).setValues(csvData);
s.getRange(+1, 1, csvData.length, csvData[5].length).setValues(csvData);
}
}

1 个答案:

答案 0 :(得分:0)

根据documentationFolder.getLastUpdated()返回该文件夹上次更新的日期对象。 因此,要遍历文件夹中的文件,可以使用var fi = fSource.getFiles()该文件夹中所有文件。

然后遍历它们以获取最新的更新文件:

var lastUpdatedFile = null;
while(fi.hasNext()){
 if(!lastUpdatedFile){ //Checks if we didn't assign anything to lastUpdatedFile
   lastUpdatedFile = fi.next();
 }else{
  var currentFile = fi.next();
  //lastUpdatedFile is older than the current file
  //set lastUpdatedFile to the current file
  if(lastUpdatedFile.getLastUpdated() < currentFile.getLastUpdated()){
    lastUpdatedFile = currentFile;
  }
 }
}

现在lastUpdatedFile保存着最新的文件。