Google Script - Insert indents to appended texts - google-apps-script

I'm trying to pass information from a google spreadsheet to a google doc.
This is the view of the table:
The first column only shows once and when it's list of items for that category will be shown.
I managed to present this information in a table inside the doc but it's required to show it as text since the minimum height of each table row is still too much.
This information will travel as an array with two columns and I'll iterate thru it. This is what I've tried:
//servicios_numrows_Q -> number of rows for the data
//value_tabla_servicios -> variable that contains the information
for(var t = 0; t < servicios_numrows_Q - 1; t++){
if(body.appendParagraph(value_tabla_servicios[t+1][0]) == ''){ //Am I in a row that hasn't a Category Title?
"\t" + body.appendParagraph(value_tabla_servicios[t+1][1]);
}else
{
body.appendParagraph(value_tabla_servicios[t+1][0]) + "\t"
+ body.appendParagraph(value_tabla_servicios[t+1][1]);
}
}
However, adding a tab only results in each element being shown in a separate line.
Is there a way to show the first and second column in the same line? Adding spaces instead of tab?

You want to convert the top image (Spreadsheet) of your question as the paragraphs of Google Document using Google Apps Script.
If my understanding is correct, how about this answer?
Modification points:
When you add \t to the top of text using appendParagraph, please use as follows.
"\t" + body.appendParagraph(value_tabla_servicios[t+1][1]); is modified to body.appendParagraph("\t" + value_tabla_servicios[t+1][1]);.
body.appendParagraph(value_tabla_servicios[t+1][0]) + "\t" + body.appendParagraph(value_tabla_servicios[t+1][1]); is modified to body.appendParagraph(value_tabla_servicios[t+1][0] + "\t" + value_tabla_servicios[t+1][1]);
In your script, when value_tabla_servicios[t+1] is declared as a variable, the readability of script can be increased.
If you want to align the column "B", "\t\t" might be suitable instead of "\t".
When above points are reflected to your script, it becomes as follows. Please think of this as just one of several answers.
Modified script:
for(var t = 0; t < servicios_numrows_Q - 1; t++){
var row = value_tabla_servicios[t+1]; // Added
if (row[0] == ''){ // Modified
body.appendParagraph("\t\t" + row[1]); // Modified
} else {
body.appendParagraph(row[0] + "\t" + row[1]); // Modified
}
}
By the length of value of row[0], "\t\t\t" of body.appendParagraph("\t\t" + row[1]) might be suitable. About this, please check your actual situation.
Reference:
appendParagraph()
If I misunderstood your question and this was not the direction you want, I apologize. If the error occurs, can you provide a sample Spreadsheet, output you want and your whole script? By this, I would like to confirm it. Of course, please remove your personal information.

Related

Copy filtered data to another sheet but creates a blank row if it met a condition

For example, I have this data,
I want to filter the data which is "USA" and copy it to another sheet but I have to creates a blank row if it met a condition. For example like this
Is it possible?
I have also tried
IF(AND(F2=FALSE, NOT(ISBLANK(F2))), "", INDEX(QUERY('Sheet 1'!A2:E, "Select A where A contains '"&"USA"&"'"),COUNTIF($F$2:F2,TRUE),1))
But it didn't work as I expected
Here is a formula version:
=ArrayFormula(
array_constrain(
sortn(
filter(
{if(A:A="USA",A:A,),if(A:A="USA",B:B,),A:A="USA",
if(A:A="USA",row(A:A),iferror(vlookup(row(A:A),if(A:A="USA",row(A:A),),1,true),0)+1)},
A:A<>""),
1000,2,4,1),
1000,3)
)
The reason for the long formula is mainly finding a way to get just one row to replace one or more rows that don't start with USA. The basis of the formula is to do a lookup for non-USA rows to get the row number of the most recent USA row. All of the non-USA rows in the same block then have the same row number and can be discarded (apart from the first) using Sortn.
I have added an extra non-USA row at the beginning to check that this edge case works and falls through to the Iferror clause.
Since you provided Google Apps Script as tag, I assume you are open to script answers? If so, then I'll provide this code below. Is this what you are looking for?
function copyUSA() {
var sheetSrc = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var sheetDst = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
var rowSrc = sheetSrc.getLastRow();
var values = sheetSrc.getRange("A2:A" + rowSrc).getValues().flat();
values.forEach(function (value, index){
var rowDst = sheetDst.getLastRow() + 1;
if(value == "USA"){
// If USA, copy then replace third column with TRUE
var row = index + 2;
sheetSrc.getRange(row + ":" + row).copyTo(sheetDst.getRange(rowDst + ":" + rowDst));
sheetDst.getRange("C" + rowDst).setValue("TRUE");
}
else{
// If not, set third column to FALSE
sheetDst.getRange("C" + rowDst).setValue("FALSE");
}
});
}
Sheet1:
Sheet2:
My assumptions were based from your formula. These are:
I assumed that you add blank when it is not USA. Thus having 2 blanks on the output
If USA, 3rd column is TRUE, else, FALSE with blank data
Based on your formula, it seems your data starts at A2, thus I adjust the code too.
You are also getting the 4th and 5th column on your formula but since you didn't show it in your post, I can't assume any values for it.
If the answer isn't the one you are looking for, I apologize.

Google Sheets SHOW the apostrophe before text

I have a column in Google Sheets with strings.
Some of the rows start with an apostrophe ', some don't. But Google assumed that the apostrophe is because it's a text instead of letting it be part of the text.
How do I make it show these apostrophes?
You mentioned:
Some of the rows start with an apostrophe ', some don't...
How do I make it show these apostrophes?
By adding an extra apostrophe ' in the beginning of the cells.
EDIT
Following the comments by OP
That's inviable for 10000 rows.
and Liron
You can do that with "Find and replace" - search for ^' (caret and apostrophe) and replace it with '' (two apostrophes), and select "Search using regular expressions" and "Also search within formulas".
That would change every apostrophe at the beginning of a cell to two apostrophes.
I wrote the following script as an answer. I assume that you have a column with a mix of strings, some being enclosed in ' and some don't, like this example:
As shown on the picture, Sheets automatically hides the first '. To prevent this you have to add another ' at the start of the string. You can do it with this code:
function myFunction() {
var dataSheet = SpreadsheetApp.openById(
"{SPREADSHEET IDENTIFICATOR}").getSheets()[0];
var dataColumn = 2;
var dataRange = dataSheet.getRange(1, dataColumn, dataSheet.getLastRow());
var data = dataRange.getValues();
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].length; j++) {
if (data[i][j].substr(-1, 1) == "'") {
data[i][j] = "''" + data[i][j];
}
}
}
dataRange.setValues(data);
}
The former code will first use a combination of .openById(), .getSheets(), .getRange() and .getValues() to open the spreadsheet, open the sheet, get the data range and read its values respectively. Then, the code will iterate over every value to check if it ends in a ', and if it does, the script will add an extra ' at the start of the string. The end result looks like this:
Please, ask me any question for additional help.

Turning an email address in a cell into a clickable link

I have a column of email addresses and would really like to turn them into clickable links. I am a rookie coder still and trying to figure this out. So the code below is from trying to record a macro in google app script. I need it to reference the current cell, turn that cells email address into a link to it, then move down the column.
Should be super simple, take cell A1's contents, turn into link of the contents in the cell, then move down the list and do it again until it completes the entire column.
function emailing() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getActiveRangeList().setShowHyperlink(true);
spreadsheet.getCurrentCell().setFormulaR1C1('=HYPERLINK("mailto:test#emailaddress.com","test#emailaddress.com")');
};
Each email will be turned into a link to that email address.
I have tested the following code and worked successfully converting each email to a hyperlink. Assuming you want to convert all of them when you use the macro, this code works for you:
function emailing() {
var sheet = SpreadsheetApp.getActiveSheet();
for(i=0; i<1048576; i++) {
var gcells = sheet.getRange(6 + i, 6); //In my test i put the emails in the F column starting from the 6th row.
var email = gcells.getValue();
if (gcells.isBlank()) {
break
}
gcells.setFormulaR1C1('=HYPERLINK("mailto:' + email + '","' + email + '")');
}
}
I used the number 1048576 as the limit on the for because that's the maximum number of rows you can have, although it'll break when it takes a blank cell.
If what you want is to convert to a hyperlink only the cell you have selected and then change the selected cell, you should use the getActiveCell function [1] to set only that value and then the activate() function [2] to change the selection to the next cell.
[1] https://developers.google.com/apps-script/reference/spreadsheet/sheet#getactivecell
[2] https://developers.google.com/apps-script/reference/spreadsheet/range#activate()

Adding new line to text in Google spreadsheet cell via apps script

I have an apps script which takes email addresses from one spreadsheet from multiple cells and adds them them to another spreadsheet into 1 cell only.
Currently the email addresses are added to that cell and separated by a ", ".
I would like to add the email addresses into that same cell but add a new line after each address.
I know it is possible to have new lines in a cell when manually adding text, by typing CTRL-Enter.
How can this be achieved in apps script?
I have so far tried to append "\n" or "\r" or "\r\n" to the string, to no avail, so I have reverted my code back to adding ", " instead.
sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.appendRow(["Num Emails", "Emails"]);
var LMEmails = "";
var count = 0;
for (var i = 0; i < reviewers.LMEmails.length; i++) {
if (count) {
LMEmails += ", " + reviewers.LMEmails[i];
} else {
LMEmails += reviewers.LMEmails[i];
}
count++;
}
data = [count, LMEmails];
sheet.appendRow(data);
If anyone could help, I would very much appreciate it
Regards
Crouz
After searching for the same question, this was my solution:
var stringToDisplay = 'FirstBit' + String.fromCharCode(10) + 'SecondBit';
then
workSheet.getRange(1,1).setValue(stringToDisplay);
output will be in a single cell, :
FirstBit
SecondBit
Google Spreadsheets seems to ignore the new line if there are no characters after it.
Using "/n" works fine as long as you add at least one other character after it, this could be a space as shown below.
For example:
var myString = 'First Bit' + "\n " + "Second Bit";
It should be:
data = [[count, LMEmails]];

How to create a comma separated string in Google Apps Script

I need LOTS of help on this one, but I think it's a procedure that would be helpful to other green-programers in the future.
I have a Google Form for people to fill that are new to our neighborhood. It, obviously, feeds a Google Docs spreadsheet. (Here's a link to a copy of the sheet that's just edited to black-out some of the personal data:
https://docs.google.com/spreadsheet/ccc?key=0AjsoIob8dJfodG9WN0ZmWUE1ek9rc3JrVFpDQ0J0OGc
)
One of the questions is which of our groups are you interested in joining. The Form asks the question, then allows the user to check off which of about 10 groups the new member is interested in joining. The data is then fed into the sheet listing all of the groups the new member wants to join in a single cell (that's column F).
The administrative task that I now need to tackle is going through all of the responses and pulling out the members who have said--for example--they're interested in joining the "Helping Hands" group, copying their e-mail address (which is in column X) and pasting it into the Google Groups sign-up sheet for that group.
This is understandable tedious. Especially because--again--we have about 15 of these Google Groups lists that need to be populated.
What would be great would be if I could write a little Google Apps Script that will go through the data in the sheet and give me a comma separated list of all the e-mail addresses that meet the correct criteria so that I could just copy-and-paste that into the Google Group sign up page.
In plain English, the regular expression should say this:
- IF column F contains Helping Hands
- AND IF column G does NOT contain Yes
- THEN add the contents of column X to an exported string, followed by a comma
- Repeat for every row in the sheet.
So here's the questions:
1) How do I do this?
2) How does this get triggered?
For the first step, I've already determined that the following regular expression will give me what I need:
/(^|, )Helping Hands($|, )/
I'm not sure how to augment that, though, to include the second required IF statement. I also don't know how to write the THEN statement. And--as I said above--I have NO idea how to trigger all of this.
Thanks in advance to anybody who can help! And the Newcomers to Sewickley also thank you! Please let me know if I can clear anything up.
Why don't you go further and set up a on form submit trigger that reads the groups and adds them automatically using the (yet experimental) Groups Services for Apps Script?
Such script is not very difficult to implement, maybe you should check the user guides and tutorials.
Looks like you are happy copy-pasting the list of email addresses if you get it in a comma separated format. So you can trigger it yourself when you need it.
You can use this code snippet
var options = ['Helping Hands','Book Club',...]; // Add all 10 options here
var GROUPS_COL = 5 ; //Column F
var COLG = 6;
var EMAIL_COL = 23 ; //Column X
var emailList = ['', '','',''...] ; // 10 blanks
var data = SpreadsheetApp.openById('ID_HERE').getSheetByName('SheetName').getvalues();
for (var i = 1; i < data.length ; i++){
for( var j = 0 ; j < options.length ; j++){
if (data[i][GROUPS_COL].indexOf(options[j]) != -1 &&
data[i][COLG] != 'Yes') {
// The entry in row i+1 has checked option[j]
if (emailList[j] != ''){
emailList[j] += ',' ; // Add your comma
}
emailList[j] += data[i][EMAIL_COL];
}
}
}
/* Now you have your comma separated list in emailList */
for ( var i = 0 ; i < 10; i ++){
Logger.log(option[i] + ':' + emailList[i])
}
Obviously, you have to tweak this code to suit your needs, but will give you a fair idea of how to proceed. The code has not been tested.
You have no idea how unbelievable stoked I am that this finally worked out. Thanks a million times over to #Sirik for sticking with it and writing the code and helping me debug it. It does EXACTLY what I want it to and it's just the coolest thing in the world to make it do EXACTLY what I wanted it to.
For the sake of posterity or anybody else who might want to be doing something similar to what I was doing, here's the exact code, all smoothed out, as implemented. You'll see that I added just a few extra bits at the end to e-mail the log to me and give me a dialogue box acknowledging that the script had run (I don't like that feeling of clicking the button and not SEEING something happen).
function Export_Groups_List() {
var options = ['1 & 2 Year Olds\' Playgroup','3 & 4 Year Olds\' Playgroup','Babies\' Playgroup','Book Club','Couples Night Out','Directory','Girls Night Out','Helping Hands','Membership','Newsletter','Serving Sewickley','Treasurer'];
var GROUPS_COL = 5; //This is column 5
var COLG = 6; //Column G
var EMAIL_COL = 23; //Column X
var emailList = ['', '', '', '', '', '', '', '', '', '', '', ''] //12 blanks
var data = SpreadsheetApp.openById('___').getSheetByName('Master').getDataRange().getValues();
for (var i = 1; i < data.length ; i++){
for( var j = 0 ; j < options.length ; j++){
if (data[i][GROUPS_COL].indexOf(options[j]) != -1 &&
data[i][COLG] != 'Yes') {
if (emailList[j] != ''){
emailList[j] += ', ' ;
}
emailList[j] += data[i][EMAIL_COL];
}
}
}
for ( var i = 0 ; i < 12; i ++){
Logger.log(options[i] + ': ' + emailList[i])
}
MailApp.sendEmail("matt#twodoebs.com", "Groups Export", Logger.getLog() + " \n\n" +
"At your request, you've been added to this Sewickley Newcomers & Neighbors Google Group." + "\n\n" +
"Using Google Groups allows us to always have up to date e-mail lists, make sure that people don't get bombarded with messages they don't want, and facilitate smooth communication between our members. If you have any questions about how to use the Google Groups service with your Newcomers & Neighbors membership, please send an e-mail to SewickleyNAN#gmail.com." + "\n\n" +
"Thank you and thanks for your participation!") ;
Browser.msgBox("OK. Check your e-mail for the export list. doebtown rocks the house!")
}
Evan Plaice provides a nice Google Apps Script that you can use in your own spreadsheet which essentially renders a menu that allows you to transpose a column using a "Text to Column" feature. https://webapps.stackexchange.com/questions/22799/text-to-columns-conversion-in-google-spreadsheets