为每个循环Google App脚本获取2列的值

时间:2018-12-08 17:24:45

标签: google-apps-script foreach

我正在尝试使用Google Apps脚本构建函数,以遍历下表,并向每个供应商发送一封电子邮件,其中包含要订购的正确物品。

我的订购范围如下:

 Supplier Name  |   Item                | Qty
-----------------------------------------------------
My Veg Supplier |   Baby Spinach (Kg)   |0.8
My Veg Supplier |   Basil (Kg)          |0.1
My Veg Supplier |   Chives (KG)         |0.2
My Veg Supplier |   Lettuce Mixed       |1
My Veg Supplier |   Onions Spring       |3
Baking Supplier |   Apple Cruffin       |3
Baking Supplier |   Brioche Rolls       |7
Baking Supplier |   Croissant Plain     |17
Baking Supplier |   Dinner Roll         |6
Baking Supplier |   RSofa Ciabatta      |5
Baking Supplier |   Seed Loaf Large     |1

和我的供应商信息范围如下:

Supplier Name   |   Email           
-------------------------------------------------
My Veg Supplier |   veg@veg.com 
Baking Supplier |   bread@bread.com     

我有一个脚本,可以遍历槽并正确获取要订购的商品,并遍历供应商信息范围,并为每个值获取关联的电子邮件地址。

我将省去第一个函数,因为它可以很长的时间来订购商品,这不是问题,但是我努力说“遍历供应商并获取mailApp.sendEmail的供应商名称和电子邮件地址等”

我当前的职能是获取每个供应商并成功发送邮件,但总是发送到所有供应商的所有地址,而不仅仅是发送给与该供应商相关联的地址

这里是:

  function loopMail(){    
        var ss = SpreadsheetApp.getActiveSpreadsheet();
        var bulk = ss.getSheetByName("To Email");

        var SupplierVals = ss.getRange("H2:H").getValues(); //Supplier Column
        var Supplierlast = SupplierVals.filter(String).length;
        var supplierArray = bulk.getRange(2, 8,Supplierlast,1).getDisplayValues(); // unique supplier column

        var EmailVals = ss.getRange("J2:J").getValues(); //Email Column
        var EmailLast = EmailVals.filter(String).length;
        var emailArray = bulk.getRange(2, 10,Supplierlast,1).getDisplayValues(); // unique email column

      for each (var supplier in supplierArray ){
       for each (var emailAddress in emailArray ){
        var subject = "New Order";
        var emailBody = emailBody;
        MailApp.sendEmail(emailAddress,subject  + supplier,emailBody, {name: 'My Company', replyTo: 'orders@mycompany.com', to: emailAddress, htmlBody: emailBody});        
        var confirm = Browser.msgBox('Order has been sent to  ' + supplier + ' (' + emailAddress + ')', Browser.Buttons.OK); 
    }} 
}

3 个答案:

答案 0 :(得分:0)

尝试一下:

一种支持功能。我使用无模式对话框来帮助调试代码。

function colHeight(col){
  var col=col || 1;
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  var rg=sh.getRange(1,col,sh.getLastRow(),1);
  var vA=rg.getValues();
  for(var i=vA.length-1;i>-1;i--){
    if(!vA[i][0]){
      vA.splice(i,1);
    }else{
      break;
    }
  }
  return vA.length;
}

这是主要功能:

function emailVendorOrders(){
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Orders');
  var erg=sh.getRange(2,5,colHeight(5)-1,2);
  var eA=erg.getValues();
  var emailObj={};
  for(var i=0;i<eA.length;i++){
    emailObj[eA[i][0]]=eA[i][1];
  }
  var orderObj={};
  var org=sh.getRange(2,1,colHeight(1)-1,3);
  var oA=org.getValues();
  for(var i=0;i<oA.length;i++){
    if(orderObj.hasOwnProperty(oA[i][0])){
      orderObj[oA[i][0]].push({Item:oA[i][1],Qty:oA[i][2]});
    }else{
      orderObj[oA[i][0]]=[];
      orderObj[oA[i][0]].push({Item:oA[i][1],Qty:oA[i][2]});
    }
  }
  var hl='';
  for(key in orderObj){
    s='';
    s1='';
    s+=Utilities.formatString('Supplier: %s<br />',key);
    s1+=Utilities.formatString('Supplier: %s\n',key)
    s+=Utilities.formatString('Email Address: %s<br />',emailObj[key]);
    s1+=Utilities.formatString('Email Address: %s\n',emailObj[key]);
    for(var i=0;i<orderObj[key].length;i++){
      s+=Utilities.formatString('Item: %s Qty: %s<br />',orderObj[key][i].Item,orderObj[key][i].Qty);
      s1+=Utilities.formatString('Item: %s Qty: %s\n',orderObj[key][i].Item,orderObj[key][i].Qty);
    }
    s+='<br />';
    s1+='\n';
    var subject='New Order';
    //MailApp.sendEmail(emailObj[key[,subject  + key,s1, {name: 'My Company', replyTo: 'orders@mycompany.com', to: emailObj[key], htmlBody: s});
    hl+=s;
  }
  var ui=HtmlService.createHtmlOutput(hl);
  SpreadsheetApp.getUi().showModelessDialog(ui, 'title');
}

这是我的电子表格的外观。我的范围与您的范围有所不同。

enter image description here

答案 1 :(得分:0)

正如我在评论中所暗示的,您可以使用两种Array方法forEachfilter来做到这一点。

想法是读取订单和供应商的关联工作表范围值:

const wb = SpreadsheetApp.getActive();
const orders = wb.getSheetByName("Orders").getDataRange().getValues();
const suppliers = wb.getSheetByName("Suppliers").getDataRange().getValues();

然后,对每个供应商及其相关数据进行一些操作。这里使用reduce数组方法根据供应商的订单构造一条纯文本消息。

const supplierNameIndex = 0; // example - name in col A
const orderSupplierIndex = 3; // example - supplier name in col D
suppliers.forEach(function (supplier) {
  var name = supplier[supplierNameIndex];
  var supplierOrders = orders.filter(function (order) { return order[orderSupplierIndex] === name; });
  // Log data to Stackdriver for debug purposes
  console.log({message: "All orders for " + name, orderData: supplierOrders});

  // Do something with the filtered orders
  var preface = name + "\n\nPlease order the following:\n\n\tName\tSKU\tQuantity\n";
  var bodyText = supplierOrders.reduce(function (text, order) {
    text += "\t" + order[0] + "\t" + order[1] + "\t" + order[2] + "\n";
    return text;
  }, preface);
  bodyText += "\nThanks,\nShift Supervisor Steve";
  console.log({message: "Email text", text: bodyText});
});

答案 2 :(得分:0)

在无需过多更改代码的情况下,以下代码对我有用,放在每个循环的

  //get email address of supplier - ie the value to the right of supplier column
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var dataRange = sheet.getRange(2,8,10,2); // Column H:J
  var values = dataRange.getValues();

  for (var i = 0; i < values.length; i++) {
    for (var j = 0; j < values[i].length; j++) {     
      if (values[i][j] == supplier) {
        var emailAddress = values[i][j+1];
        Logger.log("Email Address: " +emailAddress);
      }
    }    
  }  //END get email address of supplier - ie the value to the right of supplier column