GAS insert emoji into a table - google-apps-script

I am sending an email that contains a table.
The output is a table in the email where the first column should be the emoji follow by the name and date.
When I tried to put the emoji into the column of my array, the output in the column 1 of the table is a black ? triangle.
My code snippet is below -
for (let indx =0; indx<empDates.length; ++indx){
if (empDates[indx][startMonthIndx]!="") {
var tempDate = new Date(empDates[indx][startMonthIndx+1]);
if (tempDate.getMonth() >= monDate.getMonth() && tempDate.getDate() >= monDate.getDate() && tempDate.getMonth() <= sunDate.getMonth() && tempDate.getDate()<= sunDate.getDate()) {
var emojiType = empDates[indx][startMonthIndx];
if (emojiType.indexOf("(B)")==0) {
var emojiIcon = '🎂';
} else {
var emojiIcon = '🎉';
}
thisWeekReminder.push(emojiIcon, [empDates[indx][startMonthIndx], empDates[indx][startMonthIndx+1]]);
}
if (startMonth != endMonth) {
tempDate = new Date(empDates[indx][startMonthIndx+3]);
if (empDates[indx][startMonthIndx+2]!="") {
if (tempDate.getMonth() >= monDate.getMonth() && tempDate.getDate() >= monDate.getDate() && tempDate.getMonth() <= sunDate.getMonth() && tempDate.getDate()<= sunDate.getDate()) {
var emojiType = empDates[indx][startMonthIndx];
if (emojiType.indexOf("(B)")==0) {
var emojiIcon = '🎂';
} else {
var emojiIcon = '🎉';
}
thisWeekReminder.push(emojiIcon, [empDates[indx][startMonthIndx+2], empDates[indx][startMonthIndx+3]]);
}
}
}
}
}
const htmlTemplate = HtmlService.createTemplateFromFile('emailTable');
htmlTemplate.name = name;
htmlTemplate.specialDate = specialDate;
htmlTemplate.tablerangeValue = thisWeekReminder;
const htmlForEmail = htmlTemplate.evaluate().getContent();
var toEmail = emailAddr[0][0];
var ccEmail = "";
for (let i=1; i<emailAddr.length; ++i) {
if (emailAddr[i][0] != "") {
if (i=1) {
ccEmail = emailAddr[i][0];
} else {
ccEmail = ccEmail + "," + emailAddr[i][0];
}
}
}
MailApp.sendEmail({
to: toEmail,
cc: ccEmail,
subject: "REMINDER: This week's Birthdays and Anniversaries",
htmlBody:htmlForEmail
});
}
}

Related

renameCustomField() Change the Label Field Name

SVP i'm newsbe in Appsscript with API PEOPLE
This script don't work : I want to rename "CKD EPI" by "CKD EPI / CROKOFF / CREAT"
Can you tell me what's wrong ?
function renameCustomField() {
var debug = true;
var group = People.PeopleApi.getContactGroups().get("Mygroup").execute();
var oldFieldName = "CKD EPI";
var newFieldName = "CKD EPI / CROKOFF / CREAT";
for (var i = 0; i < group.members.length; i++) {
var contact = group.members[i];
var fields = contact.userDefined;
for (var j = 0; j < fields.length; j++) {
if (fields[j].key === oldFieldName) {
fields[j].key = newFieldName;
if (debug) {
console.log("Renaming field for contact: " + contact.names[0].displayName);
}
}
}
var updateContact = {
resourceName: contact.resourceName,
updatePersonFields: "userDefined",
userDefined: fields
}
People.PeopleApi.updateContact(updateContact).execute();
}
}

My website becomes unresponsive when dealing 1000 rows excel file

I am uploading data from an excel file into my website using input html button.
and then convert the data into json and then I map it with local external metadata.
Finally view it using the id.
My website becomes unresponsive & sometimes takes a lot of time processing. Please help
function ExportToTable() {
var regex = /^([a-zA-Z0-9\s_\\.\-:()])+(.xlsx|.xls)$/;
/*Checks whether the file is a valid excel file*/
if (regex.test($("#excelfile").val().toLowerCase())) {
var xlsxflag = false; /*Flag for checking whether excel is .xls format or .xlsx format*/
if ($("#excelfile").val().toLowerCase().indexOf(".xlsx") > 0) {
xlsxflag = true;
}
/*Checks whether the browser supports HTML5*/
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
/*Converts the excel data in to object*/
if (xlsxflag) {
var workbook = XLSX.read(data, { type: 'binary' });
}
else {
var workbook = XLS.read(data, { type: 'binary' });
}
/*Gets all the sheetnames of excel in to a variable*/
var sheet_name_list = workbook.SheetNames;
console.log(sheet_name_list);
var cnt = 0; /*This is used for restricting the script to consider only first
sheet of excel*/
sheet_name_list.forEach(function (y) { /*Iterate through all sheets*/
/*Convert the cell value to Json*/
if (xlsxflag) {
var exceljson = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
}
else {
var exceljson = XLS.utils.sheet_to_row_object_array(workbook.Sheets[y]);
}
//Download & View Subscriptions
if (exceljson.length > 0 && cnt == 1) {
metadata = [];
fetch("metadata.json")
.then(response => response.json())
.then(json => {
metadata = json;
console.log(metadata);
user_metadata1 = [], obj_m_processed = [];
for (var i in exceljson) {
var obj = { email: exceljson[i].email, name: exceljson[i].team_alias, id: exceljson[i].autodesk_id };
for (var j in metadata) {
if (exceljson[i].email == metadata[j].email) {
obj.GEO = metadata[j].GEO;
obj.COUNTRY = metadata[j].COUNTRY;
obj.CITY = metadata[j].CITY;
obj.PROJECT = metadata[j].PROJECT;
obj.DEPARTMENT = metadata[j].DEPARTMENT;
obj.CC=metadata[j].CC;
obj_m_processed[metadata[j].email] = true;
}
}
obj.GEO = obj.GEO || '-';
obj.COUNTRY = obj.COUNTRY || '-';
obj.CITY = obj.CITY || '-';
obj.PROJECT = obj.PROJECT || '-';
obj.DEPARTMENT = obj.DEPARTMENT || '-';
obj.CC = obj.CC || '-';
user_metadata1.push(obj);
}
for (var j in metadata) {
if (typeof obj_m_processed[metadata[j].email] == 'undefined') {
user_metadata1.push({ email: metadata[j].email, name: metadata[j].name, id: metadata[j].autodesk_id,
GEO: metadata[j].GEO,
COUNTRY : metadata[j].COUNTRY,
CITY : metadata[j].CITY,
PROJECT : metadata[j].PROJECT,
DEPARTMENT : metadata[j].DEPARTMENT,
CC:metadata[j].CC
});
}
}
document.getElementById("headings4").innerHTML = "MetaData Mapping";
BindTable(user_metadata1, '#user_metadata1
cnt++;
});
$('#exceltable').show();
}
if (xlsxflag) {/*If excel file is .xlsx extension than creates a Array Buffer from excel*/
reader.readAsArrayBuffer($("#excelfile")[0].files[0]);
}
else {
reader.readAsBinaryString($("#excelfile")[0].files[0]);
}
}
else {
alert("Sorry! Your browser does not support HTML5!");
}
}
else {
alert("Please upload a valid Excel file!");
}
}
Here is how the json is bind after mapping metadata
function BindTable(jsondata, tableid) {/*Function used to convert the JSON array to Html Table*/
var columns = BindTableHeader(jsondata, tableid); /*Gets all the column headings of Excel*/
for (var i = 0; i < jsondata.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = jsondata[i][columns[colIndex]];
if (cellValue == null)
cellValue = "";
row$.append($('<td/>').html(cellValue));
}
$(tableid).append(row$);
}
}
function BindTableHeader(jsondata, tableid) {/*Function used to get all column names from JSON and bind the html table header*/
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < jsondata.length; i++) {
var rowHash = jsondata[i];
for (var key in rowHash) {
if (rowHash.hasOwnProperty(key)) {
if ($.inArray(key, columnSet) == -1) {/*Adding each unique column names to a variable array*/
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
}
$(tableid).append(headerTr$);
return columnSet;
}

How do you overwrite data instead of appendRow?

Currently the code below appends new data to my spreadsheet every time it runs and I have to manually remove the data before running.
{
var ss = SpreadsheetApp.openById("blank");
var sheetName = ss.getSheetByName("Team Database");
var url = "blank";
var response = JSON.parse(UrlFetchApp.fetch(url));
var current = 1;
if(response.returnData && response.returnData.equipos.length > 0)
{
for(var team in response.returnData.equipos)
{
if(response.returnData.equipos[team].members.length > 0)
{
var i = 0;
while(i < response.returnData.equipos[team].members.length)
{
console.log(response.returnData.equipos[team].name);
console.log(response.returnData.equipos[team].members[i].userId);
sheetName.appendRow([response.returnData.equipos[team].name, response.returnData.equipos[team].members[i].userId]);
i++;
}
}
}
}
if(team.length > 0)
{
sheetName.getRange('D2').setValue('=NOW()');
sheetName.getRange('D1').setValue(sheetName.getRange('D2').getValue());
sheetName.getRange('D2').clear();
}
}
Is there a function that would overwrite it instead like: sheetName.overwriteRow([response.returnData.equipos[team].name, response.returnData.equipos[team].members[i].userId]);?
function myfunc() {
var ss = SpreadsheetApp.openById("blank");
var sh = ss.getSheetByName("Team Database");
var url = "blank";
var response = JSON.parse(UrlFetchApp.fetch(url));
var current = 1;
let oA = [];
if (response.returnData && response.returnData.equipos.length > 0) {
for (var team in response.returnData.equipos) {
if (response.returnData.equipos[team].members.length > 0) {
var i = 0;
while (i < response.returnData.equipos[team].members.length) {
console.log(response.returnData.equipos[team].name);
console.log(response.returnData.equipos[team].members[i].userId);
oA.push([response.returnData.equipos[team].name, response.returnData.equipos[team].members[i].userId]);
i++;
}
}
}
}
if (team.length > 0) {
sh.getRange('D2').setValue('=NOW()');
sh.getRange('D1').setValue(sh.getRange('D2').getValue());
sh.getRange('D2').clear();
sh.getRange(3,1,sh.getLastRow() - 2, sh.getLastColumn()).clearContent();
sh.getRange(3,1,oA.length, oA[0].length).setValues(oA);
}
}

Why google spreadsheets scripts can't sort?

function SUMMARIZE_TOGGL_ENTRIES(proj, desc, time, taskDates, uID) {
if (!desc.map || !time.map || !taskDates.map || !proj.map) {
return 'INPUT HAS TO BE MAP';
}
if (desc.length != time.length || time.length != taskDates.length || proj.length != taskDates.length) {
return 'WRONG INPUT ARRAYS LEN';
}
var resObj = {'NO_DESCRIPTION': '00:00:00'};
var keys = [];
var result = [];
for (var i = 1; i < desc.length; i++) {
var tmpKey = createKey(proj[i], desc[i], uID[i]);
console.log('tmpKey',tmpKey);
if (resObj[tmpKey]) {
resObj[tmpKey] = formatTime(timestrToSec(resObj[tmpKey]) + timestrToSec(time[i]));
} else {
resObj[tmpKey] = formatTime(timestrToSec(time[i]));
}
}
keys = Object.keys(resObj);
var b=0;
for (b; b < keys.length; b++) {
var tmp = [];
var key = keys[b].split('__')[1];
console.log('keys',keys[b].split('__'));
tmp.push(keys[b].split('__')[0]);
tmp.push(key);
tmp.push(resObj[keys[b]]);
tmp.push(taskLastDate(keys[b], desc, taskDates, proj, uID))
tmp.push(keys[b].split('__')[2]);
if(tmp[3] != '01-01-1991 01:01:01' && tmp[3] != ''){
result.push(tmp);
}
}
return result.sort(function (a,b){
var ad = new Date(a[3].split(' ')[0].replace(/-/g,'.'));
var bd = new Date(b[3].split(' ')[0].replace(/-/g,'.'));
if (ad > bd) {
return 1;
}
if (ad < bd) {
return -1;
}
return 0;
});
}
as you can see I'm trying to return a sorted array of arrays. But it don't returns the same array. If i lunch this func on my PC it works. so what's the problem? Does anyone have an idea?
result image
Seems like your sort function will always return 0. Change to
return result.sort(function (a,b){
var ad = new Date(a[3].split(' ')[0].replace(/-/g,'.'));
var bd = new Date(b[3].split(' ')[0].replace(/-/g,'.'));
if (ad > bd) {
return 1;
} else if (ad < bd) {
return -1;
} else {
return 0;
}
});
and see if that works?

Issue with a zero showing after a decimal point

I have a script set up to extract figures from a csv file into a webpage. We have a problem in that a figure that have a 0 after the decimal point is being ignored so whilst the csv file shows 1.094 when teh figure is transferred to the webpage it is 1.94
There is a js script and then an asp script that works the function
function getHTTPObject()
{
var x = null;
if (window.XMLHttpRequest)
{
x = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
x = new ActiveXObject("Microsoft.XMLHTTP");
if (!x)
{
x = new ActiveXObject("Msxml2.XMLHTTP");
}
}
return x;
}
var gobj = getHTTPObject();
window.onload=update();
function update()
{
var xpath = "ratesxtract.asp";
if (gobj) {
gobj.open("GET", xpath, true);
gobj.onreadystatechange = update_all;
gobj.send(null);
}
else {alert("XMLHTTP access problem. Please exit page and try again" ); }
}
function update_all()
{
if (gobj.readyState == 4) {
if (gobj.status == 200) {
// dobj = document.getElementById("BLastUpdated");
var A = gobj.responseText;
// dobj.innerHTML = A;
if (A == "error") {alert("XMLHTTP access problem. Please exit page and contact us" ); }
else { processfile(A); }
}
}
function processfile(A)
{
var errormess = "none";
var AA = new String(A);
AA = AA.split("$");
var nName = null;
var dobj = null;
var nValue = null;
var i = 0;
for (i = 0; i < AA.length; i++) {
if (AA[i].charAt(0) == "Z") {
nName = AA[i];
dobj = document.getElementById(nName);
}
else { nValue = "";
nValue += AA[i];
dobj.innerHTML = nValue;
}
}
if ( i == 0 ) { errormess = "failed to access exchange rates data, please exit page and try again";
alert(errormess)
}
}
ASP SCRIPT
<%#LANGUAGE='JScript'%>
<%
var sfile = Server.MapPath("forex\\ratefile.csv");
var fs = Server.CreateObject("Scripting.FileSystemObject");
var fsT = fs.OpenTextFile(sfile, 1, 0);
var xline;
var p = 0;
var q = 0;
var d = 0;
var i = 0;
var n = 0;
var t = 0;
var ts = 0;
var mname;
var mprice;
var mtime = "";
var INLine
var LN;
var cresult = "";
while(!fsT.AtEndOfStream) {
INLine = fsT.ReadLine();
xline = String(INLine);
if ( p != 0) {
LN = xline.split(",");
mname = xtrim(LN[0]);
mprice = doamount3(LN[1]);
if (p == 1) { mtime = xtrim(LN[2]); }
if (n > 0){ cresult += "$"; }
n++;
cresult += "Z" + mname + "$" + mprice;
}
p++;
}
cresult += "$ZTIM$" + mtime;
fsT.Close();
Response.Write(cresult);
%>
<%
function xtrim(x)
{
var xd = x.replace(/^\s+|\s+$/gm,'');
return xd;
}
function doamount3(amt)
{
var ZLine = String(amt);
ZLine = xtrim(ZLine);
if (ZLine.indexOf(".") == -1) {
ZLine += ".00";
return(ZLine);
}
var idata = ZLine.split(".");
var xadp = new String(idata[1]);
var xlen = xadp.length;
if (xlen == 1) {
idata[1] = xadp + "00";
ZLine = idata[0] + "." + idata[1];
return(ZLine);
}
if (xlen == 2) {
idata[1] = xadp + "0";
ZLine = idata[0] + "." + idata[1];
return(ZLine);
}
var p4 = xadp.charAt(3);
var p3 = parseInt(xadp.substring(0,3), 10);
if (p4 > 4) { p3 += 0; }
idata[1] = String(p3);
ZLine = idata[0] + "." + idata[1];
return(ZLine);
}
%>
If anyone can help be greatly appreciated