Google-sheets – Import Google Contacts to Google Spreadsheet

google sheetsgoogle-apps-scriptgoogle-contacts

Google notice me :

You do not have permission to call getContacts (line 3)

Here is my code:

function importFullName(input) {
  var CONTACT = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var contacts = ContactsApp.getContacts();

  for (i=0; i<contacts.lenght; i++) {
    var fullname = ContactApp.getContactsByID('i');
    Logger.log(contacts[i].getFullName());
    CONTACT.getRange(i+2,2).setValues(myContact);
  }
}

Best Answer

Error

The error you received has to do with the authentication of the script.
Click on the bug button (marked yellow):
enter image description here
A popup will appear and in this case you need to grant access to both the Google Spreadsheet and Google Contacts.

It's also advisable to create an array to keep the results in, rather than writing each result to the spreadsheet. See my code below.

Code

function importFullName() {
  var contacts = ContactsApp.getContacts(), output = [];  
  for(var i = 0, iLen = contacts.length; i < iLen; i++) {
    var fullname = contacts[i].getFullName();    
    if(fullname) {
      output.push([fullname]);
    } else {
      continue;
    }
  }  
  SpreadsheetApp.getActiveSheet().getRange(1, 1, output.length, 1).setValues(output);
}