google script - send table by email with values from a loop - javascript

I have a web app which take some inputs and I need to write those inputs in a sheet and then send an email with those inputs.
My code is below, I removed some lines in the code because they are not relevant. Assume pnArray and qArray are two arrays with values (strings and numbers).
The problem statement is how to create a HTML table in the loop below and then send that table by email.
function submitInfo() {
var table = "<table><tbody><tr><td>Part Number</td><td>Packs</td></tr>";
var pnArray = ["string1","string2"];
var qArray = [1,2];
for(var i =0;i<pnArray.length;i++){
var pn = pnArray[i];
var q = qArray[i];
table += Utilities.formatString('<tr><td>%s</td>', pn);
table += Utilities.formatString('<td>%s</td></tr>', q);
}
table+="</tbody></table>";
GmailApp.sendEmail("email#email.com", "test", null, {htmlBody:table});
}

function submitInfo() {
var html = "<table><tr><td>Part Number</td><td>Packs</td></tr>";
var pnArray = ["string1","string2"];
var qArray = [1,2];
pnArray.forEach(function(pn,i){html+=Utilities.formatString('<tr><td>%s</td><td>%s</td></tr>'pn,qArray[i]);});
table+="</table>";
GmailApp.sendEmail("email#email.com","test",null,{htmlBody:html});
}

Related

How to access 2nd tab on Google Sheets using App Script/JavaScript?

I want to access simply the 2nd tab to get email and name values to be used to send automated emails. Currently, the code is using the first tab. Additionally, how do I specify that it should take only rows (on the second tab) which have values instead of taking the entire column with many blanks which then throw errors?
function sendemail() {
var spreadSheet = SpreadsheetApp.getActiveSheet();
var dataRange = spreadSheet.getDataRange();
var data = dataRange.getValues();
for (var i = 1; i < data.length; i++) {
(function(val) {
var row = data[i];
var emailAddress = row[1]; //position of email header — 1
var message = 'Hi There!';
var subject = 'Test';
MailApp.sendEmail(emailAddress, subject, message);
})(i);
}
}
To get the second sheet / tab in a Spreadsheet you can use the getSheets method and take the second element of the returned list of Sheets:
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var secondSheet = sheets[1];
To retrieve only populated rows use the getDataRange method to retrieve the Range in which data is present, and retrive the values.
var range = secondSheet.getDataRange();
var values = range.getValues();

How to set values in new column with validation from a Named Range?

Following a previous question
I want to classify text entries by adding a tag in the next column.
I could do it using regex but it will take too much time writing all conditions like :
if(String(data[i][0]).match(/acme|brooshire|dillons|target|heb|costco/gi))
{
labValues[i][0]='Supermarket';
}
Instead I created a named list with all stores names (in another sheet).
If an entry matches a term in the list, the next column is set to "Supermarket".
I am using this script below... No bugs but nothing happens when executed !
function tagStore() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange('A2:A655')
var store = range.getValues();
var tag = sheet.getRange('B2:B655');
var tagvalues= tag.getValues();
var storeList= SpreadsheetApp.getActive().getRangeByName("store_list");
for (var i = 0; i<store.length; i++)
{
if(String(store[i][0]).match(storeList))
{
tagvalues[i][0]='Supermarket';
}
}
tag.setValues(tagvalues);
}
Edit:
It is important to use a Regex as the "store" Values are not exactly the same as the "store_list".
Store Values : ["Acme Store", "HEB PLaza", "Dillons Group"...]
Store_List : [acme, heb, dillons...]
Instead of trying to go with the regEx approach there is a more straightforward approach by retrieving the range as a list.
// For a Column
var storeList = SpreadsheetApp.getActive().getRangeByName("store_list").getValues().map(function(r){return r[0];});
// For a Row
var storeList = SpreadsheetApp.getActive().getRangeByName("store_list").getValues()[0];
And then look if the values you are looking for are in this list with indexOf().
Try this:
function tagStore() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange('A2:A655')
var store = range.getValues();
var tag = sheet.getRange('B2:B655');
var tagvalues= tag.getValues();
var storeList= SpreadsheetApp.getActive().getRangeByName("store_list").getValues().map(function(r){return r[0];});//if it's a column
//var storeList=SpreadsheetApp.getActive().getRangeByName("store_list").getValues()[0];//if it's a row
for (var i=0;i<store.length; i++) {
if(storeList.indexOf(store[i][0])!=-1) {
tagvalues[i][0]='Supermarket';
}
}
tag.setValues(tagvalues);
}

Error: "You have an error in your SQL syntax; near ''' at line 1"

I'm having a problem with my JavaScript code, it says the error is:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''' at line 1
I'm trying to call this query: 'SELECT * FROM wp_fsqm_direct_52'
It connects to the database fine and show the database data in the sheet when I call the query like this: var sql = 'SELECT * FROM wp_fsqm_direct_52';
But when I call the exact same query from a cell in the A1 cell in the sheet var sql = sheetData.getRange("A1").getValue();, it returns me the error.
Sorry for my bad English, I'm from Venezuela, and this is my first time here.
This is my code:
function readFromTable() {
var ss = SpreadsheetApp.getActive();
var sheetDetails = ss.getSheetByName('Details');
var sheetData = ss.getSheetByName('Query Sheet');
var host = sheetDetails.getRange("B1").getValue();
var databaseName = sheetDetails.getRange("B2").getValue();
var userName = sheetDetails.getRange("B3").getValue();
var password = sheetDetails.getRange("B4").getValue();
var tableName = sheetDetails.getRange("B6").getValue();
var url = 'jdbc:google:mysql://' + host + '/' + databaseName;
Logger.log(url);
Logger.log(userName);
Logger.log(password);
var sql = sheetData.getRange("A1").getValue();
try {
var connection = Jdbc.getCloudSqlConnection(url, userName, password);
var results = connection.createStatement().executeQuery(sql);
var metaData = results.getMetaData();
var columns = metaData.getColumnCount();
// Retrieve metaData to a 2D array
var values = [];
var value = [];
var element = '';
// Get table headers
for (i = 1; i <= columns; i++) {
element = metaData.getColumnLabel(i);
value.push(element);
}
values.push(value);
// Get table data row by row
while (results.next()) {
value = [];
for (i = 1; i <= columns; i++) {
element = results.getString(i);
value.push(element);
}
values.push(value);
}
// Cloese connection
results.close();
// Write data to sheet Data
SpreadsheetApp.flush();
sheetData.getRange(2, 1, values.length, value.length).setValues(values);
SpreadsheetApp.getActive().toast('Data has been updated.');
} catch (err) {
SpreadsheetApp.getActive().toast(err.message);
}
}
A1 should be plain text without quotes. You seem to have added extra quotes' in A1.
SELECT * FROM wp_fsqm_direct_52
I find that running SQL on my website's database that it likes me put backticks around field names and single quotes around strings that I supply. So here's an example that I just tried.
Unfortunately, the backticks are hard show so here because they invoke the code window so here is an image showing what I mean.

Delete Row in Google Sheets Based on Cell Text (if contains)

I am trying to create a script that will automatically delete the row if the cell contains, but does not exactly match, the condition. For example, the script would delete the rows if the cell contains gmail.com, as part of a larger email
123#gmail.com
123#yahoo.com
456#gmail.com
456#yahoo.com
The two yahoo emails would be saved because they do not meet the condition. However, I am unsure of the proper conditional dictation to use when writing my script. Here is what I have so far.
function deleteRows() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('Sheet1');
var r = s.getRange('B:B');
var v = r.getValues();
for(var i=v.length-1;i>=0;i--)
if(v[0,i] 'gmail.com')
s.deleteRow(i+1);
};
I would put a ==, but this will only delete rows that match exactly with gmail.com. What would I use in place of the == to make it essentially a text contains condition?
Try this:
function deleteMatchingRows(string) {
var string=string||'gmail.com';
var ss = SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Sheet1');
var lngth=sh.getLastRow();
var rg=sh.getRange(1,2,lngth,1);
var vA=rg.getValues();
var n=0;
for(var i=1;i<vA.length;i++){
if(vA[i][0] && vA[i][0].indexOf(string)>-1){
sh.deleteRow(i-n+1);
n++;
}
}
}

google app script compare value to array values

I've got this working code:
function hUpdate() {
var ss = SpreadsheetApp.getActiveSheet();
var hRowNum = ss.getLastRow();
var hNew = ss.getRange(hRowNum,3).getValue(); // value being compared
var hCompare = ss.getRange(hRowNum-1,3).getValue();
if (hNew == hCompare)
{hNew = 'same';}
else
{hNew = 'different';}
return hNew;
}
What I really want to do is compare hNew with all values in previous rows of the same column. I know I have to use an array but I'm stuck with the actual coding.

Categories