如何将多个唯一命名的 CSV 附件从 GMAIL 导入到 GOOGLESHEETS

How to import multiple uniquely named CSV attachments from GMAIL to GOOGLESHEETS

我想从一封 GMAIL 电子邮件中导入 3 个 CSV 附件。 附件名称如下: - Sales.csv - Labor.csv - ServerPerformance.csv 我相信可以使用以下方法完成一些操作:

var title = attachment.getName();
if (attachment.getContentType() === "text/csv" && title === "Sales.csv") {  

但需要一些帮助才能正确执行。

下面是我目前用于根据 GMAIL 标签和 CSV 附件名称导入的脚本,但它只导入第一个附件 (Sales.csv),所以我想要一个标签"South Loop" 将 3 个单独的附件从一封电子邮件导入到 google 个工作表。

function SLSalesImportFromGmail() { 
  //gets first(latest) message with set label
  var threads = GmailApp.getUserLabelByName('South Loop').getThreads(0,1);
  if (threads && threads.length>0) {
  var message = threads[0].getMessages()[0];
  var attachment = message.getAttachments()[0];
  var title = attachment.getName();

  // Is the attachment a CSV file
  attachment.setContentTypeFromExtension();
  if (attachment.getContentType() === "text/csv" && title === "Sales.csv") {                            
    var ss = SpreadsheetApp.getActive();
    var sh = ss.getSheetByName("South Loop Sales");
    //parses content of csv to array
    var dataString = attachment.getDataAsString();
    var csvData = CSVToArray(dataString);
    // Remember to clear the content of the sheet before importing new data
    sh.clearContents().clearFormats();                                         
    //pastes array to sheet
    var lastRowValue = sh.getLastRow();
    for (var i = 0; i < csvData.length; i++) {
       sh.getRange(i+lastRowValue+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
    } 
    if( message.getSubject().indexOf('END OF DAY SALES DETAILS') !== -1) {
    SLlogTodaysSales();
    }
  if (attachment.getContentType() === "text/csv" && title === "Labor.csv") {                            
    var ss = SpreadsheetApp.getActive();
    var sh = ss.getSheetByName("South Loop Labor");
    //parses content of csv to array
    var dataString = attachment.getDataAsString();
    var csvData = CSVToArray(dataString);
    var range = sh.getRange("A:K");
    // Remember to clear the content of the sheet before importing new data
  range.clear();
    //pastes array to sheet
    var lastRowValue = sh.getLastRow();
    for (var i = 0; i < csvData.length; i++) {
       sh.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
    } 
    if( message.getSubject().indexOf('END OF WEEK LABOR DETAILS') !== -1) {
    SLlogWeeksLabor();
    }
  if (attachment.getContentType() === "text/csv" && title === "ServerPerformance.csv") {    
    var ss = SpreadsheetApp.getActive();
    var sh = ss.getSheetByName("South Loop Server Report");
    //parses content of csv to array
    var dataString = attachment.getDataAsString();
    var csvData = CSVToArray(dataString);
    var range = sh.getRange("A:M");
    // Remember to clear the content of the sheet before importing new data
  range.clear();                                    
    //pastes array to sheet
    var lastRowValue = sh.getLastRow();
    for (var i = 0; i < csvData.length; i++) {
       sh.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
    } 
    if( message.getSubject().indexOf('END OF DAY') !== -1) {
    SLlogTodaysServers()
    }
  }
  }
  }
  //marks the Gmail message as read, unstars it and deletes it using Gmail API (Filter sets a star)
  message.markRead();
  message.unstar();
  Gmail.Users.Messages.remove("me", message.getId()); // Added
    }
}
//The code formats the code so it can be entered into the Google Script

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 );
  var label = GmailApp.getUserLabelByName("South Loop");
  label.deleteLabel();
}
function SLlogTodaysSales() {
  var todaysSales = SpreadsheetApp.getActive().getRange('South Loop Sales Log!SLSalesImport');
  var logSheet = todaysSales.getSheet();
  logSheet.appendRow(
    todaysSales.getValues()
    .reduce(function(a, b) { return a.concat(b); }) // flatten the 2D array to 1D
  );
}
function SLlogWeeksLabor() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('South Loop Labor Log');
  var rg=sh.getRange('SLLaborImport');
  var vA=rg.getValues();
  sh.getRange(sh.getLastRow()+1,1,vA.length,vA[0].length).setValues(vA);
}
function SLlogTodaysServers() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('South Loop Server Log');
  var rg=sh.getRange('SLServerReport');
  var vA=rg.getValues();
  sh.getRange(sh.getLastRow()+1,1,vA.length,vA[0].length).setValues(vA);
}

因此,在查看您的代码时,我没有看到您遍历附件。

你只是得到第一个执着,然后去分析它,而不管其他的。

  var attachment = message.getAttachments()[0];

因此,与其这样做,不如使用 getAttachments() 获取所有附件,并进行 for 循环以分析每个附件。

var attachments = message.getAttachments();
for(var i=0; i < attachments.length; i++){
   var attachment = attachments[i]; 

   //....
   // The rest of your code needs to go inside this for loop
}

您遇到的问题是,由于这条语句 var attachment = message.getAttachments()[0];,您只查看了第一个附件。相反,只需放下 [0] 并循环遍历所有附件。

为了使这一点更清楚,我去掉了这个例子的一堆代码。也请看完我的笔记。

function SLSalesImportFromGmail() {
  var ss = SpreadsheetApp.getActive(); // Get the spreadsheet file once

  //gets first(latest) message with set label
  var threads = GmailApp.getUserLabelByName('South Loop').getThreads(0,1);
  if (threads && threads.length > 0) {
    var message = threads[0].getMessages()[0];

    // Get all of the attachments and loop through them.
    var attachments = message.getAttachments(); 
    for (var i = 0; i < attachments.length; i++) {
      var attachment = attachments[i];
      var title = attachment.getName();

      // Is the attachment a CSV file
      attachment.setContentTypeFromExtension();
      var table = Utilities.parseCsv(attachment.getDataAsString());
      if (attachment.getContentType() === "text/csv") {
        // Update the specified sheets
        // Clears the sheet of values & formatting and inserts the new table
        // using the Apps Script built-in CSV parser.
        switch (title) { 
          case "Sales.csv":
            ss.getSheetByName("South Loop Sales").getRange("A:M").clear();
            ss.getSheetByName("South Loop Sales").getRange(1, 1, table.length, table[0].length).setValues(table);
            break;
          case "Labor.csv":
            ss.getSheetByName("South Loop Labor").getRange("A:M").clear();
            ss.getSheetByName("South Loop Labor").getRange(1, 1, table.length, table[0].length).setValues(table);
            break;
          case "ServerPerformance.csv":
            ss.getSheetByName("South Loop Servers").getRange("A:M").clear();
            ss.getSheetByName("South Loop Servers").getRange(1, 1, table.length, table[0].length).setValues(table);            
            break;
        }
      }      
    }
    if (message.getSubject().indexOf('END OF DAY') !== -1) {
      SLlogTodaysSales();
      SLlogTodaysServers();
    }
    if (message.getSubject().indexOf('END OF WEEK') !== -1) {
      SLlogTodaysSales();
      SLlogTodaysServers();
      SLlogWeeksLabor();
    }
    // Marks the Gmail message as read, unstars it and deletes it using Gmail API (Filter sets a star)
  message.markRead();
  message.unstar();
  Gmail.Users.Messages.remove("me", message.getId()); // Added
  }
}

备注:

  • 您正在使用自定义 CSVToArray() 函数将 CSV 文件转换为数组,但是 Google 已经使用 Utilities.parseCsv() 提供了一个方法。在大多数情况下应该足够了。
  • 没有必要同时调用 clearContents()clearFormats(),因为 clear() 在一个调用中同时调用。
  • 我知道您有额外的逻辑(例如 "END OF DAY" 电子邮件以及劳动力和服务器性能的规则略有不同)。如前所述,我删除了所有这些以演示如何循环访问附件。您可以使用 if or switch 语句在脚本中包含该逻辑,而不必使用我编写的 updateSheet() 闭包。