Exporting from Google Sheets to Google Contacts - google-sheets

I'm trying to add contacts using a spreadsheet and a script.
So far I was able to copy the script from this user: How to sync google sheets database with google contacts
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet = ss.getSheetByName('Respostas ao formulário 1')
var headerRows = 1;
var MaxRow = sheet.getLastRow();
var dataRange = sheet.getDataRange();
var data = dataRange.getValues();
data.splice(0, headerRows);
function addContact() {
for (var i = 0; i < data.length; i++) {
var row = data[i];
var firstName = row[1];
var lastName = row[2];
var email = row[3];
var phone = row[4];
var group = row[5];
var job = row[6];
var address2 = row[7];
contact = ContactsApp.createContact(firstName, lastName, email);
contact.addPhone(ContactsApp.Field.MOBILE_PHONE, phone);
contact.setNotes(address2)
contact.addCompany('', job)
var group = ContactsApp.getContactGroup("System Group: My Contacts");
group.addContact(contact);
}
}
It works great, but I can't find out how to add age or to automatically add a label to the contact. Any help would be awesome

You need to create a custom field. Within your code if you add this line I think you'll get what you need:
contact.addCustomField("Age", '26');

Try to add " var age = row[8];" under "var address2 = row[7];
"or whereever you want. If you place it other you have to ajust the numbers.
I hope i can help!

Related

Error when adding contacts from Google Spreadsheets to Google Contacts

I tried making a script on Google Spreadsheets to add new contacts based on a spreadsheet and add them to the "adicionar marcador" group, it ended up like this::
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet = ss.getSheetByName('Planilha de cadastro')
var headerRows = 1;
var MaxRow = sheet.getLastRow();
var dataRange = sheet.getDataRange();
var data = dataRange.getValues();
data.splice(0, headerRows);
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Contatos')
.addItem('Adicionar Contatos', 'addContact')
.addToUi();
}
function addContact() {
for (var i = 0; i < data.length; i++) {
var row = data[i];
var firstName = row[1];
var lastName = row[2];
var email = row[3];
var phone = row[4];
var job = row[5];
var address2 = row[6];
var Age = row [7];
var obs = row [8];
var group = row[10];
contact = ContactsApp.createContact(firstName, lastName, email);
contact.addPhone(ContactsApp.Field.MOBILE_PHONE, phone);
contact.setNotes(obs)
contact.addCompany('', job)
contact.addCustomField("Idade", Age);
contact.addCustomField("Endereço", address2)
var group = ContactsApp.getContactGroup("System Group: My Contacts");
group.addContact(contact);
var group = ContactsApp.getContactGroup('Adicionar marcador')
group.addContact(contact);
}
}
But when I try adding contacts by using the function addContact it returns me an error message. Any idea on what is wrong with the code?
see comments above about declaring variables multiple times and arrays starting with zero. This added the data (and not the headings) and placed the contacts into the group from the spreadsheet. I created the group first.
function createContactGroup() { // this works
let group = ContactsApp.createContactGroup('apps-script');
console.log('group.getName(): ', group.getName() );
}
function addContact() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
const sheet = ss.getSheetByName('contact')
const headerRows = 1;
let MaxRow = sheet.getLastRow();
let dataRange = sheet.getDataRange();
let data = dataRange.getValues();
console.log('data: ', data);
let row, firstName, lastName, email, phone, job, address2, Age, obs, group;
for (var i = 1; i < data.length; i++) { // top row is header
row = data[i];
firstName = row[0];
lastName = row[1];
email = row[2];
console.log('fname: ', firstName, ' lname: ', lastName, ' email: ', email );
phone = row[3];
job = row[4];
address2 = row[5];
Age = row[6];
obs = row[7];
group = row[8];
console.log('group: ', group );
try {
contact = ContactsApp.createContact(firstName, lastName, email);
} catch (err) {
console.log('createContact err: ', err );
}
contact.addPhone(ContactsApp.Field.MOBILE_PHONE, phone);
contact.setNotes(obs)
contact.addCompany('', job)
contact.addCustomField("Idade", Age);
contact.addCustomField("Endereço", address2)
addToGroup = ContactsApp.getContactGroup(group);
addToGroup.addContact(contact);
// var group = ContactsApp.getContactGroup('Adicionar marcador')
// group.addContact(contact);
}
}

.makeCopy - copy values only - script modification

could you please advise how to modify the script in google spreadsheets, to copy VALUES only ?
function Report() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet();
var folderID = "1czYdbjaPOqUmpPbnB2Fl0LGX_eVYWskD";
var LPSheetSpreadsheet = SpreadsheetApp.getActive();
var LPSheet = LPSheetSpreadsheet.getSheetByName("RAW Master CHF");
var folder = DriveApp.getFolderById(folderID);
var fileName = "LP Report "
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(LPSheetSpreadsheet.getId()).makeCopy(fileName , folder)
var destSheet = destSpreadsheet.getSheetByName("RAW Master CHF");
It works, but copy sheets with all formulas. Can we add some another argument/modify the script to copy/paste just values?
many thanks!
You can add function to copy paste value after you have create the new sheet, so that it will loop through all the sheets and replace all formula with value only:
function Report() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet();
var folderID = "1QmdQ0meKRbxe2GIg9rRkcTWOcKVKHWvn";
var LPSheetSpreadsheet = SpreadsheetApp.getActive();
var folder = DriveApp.getFolderById(folderID);
var fileName = "LP Report "
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(LPSheetSpreadsheet.getId()).makeCopy(fileName , folder));
var destSheets = destSpreadsheet.getSheets();
for (var i = 0; i < destSheets.length;i++){
var sheet = destSheets[i];
var copyRange = sheet.getRange(1,1,sheet.getLastRow(),sheet.getLastColumn());
copyRange.copyTo(copyRange, SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
}
}
Answer
Use getDataRange, getDisplayValues and setValues.
Explanation
Once you have made a copy of the file, you can replace all its formulas with values combining the mentioned methods.
Code
function formula2value() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheets = ss.getSheets()
for (var i = 0; i < sheets.length; i++) {
var values = sheets[i].getDataRange().getDisplayValues()
sheets[i].getDataRange().setValues(values)
}
}
References
Sheet: getDataRange
Range: getDisplayValues
Range: setValues

Google Script to grab values in a column and compares those to parameter with if/else statement

I'm trying to create an app script that you can type in the name and username of an individual and select various dates associated with their training. I'm nearly done with the project but one piece of script is giving me issues. What the script is supposed to do is take the User Name I've entered into the app and see if that value already exists in column L of the archive. If the value exists then it should return an alert with a YES_NO option and depending on what is selected it will either cancel the import or continue on and import the username to the sheet.
I've been trying to figure out this script for about 5 days and cannot figure it out. I've tried pretty much everything I can think of. Here's the code. The Username already exists in Cell L3 of the Archive.
function postApp(e)
{
var usern = e.parameter.userN;
var name1 = e.parameter.name;
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var tM = sheet.getSheetByName('Archive');
var tR = tM.getLastRow()-1;
var tC = tM.getLastColumn();
var tD = tM.getRange("L3").getValues();
if(tD == usern )
{
var ui = SpreadsheetApp.getUi(); // Same variations.
var result = ui.alert('Wait', 'The Username you are trying to use has already been archived. Would you still like to continue?', ui.ButtonSet.YES_NO);
// Process the user's response.
if (result == ui.Button.Yes) {
// User clicked "Yes".
SpreadsheetApp.getActiveSpreadsheet().toast('Error Report Has Been Updated', 'UPDATE ERRORS',3);
var date = new Date();
var d = Utilities.formatDate(date, Session.getScriptTimeZone(), 'M/d/yyyy');
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('SyNERGY');
var lR = s.getLastRow()+1;
var lC = s.getLastColumn();
var app = UiApp.getActiveApplication();
var name = e.parameter.name;
var user = e.parameter.userN;
var team = e.parameter.team;
var hire = e.parameter.hire;
////////////////////////////
// CREATE REPORT CARD
genReportCard(name, team, hire, app, user);
s.getRange(lR,12).setValue([[user]]).setNumberFormat(';;;');
s.getRange(lR,12).setValue(user.toString().toLowerCase());
s.getRange(lR,11).setValue('SyN');
///////////////////////////////////////////
///////////Close after complete////////////
var ui = SpreadsheetApp.getUi(); // Same variations.
var result = ui.alert("Specialist Created!");
var app = UiApp.getActiveApplication();
app.close();
return app;
}else {
// User clicked "No" or X in the title bar.
ui.alert('Import Canceled');
}
}else{
var date = new Date();
var d = Utilities.formatDate(date, Session.getScriptTimeZone(),
'M/d/yyyy');
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('SyNERGY');
var lR = s.getLastRow()+1;
var lC = s.getLastColumn();
var app = UiApp.getActiveApplication();
var name = e.parameter.name;
var user = e.parameter.userN;
var team = e.parameter.team;
var hire = e.parameter.hire;
////////////////////////////
// CREATE REPORT CARD
genReportCard(name, team, hire, app, user);
s.getRange(lR,12).setValue([[user]]).setNumberFormat(';;;');
s.getRange(lR,12).setValue(user.toString().toLowerCase());
s.getRange(lR,11).setValue('SyN');
///////////////////////////////////////////
///////////Close after complete////////////
var ui = SpreadsheetApp.getUi(); // Same variations.
var result = ui.alert("Specialist Created!");
var app = UiApp.getActiveApplication();
app.close();
return app;
}
}
This script Works as long as I am referencing One Cell so tM.getRange("L3").getValues(); Works. However, As soon as I change that to tM.getRange("L3:L").getValues(); it does not recognize the value exists within the range and returns the else portion of the code.
I have also tried a loop for the top section that is giving me issues but the same thing is happening. As soon as I try to find a value within the column rather than a specific cell it won't work. Here is what it looks like with the loop.
function postApp(e)
{
var usern = e.parameter.userN;
var name1 = e.parameter.name;
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var tM = sheet.getSheetByName('Archive');
var tR = tM.getLastRow()-1;
var tC = tM.getLastColumn();
var tD = tM.getDataRange().getValues();
for(var i = 0; i<tD.length; i++){
if(tD[i][11] == usern )
{
If anyone can figure out what i'm doing wrong or why it's not working as soon as I reference the entire column any help would be greatly appreciated.
Thanks!

Getting error: "Missing ) after argument list. (line 11, file "Code")

I'm new to coding. I am attempting to import e-mail addresses from a Google Sheet to my gmail account. Any help on why this code is not working would be greatly appreciated! Here is the code I have entered:
function myFunction() {
var alreadyAdded = "Already added";
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 396; // Number of rows to process
// Fetch the range of cells A2:F397
var dataRange = sheet.getRange(startRow, 1, numRows, 400
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for
var
for (var i = 0; i < data.length; ++i)
};
var row = data[i];
var lastName = row[0]
var firstName = row[1]
var emailAddress = row[2]
var address = row[3]
var notes = row[4]
if (addedAlready != alreadyAdded) {
// Create contact in Google Contacts
var contact = ContactsApp.createContact(firstName, lastName, emailAddress);
// Add values to new contact
contact.addAddress(address, "");
contact.setNotes(notes);
sheet.getRange(startRow + i, 7).setValue(alreadyAdded);
};
};
}
try it var dataRange = sheet.getRange(startRow, 1, numRows, 400);

google script editor mailchimp - fetch segment subscriber

I'm currently trying to fetch mailchimp data for the total amount of subscribers within a predefined auto updating segment within our subscriber list into Google sheets using the script editor. However, I must confess I'm not very knowledgeable in this area and have tried various ways of customizing this code with no luck. I have looked at Mailchimps documentation regarding this but still cannot seem to get this work.
function chimpSubscribers() {
var API_KEY = ''; // MailChimp API Key
var LIST_ID = ''; // MailChimp List ID
var SEGMENT_ID =''; //Mailchimp Segment ID
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Subscribers");
var dc = API_KEY.split('-')[1];
var api = 'https://'+ dc +'.api.mailchimp.com/3.0';
var memberList = '/lists/'+LIST_ID
var memberSegment = '/segments/'+SEGMENT_ID
var apiCall = function(endpoint){
options = {"headers": {"authorization": 'apikey '+API_KEY}};
apiResponseMembers = UrlFetchApp.fetch(api+endpoint,options);
json = JSON.parse(apiResponseMembers);
return json
}
var members = apiCall ("memberList", "memberSegment");
if (members) {
var d = new Date();
var member_count = members.stats.member_count;
var unsubscribe_count = members.stats.unsubscribe_count;
var open_rate = members.stats.open_rate;
var click_rate = members.stats.click_rate;
var report = [d, member_count, unsubscribe_count, open_rate, click_rate,];
Logger.log(report);
// Clear MailChimp data in Spreadsheet
sheet.clear();
// Append MailChimp data to Spreadsheet
sheet.appendRow(["Date", "Total Subscribers", "Unsubscribe Count", "Open Rate", "Click Rate"]);
sheet.appendRow(report);
}
}
Figured it out - for anyone else that may need it the code is as follows:
function chimpSubscribers() {
var API_KEY = ''; // MailChimp API Key
var LIST_ID = ''; // MailChimp List ID
var SEGMENT_ID = ''; // Mailchimp Segment ID
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Subscribers");
var dc = API_KEY.split('-')[1];
var api = 'https://'+ dc +'.api.mailchimp.com/3.0';
var memberList = '/lists/'+LIST_ID +'/segments/'+ SEGMENT_ID
options = {"headers": {"authorization": 'apikey '+API_KEY}};
var apiCall = function(endpoint){
apiResponseMembers = UrlFetchApp.fetch(api+endpoint,options);
json = JSON.parse(apiResponseMembers);
return json
}
var members = apiCall(memberList);
if (members) {
var d = new Date();
var member_count = members.member_count;
var report = [d,member_count,];
Logger.log(report);
// Clear MailChimp data in Spreadsheet
sheet.clear();
// Append MailChimp data to Spreadsheet
sheet.appendRow(["Date", "Total Subscribers"]);
sheet.appendRow(report);
}
}

Resources