Create a Contact Group via Google Spreadsheet

2019-06-13 02:26发布

问题:

I am trying to create an email distribution list from a Google form. I then want to place the individuals in a particular contact group. Here is the code I've compiled thus far. Please help. Thank you in advance.

 function addContact() {
   var sheet = SpreadsheetApp.getActiveSheet();
   var startRow = 3;
   var numRows = 10;   // I want the rows to be infinite
   var dataRange = sheet.getRange(startRow, 2, numRows, 10)
   var data = dataRange.getValues();
   for (i in data) {
    var row = data[i];
    var firstName = row[1]; 
    var lastName = row[2];      
    var emailAdd = row[3];
  }
  // The code below creates a new contact and adds it to the "Work Friends" contact group
  var contact = ContactsApp.createContact(firstName, lastName, emailAdd);
  var group = ContactsApp.getContactGroup('Work Friends');
  group.addContact(contact);
  }

回答1:

You were close, just needed some tweaking. See comments in-line, explaining the changes.

function addContact() {
  var sheet = SpreadsheetApp.getActiveSheet();
  // var startRow = 3;  // This implies you have two header rows...
  var headerRows = 2;                   // Number of header rows to skip
  // var numRows = 10;   // I want the rows to be infinite (so use getDataRange)
  var dataRange = sheet.getDataRange(); // Range containing all non-blank rows & cols
  var data = dataRange.getValues();     // Read all data
  data.splice(0,headerRows);            // Remove header rows
  for (i =0; i<data.length; i++) {      // Avoid using for..in with arrays
    var row = data[i];
    var firstName = row[1]; 
    var lastName = row[2];      
    var emailAdd = row[3];

    // Do this IN the loop vvv

    // The code below creates a new contact and adds it to the "Work Friends" contact group
    var contact = ContactsApp.createContact(firstName, lastName, emailAdd);
    var group = ContactsApp.getContactGroup('Work Friends');
    debugger;  // Pause if running in debugger, to examine state
    group.addContact(contact);
  }
}