I'm French and beginner in the app script.
My Problem:
I get data from a "var resultat = UrlFetchApp.fetch(url).getContentText();" that gives me an XML file
I want to add the result in my spreadsheet BUT before I would like to know if the row already exists in my spreadsheet.
I try to do this:
function GetMeteo() {
url = "http://www.yr.no/place/France/Alsace/Strasbourg/forecast_hour_by_hour.xml";
var resultat = UrlFetchApp.fetch(url).getContentText();
var root = XmlService.parse(resultat).getRootElement();
var entries = root.getChild('forecast').getChild('tabular').getChildren();
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
var newData = new Array();
for (var i =0 ; i < entries.length; i++) {
var heure = entries[i].getAttribute('from').getValue();
var precipitation = entries[i].getChild('precipitation').getAttribute('value').getValue();
var windDirection = entries[i].getChild('windDirection').getAttribute('deg').getValue();
var windSpeed = entries[i].getChild('windSpeed').getAttribute('mps').getValue();
var temperature = entries[i].getChild('temperature').getAttribute('value').getValue();
var pressure = entries[i].getChild('pressure').getAttribute('value').getValue();
var duplicate = -1;
Données.activate();
var data = Données.getDataRange().getValues();
for (j in data) {
if (data[j][0] == heure) {
duplicate = j;
}
else {
duplicate = -1;
}
}
if (NumLigne == -1) {
data.push({heure,precipitation,windDirection,windSpeed,temperature,pressure});
}
else {
data[NumLigne].push({heure,precipitation,windDirection,windSpeed,temperature,pressure});
}
}
But the DataPush does not work.
Related
Below is a script written by Jordan Rhea and provided via github.
I am trying to follow its logic so that I can understand how to approach automatically populating a form with questions that have conditional logic flowing to different sections of a Google Form.
The code is breaking at line 35 "ReferenceError: form is not defined (line 35, file "RosterMaker")
Line 35 = var classSection = form.addPageBreakItem().setTitle(className).setGoToPage(FormApp.PageNavigationType.SUBMIT);
I'm sure this is a simple error, but I cannot figure it out.
var ssID = "something";
var formID = "something"
//SpreadsheetApp.openById(ssID).getSheetByName("db_type");
function rosterMaker() {
//spreadsheet id of the rosters
var SHEET_ID = SpreadsheetApp.getActive();
var ss = SpreadsheetApp.openById(ssID);
var form = FormApp.openById((formID));
//get only the sheets with 'Roster' in the title
var sheets = ss.getSheets()
.filter(function(sheet) {return sheet.getName().match(/Roster/gi);});
//add multiple choice item
var classSelect = form.addMultipleChoiceItem()
.setTitle('Choose a class');
Logger.log(classSelect);
//get the class choices for the multiple choice item
var classChoices = getClasses(sheets);
//assign the choices to the classSelect variable
classSelect.setChoices(classChoices);
}
function getClasses(sheets) {
var classChoices = [];
for(var i = 0; i < sheets.length; i++) {
var className = sheets[i].getName();
var classSection = form.addPageBreakItem()
.setTitle(className)
.setGoToPage(FormApp.PageNavigationType.SUBMIT);
var students = getStudents(sheets[i]);
var studentSelect = form.addCheckboxItem()
.setTitle(className + ' absent')
.setHelpText('Select the students who are absent from this class');
var studentChoices = [];
for(var j = 0; j < students.length; j++) {
studentChoices.push(studentSelect.createChoice(students[j]));
}
studentSelect.setChoices(studentChoices);
classChoices.push(classSelect.createChoice(className, classSection));
}
return classChoices;
}
function getStudents(sheet) {
var studentValues = sheet.getDataRange().getValues();
var students = [];
for(var i = 1; i < studentValues.length; i++) {
students.push(studentValues[i].join(' '));
}
return students;
}
Test this:
var ssID = "something";
var formID = "something";
function rosterMaker() {
var SHEET_ID = SpreadsheetApp.getActive();
var ss = SpreadsheetApp.openById(ssID);
var form = FormApp.openById((formID));
var sheets = ss.getSheets().filter(function(sheet) {return sheet.getName().match(/Roster/gi);});
var classSelect = form.addMultipleChoiceItem().setTitle('Choose a class');
var classChoices = getClasses(sheets,form);//modified
classSelect.setChoices(classChoices);
}
function getClasses(sheets,form) {//modified
var classChoices = [];
for(var i = 0; i < sheets.length; i++) {
var className = sheets[i].getName();
var classSection = form.addPageBreakItem().setTitle(className).setGoToPage(FormApp.PageNavigationType.SUBMIT);
var students = getStudents(sheets[i]);
var studentSelect = form.addCheckboxItem().setTitle(className + ' absent').setHelpText('Select the students who are absent from this class');
var studentChoices = [];
for(var j = 0; j < students.length; j++) {
studentChoices.push(studentSelect.createChoice(students[j]));
}
studentSelect.setChoices(studentChoices);
classChoices.push(classSelect.createChoice(className, classSection));
}
return classChoices;
}
function getStudents(sheet) {
var studentValues = sheet.getDataRange().getValues();
var students = [];
for(var i = 1; i < studentValues.length; i++) {
students.push(studentValues[i].join(' '));
}
return students;
}
I have some data containing, Dates, Usernames and an average percent that i want to save in a certain way. My problem is that the order of the usernames can change depending on if new ones are added. I therefore need to "find" a specific username and then save the percentage data in the correct column.
I have found some code that partially helps me save the data that i need. But i could use some help in the "find" the corresponding username and save it in a certain Column part.
function save() {
var sss = SpreadsheetApp.getActive();
var ss = sss.getSheetByName('Result');
var range = ss.getRange('B1:B10');
var data = range.getValues();
var tss = SpreadsheetApp.getActive();
var ts = tss.getSheetByName('Archive');
ts.getRange(ts.getLastRow()+1, 1,data[0].length,data.length)
.setValues(Object.keys(data[0]).map ( function (columnNumber) {
return data.map( function (row) {
return row[columnNumber];
});
}));
}
Basically from this:
To a result that looks like this:
Thank you for your assistance.
Alright for anyone out there that may have a similar problem, this is what i ended up with.
function extractAttendance() {
var currentSheet = SpreadsheetApp.getActive();
var attendanceTab = currentSheet.getSheetByName('Data_Filtered');
var userData = attendanceTab.getRange('B1:B').getValues();
var percentageData = attendanceTab.getRange('I1:I').getValues();
var archiveTab = currentSheet.getSheetByName('Archive');
var existingUsersRow = archiveTab.getRange('1:1');
var newRowNumber = archiveTab.getLastRow() + 1;
archiveTab.getRange(newRowNumber, 1).setValue(new Date());
for (var i = 1; i < userData.length; i++) {
var user = userData[i][0];
if (user === '') {
continue;
}
var existingUsers = existingUsersRow.getValues()[0];
var exists = false;
var existingColumnNumber = -1;
for (var j = 0; j < existingUsers.length; j++) {
if (existingUsers[j] === user) {
exists = true;
existingColumnNumber = j + 1;
break;
}
}
if (exists) {
archiveTab.getRange(newRowNumber, existingColumnNumber).setValue(percentageData[i]);
} else {
var newColumnNumber = archiveTab.getLastColumn() + 1;
archiveTab.getRange(1, newColumnNumber).setValue(user);
archiveTab.getRange(newRowNumber, newColumnNumber).setValue(percentageData[i]);
}
}
}
It might be easier to implement your desired functionality through looping rather than through mapping.
The following code retrieves all users ad their percentage data in ‘Result’ and transfers the data (in the format you desire) to "Archive" with the percentages data pasted with the corresponding timestamp into the first empty row.
function save() {
var sss = SpreadsheetApp.getActive();
var ss = sss.getSheetByName('Result');
var range = ss.getRange('B1:B');
var percentageRange = ss.getRange('G1:G');
var userData = range.getValues();
var percentageData = percentageRange.getValues();
var tss = SpreadsheetApp.getActive();
var ts = tss.getSheetByName('Archive');
var userRow=1;
var percentageRow=(ts.getLastRow()+1)
for(var i=0; i<=userData.length; i++)
{
{
var j=(i+2);
ts.getRange(userRow, j).setValue(userData[i])
ts.getRange(percentageRow, 1).setValue(new Date())
ts.getRange(percentageRow, j).setValue(percentageData[i])
}
}
}
I am trying to update four out of five columns in FusionTables using data from Google Spreadsheet. I have just started programming Apps-scripts. I need help with update query. Any suggestions or feedback is appreciated. Thank you in advance.
function sync() {
var tasks = FusionTables.Task.list(TABLE_ID);
// Only run if there are no outstanding deletions or schema changes.
if (tasks.totalItems === 0) {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
//i = 1 for 1st row with values in spreadsheet. 0 for column headers.
for (var i = 1; i < data.length; i++) {
var cName = data[i][0];
var ed_vs = data[i][1];
var ed_vs_ada = data[i][2];
var color = data[i][3];
//update ft
var updateQry = "update "+TABLE_ID+" set ED_VS = "+ed_vs+",ED_VS_ADA = "+ed_vs_ada+", COLOR = "+color+ "where COUNTY = "+cName;
//FusionTables.Query.sql(updateQry);
//is this even possible to execute an update query? help with syntax?
Logger.log(updateQry);
}
}
};
Here's working solution for someone with similar issue.
function sync() {
var tasks = FusionTables.Task.list(TABLE_ID);
// Only run if there are no outstanding deletions or schema changes.
if (tasks.totalItems === 0) {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
//i = 1 for 1st row with values in spreadsheet. 0 will give column headers.
for (var i = 1; i < data.length; i++) {
var cName = data[i][0];
var ed_vs = data[i][1];
var ed_vs_ada = data[i][2];
var color = data[i][3];
//parse rowid from output
var selQry = "select ROWID FROM "+TABLE_ID+" where COUNTY = '"+cName+"' ";
var cdata = FusionTables.Query.sql(selQry);
var c_rowid = cdata.rows[0][0]; //rowid
Logger.log(c_rowid);
var updateQry = "update "+TABLE_ID+" set ED_VS = '"+ed_vs+"',ED_VS_ADA = '"+ed_vs_ada+"', COLOR = '"+color+ "' where ROWID = '"+c_rowid+"' ";
FusionTables.Query.sql(updateQry);
Logger.log(updateQry);
}
}
};
I would like to copy entire row(s) into another sheet if A(i) equals the content of a cell (see criteria).
Example:
My criteria (which is located in ws2.A4) = "good"
Copy row 7 into ws1.A5 as ws1.A7 = "good"
Copy row 8 into ws1.A6 as ws1.A8 = "good"
But not the other rows.
(Note: I am trying to adapt this vba code into GAS https://stackoverflow.com/a/12185026/457557)
Here is where I blocked now :
function copy_row_s_if_cellAi_equal_X() {
var ws1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("base");
var ws2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("ok");
var Alast = ws1.getLastRow()
var criteria = ws2.getRange(4 ,1).Value
var target = ws2.getRange(5 ,1)
for (var i = 3; i < Alast; i++ ) {
if (ws1.getRange(i ,1) == criteria) {
ws1.getRange(i ,1).copyTo(target, {contentsOnly:true}); // copy/paste content only
}
}
}
something like that does what you want... not sure I understood exactly what you wanted though...
function copy_row_s_if_cellAi_equal_X() {
var ws1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("base");
var ws2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("ok");
var Alast = ws1.getLastRow();
var criteria = ws2.getRange(4 ,1).getValue();
for (var i = 3; i < Alast; i++ ) {
Logger.log(ws1.getRange(i ,1).getValue()+ ' ==? ' + criteria);
if (ws1.getRange(i ,1).getValue() == criteria) {
ws1.getRange(i ,1,1,ws1.getLastColumn()).copyTo(ws2.getRange(i ,1,1,ws1.getLastColumn()), {contentsOnly:true}); // copy/paste content only
}
}
}
EDIT : high speed version
function copy_row_s_if_cellAi_equal_X() {
var ws1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("base");
var ws2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("ok");
var Alast = ws1.getLastRow();
var criteria = ws2.getRange(4 ,1).getValue();
var dataws1 = ws1.getRange(3,1,Alast,ws1.getLastColumn()).getValues();
var outData = [];
for (var i in dataws1) {
if (dataws1[i][0] == criteria) {
outData.push(dataws1[i])
}
}
ws2.getRange(ws2.getLastRow(),1,outData.length,outData[0].length).setValues(outData);
}
I am writing a Form script and need to store extra settings for each question. I want to avoid creating a spreadsheet so I am trying to use scriptDB to store the settings for each question. (If there is a better way please let me know).
Right now I am just trying to create a synchronizeDB() function that will update the Database with any new or deleted questions. I can't just delete and reload because that would delete the extra data I stored for each question.
-bj
I figured it out:
function snycFormToDb(){
var formQs = getFormQarray();
addDBQuestions(formQs);
removeDBQuestions(formQs);
// showAll();
}
// Save Questions To DB
function getFormQarray(){
var form = FormApp.getActiveForm();
var items = form.getItems();
var itemL = items.length-1;
var allQuestions = [];
for (var i=0; i <= itemL; ++i) {
var qID = items[i].getId();
var qType = items[i].getType()+ "";
var qTitle = items[i].getTitle();
var qIndex= items[i].getIndex();
var qHelpTxt = items[i].getHelpText();
var entry = [qID,qIndex,qTitle,qType,qHelpTxt];
allQuestions.push(entry);
} // end For
return(allQuestions);
}; // end function questionsDB()
// Add questions to DB
function addDBQuestions(formQs) {
var dbQuestions = [];
var results = db.query({});
while (results.hasNext()) {
var current = results.next();
dbQuestions.push(current);
}
var dbQuestionsL = dbQuestions.length-1;
var formQsL = formQs.length-1;
var addToDb = [];
for (var j=0; j <= formQsL; ++j) {
var notPresent = false;
for (var k=0; k <= dbQuestionsL; ++k) {
var dbID = dbQuestions[k]['qID'];
var frmID = formQs[j][0];
if (dbID == frmID){
notPresent = true;
}
}
if (notPresent == false) {
//var entry = [qID,qIndex,qTitle,qType,qHelpTxt];
//var format = {type: formQs[j][2],title: formQs[j][1],qID: formQs[j][0]};
var format = {qID: formQs[j][0],qIndex: formQs[j][1],qTitle: formQs[j][2],qType: formQs[j][3],qHelpTxt: formQs[j][4]};
addToDb.push(format);
}
} // end for formQsL
db.saveBatch(addToDb, false);
} //end my function
// Remove Q's from Database
function removeDBQuestions(formQs) {
var formQsL = formQs.length-1;
//get qID results from Database
var results = db.query({});
while (results.hasNext()) {
var current = results.next();
//var recordID = results.getId();
var deleteCurrent = "true";
// Delete missing questions
for (var j=0; j <= formQsL; ++j) {
var c1 = current.qID;
var c2 = formQs[j][0];
if (current.qID == formQs[j][0]){ deleteCurrent = "false";}
}
if (deleteCurrent == "true"){
db.remove(current);
}
}
} //end my function