微调 2 个 GoogleApp 脚本? GMail 到 GDrive & GDrive 到 GSheet

Fine tuning 2 GoogleApp Scripts? GMail to GDrive & GDrive to GSheet

我目前有一个 GoogleSheet,其中有 2 个 GoogleApp 脚本或多或少也可以按照我的要求工作,但我需要一些帮助来完善它们让他们完美地工作。

我有 1 个脚本可以扫描我的电子邮件,查找邮件的主题,然后将其拉到我的 Google 驱动器(如果匹配)。

脚本 1:从 Gmail 拉取到 GDrive

function importData() {
  var fSource = DriveApp.getFolderById('0B3h9TQiHV_rjR04xTlctb2s2Qms'); // reports_folder_id = id of folder where csv reports are saved
  var fi = fSource.getFilesByName('CR Logs this week.csv'); // latest report file
  var ss = SpreadsheetApp.openById('1OuEXVjZzPwfdcEW8eIOtNAeS4HJeTn_rw8w5o5Ja-Fo'); // data_sheet_id = id of spreadsheet that holds the data to be updated with new report data

  if ( fi.hasNext() ) { // proceed if "CR Logs this week.csv" file exists in the reports folder
    var file = fi.next();
    var csv = file.getBlob().getDataAsString();
    var csvData = CSVToArray(csv); // see below for CSVToArray function
    var newsheet = ss.insertSheet('NEWDATA'); // create a 'NEWDATA' sheet to store imported data
    // loop through csv data array and insert (append) as rows into 'NEWDATA' sheet
    for ( var i=0, lenCsv=csvData.length; i<lenCsv; i++ ) {
      newsheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
    }
    /*
    ** report data is now in 'NEWDATA' sheet in the spreadsheet - process it as needed,
    ** then delete 'NEWDATA' sheet using ss.deleteSheet(newsheet)
    */
    // rename the CR Logs this week.csv file so it is not processed on next scheduled run
    file.setName("CR Logs this week.csv-"+(new Date().toString())+".csv");
  }
};


// http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.

function CSVToArray( strData, strDelimiter ) {
  // Check to see if the delimiter is defined. If not,
  // then default to COMMA.
  strDelimiter = (strDelimiter || ",");

  // Create a regular expression to parse the CSV values.
  var objPattern = new RegExp(
    (
      // Delimiters.
      "(\" + strDelimiter + "|\r?\n|\r|^)" +

      // Quoted fields.
      "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

      // Standard fields.
      "([^\"\" + strDelimiter + "\r\n]*))"
    ),
    "gi"
  );

  // Create an array to hold our data. Give the array
  // a default empty first row.
  var arrData = [[]];

  // Create an array to hold our individual pattern
  // matching groups.
  var arrMatches = null;

  // Keep looping over the regular expression matches
  // until we can no longer find a match.
  while (arrMatches = objPattern.exec( strData )){

    // Get the delimiter that was found.
    var strMatchedDelimiter = arrMatches[ 1 ];

    // Check to see if the given delimiter has a length
    // (is not the start of string) and if it matches
    // field delimiter. If id does not, then we know
    // that this delimiter is a row delimiter.
    if (
      strMatchedDelimiter.length &&
      (strMatchedDelimiter != strDelimiter)
    ){

      // Since we have reached a new row of data,
      // add an empty row to our data array.
      arrData.push( [] );

    }

    // Now that we have our delimiter out of the way,
    // let's check to see which kind of value we
    // captured (quoted or unquoted).
    if (arrMatches[ 2 ]){

      // We found a quoted value. When we capture
      // this value, unescape any double quotes.
      var strMatchedValue = arrMatches[ 2 ].replace(
        new RegExp( "\"\"", "g" ),
        "\""
      );

    } else {

      // We found a non-quoted value.
      var strMatchedValue = arrMatches[ 3 ];

    }

    // Now that we have our value string, let's add
    // it to the data array.
    arrData[ arrData.length - 1 ].push( strMatchedValue );
  }

  // Return the parsed data.
  return( arrData );
};

第二个脚本然后在我的 Google 驱动器中查找匹配的文件名,然后将其导入到 Google Sheet.

脚本 2:从 GDrive 导入到 GSheet

// GLOBALS
//File extension
var fileTypesToExtract = ['csv'];
//Name of the GDrive folder it will be placed
var folderName = 'Reports';
//Name of the label which will be applied after processing the mail message
var labelName = 'ReportToDrive';



function GmailToDrive(){
  //query to search mails
  var query = 'CR Logs this week';
  //filename:csv; //'after:'+formattedDate+
  for(var i in fileTypesToExtract){
  query += (query == '' ?('filename:'+fileTypesToExtract[i]) : (' OR filename:'+fileTypesToExtract[i]));
  }
  query = 'in:inbox has:nouserlabels ' + query;
  var threads = GmailApp.search(query);
  var label = getGmailLabel_(labelName);
  var parentFolder;
  if(threads.length > 0){
  parentFolder = getFolder_(folderName);
  }
  for(var i in threads){
  var mesgs = threads[i].getMessages();
  for(var j in mesgs){
      //get attachments
      var attachments = mesgs[j].getAttachments();
      for(var k in attachments){
      var attachment = attachments[k];
      var isFileType = checkIfCSV_(attachment);
      if(!isFileType) continue;
      var attachmentBlob = attachment.copyBlob();
        var file = DriveApp.createFile(attachmentBlob);
        parentFolder.addFile(file);
      }
  }
  threads[i].addLabel(label);
  }
}

//This function will get the parent folder in Google drive
function getFolder_(folderName){
  var folder;
  var fi = DriveApp.getFoldersByName(folderName);
  if(fi.hasNext()){
    folder = fi.next();
  }
  else{
    folder = DriveApp.createFolder(folderName);
  }
  return folder;
}

//getDate n days back
// n must be integer
function getDateNDaysBack_(n){
  n = parseInt(n);
  var today = new Date();
  var dateNDaysBack = new Date(today.valueOf() - n*2);
  return dateNDaysBack;
}

function getGmailLabel_(name){
  var label = GmailApp.getUserLabelByName(name);
  if(label == null){
  label = GmailApp.createLabel(name);
  }
  return label;
}

//this function will check for filextension type.
// and return boolean
function checkIfCSV_(attachment){
  var fileName = attachment.getName();
  var temp = fileName.split('.');
  var fileExtension = temp[temp.length-1].toLowerCase();
  if(fileTypesToExtract.indexOf(fileExtension) != -1) return true;
  else return false;
}

目标

我有一个软件可以生成 CSV 格式的报告,这些报告每天午夜都会通过电子邮件发送给我。我想要发生的是:

  1. 脚本 1 从电子邮件中提取 CSV 并将其导入 GDrive
  2. 脚本2导入数据到GoogleSheet
  3. 第二天晚上重复上述操作,替换(并丢弃)之前导入的数据

目前,它可以从我的 GMail 拉入我的 GDrive。但是我无法获取它来替换旧数据/删除旧数据并导入新数据。

如果有更多经验的人能帮助我,那就太好了!

所以,最后我自己弄明白了。

//function CopyData() {
       var source = SpreadsheetApp.openById('xxx');
       var sourcesheet = source.getSheetByName('NEWDATA');
       var target = SpreadsheetApp.openById('xxx')
       var targetsheet = target.getSheetByName('Data');
       var targetrange = targetsheet.getRange(2, 1, sourcesheet.getLastRow(), sourcesheet.getLastColumn());
       var rangeValues = sourcesheet.getRange(2, 1, sourcesheet.getLastRow(), sourcesheet.getLastColumn()).getValues();
       targetrange.setValues(rangeValues);
       ss.deleteSheet(newsheet)    

这从 NEWDATA 复制数据,上面的 Script 2 创建的 sheet,然后将其复制到 sheet 数据,替换任何内容已经 there.It 然后删除 NEWDATA sheet,以便脚本可以在第二天晚上 运行。