我正在使用google appscript创建脚本
我尝试过 指数 ,用于循环遍历range.getValues() 它们均无法按预期正常工作。 数据的长度为3。
function myFunction() {
getFileNameFromFolders('1TcR5oUKwH9hUG9xHBA6HuXQOr40etS5z');
}
function getFileNameFromFolders(folderID) {
var folder = DriveApp.getFolderById(folderID);
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
var fileName = file.getName();
var agentDetails = fileName.split("-");
var agentID = agentDetails[0];
var fileType = agentDetails[1];
var fileUrl = file.getUrl();
var fileDate = agentDetails[2];
locateAgent(agentID, fileType, fileDate, fileUrl, fileName);
}
}
function locateAgent(agentID, fileType, fileDate, url, uniqueKey) {
Logger.log('locating ' + uniqueKey);
var spreadSheet = SpreadsheetApp.openByUrl(SpreadsheetApp.getActiveSpreadsheet().getUrl());
var sheet = spreadSheet.getSheets()[0];
var range = sheet.getRange(2, 1, sheet.getLastRow() - 1, 6)
var data = range.getValues();
for (var i in data) {
if (data[i][5] == uniqueKey) {
Logger.log('yes');
break;
}
else { Logger.log('no');
var newRange = sheet.appendRow([agentID,fileType, fileDate, url, 'r', uniqueKey]);}
}
}
function sendEmails(email, fileUrl) {
var asPDF = DriveApp.getFileById(getIdFromUrl(fileUrl));
MailApp.sendEmail(email, 'test-email-with-agent-stuff-thing-i-dont-know-the-name', 'you should recieve a file named AID-2 as you are registered as 2', {
name: 'Automatic Emailer Script from DOER',
attachments: asPDF.getAs(MimeType.PDF)
});
}
function getIdFromUrl(url) {
return url.match(/[-\w]{25,}$/);
}
即使存在循环,循环也会添加到列表中。我可能会明白。如果您有其他方法可以执行此操作,我将不胜感激。
答案 0 :(得分:2)
修改代码如下:
function locateAgent(agentID, fileType, fileDate, url, uniqueKey) {
Logger.log('locating ' + uniqueKey);
var spreadSheet = SpreadsheetApp.openByUrl(SpreadsheetApp.getActiveSpreadsheet().getUrl());
var sheet = spreadSheet.getSheets()[0];
var range = sheet.getRange(2, 1, sheet.getLastRow()-1, 6)
var data = range.getValues();
var exists=false;
for (var i in data) {
if (data[i][5] == uniqueKey){
exists=true;
var row=i;
break;
}
}
if(exists==false){
Logger.log('it does not exist yet');
var insertRange = sheet.getRange(sheet.getLastRow()+1, 1, 1, 6);
//adapt according to your needs:
insertRange.setValues([[agentID],[fileType],[fileDate],[url],[],[uniqueKey]]);
}else{
//implement here your statement to check status column, e.g.:
if(data[row][status column]!="Sent"){
sendEmails(...);
}
}
}