I am trying to parse forex values (all of them) for http://indicador.eof.cl/rss XML feed into a Gooogle Sites trough Google Apps Script.
The script as follow>
function doGet(){
var response = UrlFetchApp.fetch("http://indicador.eof.cl/rss").getContentText();
var parsedResponse = Xml.parse(response, false);
var root = parsedResponse.getElement();
var entries = root.getElement('channel').getElements("item");
for (var i=0; i<entries.length; i++) {
var e = entries[i];
var title = e.getElement("title").getText();
var description = e.getElement("description").getText();
}
var app = UiApp.createApplication();
var TopVar = app.createHorizontalPanel();
TopVar.add(app.createLabel(title).setStyleAttribute("fontSize","12px"));
TopVar.add(app.createLabel(description).setStyleAttribute("fontSize","12px"));
app.add(TopVar);
return app;
}
The issue is the code just bring me the first value no all of them, what i am forgetting?
Best Regards,
Try to move TopVar.add(...); lines inside for loop :
var app = UiApp.createApplication();
var TopVar = app.createHorizontalPanel();
for (var i=0; i<entries.length; i++) {
var e = entries[i];
var title = e.getElement("title").getText();
var description = e.getElement("description").getText();
TopVar.add(app.createLabel(title).setStyleAttribute("fontSize","12px"));
TopVar.add(app.createLabel(description).setStyleAttribute("fontSize","12px"));
}
Actually, I know nothing about google-apps-script. But your current code logic seems a bit off. It doesn't make use of values of local variables declare inside for loop (e, title, and description). Value of those variables changed in every iteration without any code using it.
Related
I have an indesign document with multiple pages. each page has a linked pdf in it. each pdf has 3 layers within it and in order to turn these layers on or off, you have to right click, select Object Layer Options, and then manually turn on or off layers.
I would like to loop through all my pages and turn on a layer in the PDF using a script. i have been messing with graphicLayerOptions.graphicLayers but keep running into an error when telling it to turn the currentVisibilty=true;
var myDocument = app.activeDocument;
var docLength = myDocument.pages.length;
var myPages = myDocument.pages
for (var i = 0; i < docLength; i++) {
var labelPlaceholder = myDocument.allGraphics;
var labelArtwork = labelPlaceholder[0];
var artworkLayers = labelArtwork.graphicLayerOptions.graphicLayers;
artworkLayers.item("Die Copy").currentVisibility = true;
}
i got it working...l
var myDocument = app.activeDocument;
var docLength = myDocument.pages.length;
var myPages = myDocument.pages
for (var i = 0; i < docLength; i++) {
var labelPlaceholder = myPages[i].allGraphics;
var labelArtwork = labelPlaceholder[0];
var artworkLayers = labelArtwork.graphicLayerOptions.graphicLayers;
artworkLayers[0].currentVisibility = true;
}
Just in case. In InDesing (Illustrator, etc) you have two options to get an item from a collection.
By its number:
var layer = app.activeDocument.layers[0];
By its name:
var layer = app.activeDocument.layers.itemByName("Die Copy");
Later options is less reliable. Not all collections has this method. I don't know if it (PDF layers) is the case, though.
CONTEXT
I'm using a script to fetch emails that I found here (from Niclas, I think): fetching emails script
I've adapted it to my needs and it works very well!
WHAT I'VE TESTED
I saw getDescription() from the Google script Class Attachment but couldn't get it to work and I'm not even sure if that's the way to go
WHAT I WOULD WANT
In addition, I would like to fetch the attachments filenames since It's a distinctive mark on each email
Any help would me very appreciated. Thanks in advance
Modifications:
Do the following modifications to the answer of the post you mentioned in your question:
Add these lines:
var attachments = messages[maxIndex].getAttachments();
var attNames = attachments.map(att=>att.getName());
and modify this one:
ss.appendRow([from, cc, time, sub,...attNames ,'https://mail.google.com/mail/u/0/#inbox/'+mId])
Solution:
function myFunction() {
// Use sheet
var ss = SpreadsheetApp.getActiveSheet();
// Gmail query
var query = "label:support -label:trash -label:support-done -from:me";
// Search in Gmail, bind to array
var threads = GmailApp.search(query);
// Loop through query results
for (var i = 0; i < threads.length; i++)
{
// Get messages in thread, add to array
var messages = threads[i].getMessages();
// Used to find max index in array
var max = messages[0];
var maxIndex = 0;
// Loop through array to find maxIndexD = most recent mail
for (var j = 0; j < messages.length; j++) {
if (messages[j] > max) {
maxIndex = j;
max = messages[j];
}
}
// Find data
var mId = messages[maxIndex].getId() // ID used to create mail link
var from = messages[maxIndex].getFrom();
var cc = messages[maxIndex].getCc();
var time = threads[i].getLastMessageDate()
var sub = messages[maxIndex].getSubject();
var attachments = messages[maxIndex].getAttachments();
var attNames = attachments.map(att=>att.getName());
// Write data to sheet
ss.appendRow([from, cc, time, sub,...attNames ,'https://mail.google.com/mail/u/0/#inbox/'+mId])
}
}
Don't forget to change the value of query to your needs.
References:
Class GmailMessage
map()
Rest parameters
You have to enable V8 runtime to be able to use the snippet.
I am a novice here to google app scripts and my JavaScript is also not very strong, but neither of these seem to be the problem here as my code works the first time I run it but then when I try to call it again it fails.
Simply I am trying to have a function that will dynamically find a given text in a given range. While it looks like there might be a built in package that does this I cannot figure out how to implement it. And the documentation is not helpful for someone new.
Option 1: was to implement the following: https://developers.google.com/apps-script/reference/spreadsheet/text-finder#findAll()
Since that has not been sucessful in finding out how to do it I moved to creating the following simple two functions, Option 2:
function findIndexRow(range,fText){
for(var i = 0; i<range.length;i++){
for(var j = 0; j<range.length;j++){
if(range[i][j] == fText){
var fTextRow = i+1;
var fTextCol = j+1;
}
}
}
return fTextRow
}
function findIndexCol(range,fText){
for(var i = 0; i<range.length;i++){
for(var j = 0; j<range.length;j++){
if(range[i][j] == fText){
var fTextRow = i+1;
var fTextCol = j+1;
}
}
}
return fTextCol
}
It takes in a range that I defined like:
var sheet = SpreadsheetApp.openById('the-gsheet-id');
var CurrSheet = sheet.getSheetByName('Sheet1');
var SHTvalues = CurrSheet.getDataRange().getValues();
So the above works when I call it once in my main code but the second time it returns null, help here as to why re calling the same function does not work.
var text1Row = findIndexRow(SHTvalues,"text1");
var text1Col = findIndexCol(SHTvalues,"text1");
Logger.log(text1Row)
Logger.log(text1Col)
var text2Row = findIndexRow(SHTvalues,"text2");
var text2Col = findIndexCol(SHTvalues,"text2");
Logger.log(text2Col)
Logger.log(text2Row)
I can't understand why my logs return the correct values for text1Row and text1Col but when it is called a second time the text2Row and text2Col both return null
I believe your goal as follows.
You want to search a text value from a sheet in the Google Spreadsheet, and want to retrieve the row and column numbers of the found values.
You want to achieve this using TextFinder.
For this, how about this answer?
Sample script:
var findText = "text1";
var sheet = SpreadsheetApp.openById('the-gsheet-id');
var CurrSheet = sheet.getSheetByName('Sheet1');
var SHTvalues = CurrSheet.createTextFinder(findText).findAll();
var result = SHTvalues.map(r => ({row: r.getRow(), col: r.getColumn()}));
console.log(result)
Note:
About my logs return the correct values for text1Row and text1Col but when it is called a second time the text2Row and text2Col both return null in your script, if there are the values of text1 and text2 in Sheet1, text1Row, text1Col, text2Col and text2Row has the values. If only the value of text1 is put in Sheet1, text1Col and text2Col has the values. But text2Col and text2Row has no values (null). Please be careful this.
But in this case, when 2 values of `text1 are put to the cells "A1" and "A2", only "A2" is returned. Also please be careful this.
In this sample script, please enable V8.
References:
createTextFinder() in Class Sheet
Class TextFinder
Here's a script that I used for searching through my spreadsheets when I'm having trouble finding the sheet I want. It does read another sheet to get a list of spreadsheets to search through.
function regexSearch(sObj) {
var ass=SpreadsheetApp.getActive();
var startRow=2;
var msrsh=ass.getSheetByName('MultiSearchResults');
msrsh.clearContents();
msrsh.appendRow(['Path','FileName','FileId','SheetName','CellA1Notation','Value','Pattern']);
msrsh.activate();
var sh=ass.getSheetByName('SelectedSpreadsheets');
var hA=sh.getRange(1,1,1,sh.getLastColumn()).getValues()[0];
var getArrayIndex={};
hA.forEach(function(e,i){getArrayIndex[e]=i;});
var rg=sh.getRange(startRow,1,sh.getLastRow()-startRow+1,sh.getLastColumn());
var ssA=rg.getValues();
var matches='';
var n=0
for(var k=0;k<ssA.length;k++) {
var fileid=ssA[k][getArrayIndex['FileId']];
var filename=ssA[k][getArrayIndex['FileName']];
var filepath=getFilePathFromId(ssA[k][getArrayIndex['FileId']]);
//Logger.log(fileid);
var ss=SpreadsheetApp.openById(fileid);
Logger.log(sObj.pattern);
var tf=ss.createTextFinder(sObj.pattern).useRegularExpression(true);
var all=tf.findAll();
for(var i=0;i<all.length;i++) {
if(i==0)n++;
matches+=Utilities.formatString('<br /><b>Path:</b> %s <b>Sheet:</b> %s <b>Cell:</b> %s <b>Value:</b> %s<hr width="100%"/>',filepath,all[i].getSheet().getName(),all[i].getA1Notation(),all[i].getValue());
msrsh.appendRow([filepath,filename,fileid,all[i].getSheet().getName(),all[i].getA1Notation(),all[i].getValue(),sObj.pattern]);
}
}
if(matches) {
sObj.matches=matches;
sObj.message=Utilities.formatString('<p>Pattern %s was found in %s spreadsheet out of a total of %s</p>',sObj.pattern,n,ssA.length);
}else{
sObj.message=Utilities.formatString('No Matches found for %s',sObj.pattern);
}
return sObj;
}
I am very new to Google Apps Scripts and am curious how I can use functions created in my own project. For example, I have a script bound to a spreadsheet with just one function:
function addOrder(title, content) {
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow([ Date(), title, content]);
}
It simply takes 2 arguments and adds a row to the spreadsheet with that data. I have deployed it as a web app, but I'm not sure how to use this function in an environment like JSFiddle. Any help is appreciated.
Thanks
Spreadsheet bound scripts run server side and the SpreadsheetApp.getActiveSheet() method you are using will only work in the context of a spreadsheet bound script since it's the only case where the script actually "sees" an active spreadsheet. When you deploy this as a webapp you will have to tell the script which spreadsheet it must look at using for example the SpreadsheetApp.openById('spreadsheet ID') method.
But even doing so will not allow for using such a code outside of Google environment (as in JS fiddle for example) since SpreadsheetApp is specific to Google Apps service.
You have to remember that Google Apps Script is based on JavaScript but is not "plain" JavaScript , it uses a lot of specific services that work only in relation with Google Apps.
edit to answer your comment below :
the code used in the spreadsheet to work as a data server goes like this : (this is deployed as a webapp without user interface. It runs as a service
function doGet(e) {
if(e.parameter.mode==null){return ContentService.createTextOutput("error, wrong request").setMimeType(ContentService.MimeType.TEXT)};
var mode = e.parameter.mode;
var value = e.parameter.value;
var ss = SpreadsheetApp.openById('1yad5sZZt-X6bIftpR--OSyf3VZWf3Jxx8UJBhh7Arwg');
var sh = ss.getSheets()[0];
if(mode=='read'){
var sheetValues = sh.getDataRange().getValues();// get data from sheet
var valToReturn = ContentService.createTextOutput(JSON.stringify(sheetValues)).setMimeType(ContentService.MimeType.JSON);
return valToReturn;// send it as JSon string
}
if(mode=='write'){
var val = Utilities.base64Decode(value,Utilities.Charset.UTF_8);// decode base64 and get an array of numbers
Logger.log(val);// see it !
var stringVal = ''; // create an empty string
for(var n in val){
stringVal += String.fromCharCode(val[n]);// add each character in turn
}
var sheetValues = JSON.parse(stringVal);// convert the string into an object (2D array)
Logger.log(sheetValues);// check result
sh.getRange(1,1,sheetValues.length,sheetValues[0].length).setValues(sheetValues);// update the sheet
return ContentService.createTextOutput(JSON.stringify(sheetValues)).setMimeType(ContentService.MimeType.JSON);// send back the result as a string
}
return ContentService.createTextOutput('error').setMimeType(ContentService.MimeType.TEXT);// in case mode is not 'read' nor 'write'... should not happen !
}
you can call this service by its url + parameters and it will get / set values in the spreadsheet. This is a basic example but it works nicely.
below it the webapp code of the Ui that uses this service in this spreadsheet
var stylePanel = {'padding':'50px', 'background':'#FFA'};
var styleButton = {'padding':'5px', 'border-radius':'5px', 'borderWidth':'1px', 'borderColor':'#DDD','fontSize':'12pt'};
var styleTextItalic = {'fontSize':'12pt','fontStyle':'italic','fontFamily':'arial,sans-serif','color':'#F00'};
var styleTextNormal = {'fontSize':'12pt','fontStyle':'normal','fontFamily':'arial,sans-serif','color':'#00F'};
var styleLabel = {'fontSize':'12pt','color':'#F00'};
var url = 'https://script.google.com/macros/s/AKfycbwPioVjYMSrmhKnJOaF2GG83dnstLWI7isU9SF1vxPV8td-g9E7/exec';
var numRow = 21;// the number of rows in the grid = number of rows in the SS + 1
;
function doGet() {
var app = UiApp.createApplication().setTitle('url_fetch_demo');
var panel = app.createVerticalPanel().setStyleAttributes(stylePanel);
var headers = ['Field Name','Your answer'];// grid title
var grid = app.createGrid(numRow+2,2);// create the grid with right size
var wait = app.createImage('https://dl.dropboxusercontent.com/u/211279/loading3T.gif').setId('wait').setVisible(false);// get a spinner image in animated gif
var handlerWrite = app.createServerHandler('writeSheet').addCallbackElement(grid);// 2 handlers for the buttons
var handlerRead = app.createServerHandler('readSheet').addCallbackElement(grid);
var Chandler = app.createClientHandler().forTargets(wait).setVisible(true);// a client handler for the spinner
var buttonWrite = app.createButton('Write to Sheet',handlerWrite).addClickHandler(Chandler).setStyleAttributes(styleButton);
var buttonRead = app.createButton('Read from Sheet',handlerRead).addClickHandler(Chandler).setStyleAttributes(styleButton);
for(var n=1 ; n < numRow ; n++){
for(var m=0 ; m < 2 ; m++){ // create all the textBoxes with names & IDs
var textBox = app.createTextBox().setText('no value').setName('text'+n+'-'+m).setId('text'+n+'-'+m).setStyleAttributes(styleTextNormal);
//if(m==0){textBox.setEnabled(false)};// prevent writing to left column (optional)
grid.setWidget(n,m,textBox);// place widgets
}
}
grid.setWidget(numRow,0,buttonRead).setWidget(numRow,1,buttonWrite).setWidget(numRow+1,1,wait) // place buttons
.setWidget(0,0,app.createLabel(headers[0]).setStyleAttributes(styleLabel)) // and headers
.setWidget(0,1,app.createLabel(headers[1]).setStyleAttributes(styleLabel));
app.add(panel.add(grid));
return app; // show Ui
}
function writeSheet(e){
var app = UiApp.getActiveApplication();
app.getElementById('wait').setVisible(false);// spinner will be hidden when fct returns
var dataArrayImage = [];// an array to get typed values
for(var n=1 ; n < numRow ; n++){
var row=[];
for(var m=0 ; m < 2 ; m++){
row.push(e.parameter['text'+n+'-'+m]); // get every value in every "cell"
var textBox = app.getElementById('text'+n+'-'+m).setStyleAttributes(styleTextItalic);// update "cells" style
//textBox.setText('written value = '+e.parameter['text'+n+'-'+m]);// rewrite to the cells - not usefull but serves to check while debugging
}
dataArrayImage.push(row);// store one row(=2cells)
}
var UiValues = JSON.stringify(dataArrayImage);// stringfy the array
var newValues = url+'?mode=write&value='+Utilities.base64Encode(UiValues,Utilities.Charset.UTF_8);// add to url & parameters+ encode in pure ASCII characters
Logger.log(newValues);// check in logger
var check = UrlFetchApp.fetch(newValues).getContent();// get back the result
Logger.log(check);// check result = newValues sent back in bytes format
return app;//update Ui
}
function readSheet(e){
var app = UiApp.getActiveApplication();
app.getElementById('wait').setVisible(false);
var returnedValue = UrlFetchApp.fetch(url+'?mode=read').getContentText();// get data from server
Logger.log(returnedValue);// check values
var sheetValues = JSON.parse(returnedValue);
for(var n=1 ; n < numRow ; n++){
for(var m=0 ; m < 2 ; m++){
var textBox = app.getElementById('text'+n+'-'+m).setStyleAttributes(styleTextNormal);
textBox.setText(sheetValues[n-1][m]);// iterate and update cells values
}
}
return app;// update Ui
}
I copied this function from somewhere on the web. My goal is to import the body of specifically labeled emails in my gmail account to a google spreadsheet. While I'm not completely inept when it comes to coding, I'm not familiar with this stuff.
Some details that may be relevant: Each of these Emails I am trying to import are NOT conversations, they are a single email received, no response and no earlier messages in the thread. I want the entire body of each Email placed in a single cell in the spreadsheet.
As it is, only the subject is being placed in my spreadsheet. How can I get it to bring the body, as well? I feel like it's being placed in the array, but when looping the setValue it gets skipped.
Much love, folks!
Code:
function getMessagesWithLabel() {
var destArray = new Array();
var threads = GmailApp.getUserLabelByName('abc').getThreads(1,10);
for(var n in threads){
var msg = threads[n].getMessages();
var destArrayRow = new Array();
destArrayRow.push('thread has '+threads[n].getMessageCount()+' messages');
for(var m in msg){
destArrayRow.push(msg[m].getSubject());
}
destArray.push(destArrayRow);
}
Logger.log(destArray);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getActiveSheet();
if(ss.getLastRow()==0){sh.getRange(1,1).setValue('getMessagesWithLabel() RESULTS')};
sh.getRange(ss.getLastRow()+1,1,destArray.length,destArray[0].length).setValues(destArray)
}
You're not employing .getBody() anywhere in your script? In a case like this I'd store each message as an object with subject and body as separate values:
var msg = threads[n].getMessages();
var contentArray = [];
for(var i = 0; i < msg.length; i++){
var obj = {
subject: msg[i].getSubject(),
body: msg[i].getBody()
};
contentArray.push(obj);
}
These values can then be iterated through using the following notation:
console.log(contentArray[0].subject);
console.log(contentArray[0].body);