Remove notes in Google Slides using Google Apps Script and Slides API - google-apps-script

I'm trying to write a function to delete notes from Google Slides presentation using Google Apps Script.
I went through the examples and assume I need to match that to something like https://developers.google.com/slides/samples/writing#delete_a_page_or_page_element by calling speakers notes using https://developers.google.com/slides/how-tos/notes, but I can't make the link.
New to Google Apps Script, any help appreciated.

Thanks for the initial script!
Unfortunately it didn't work for me, and after several attempts, I've made it work:
function clearNotes(){
var presentation = SlidesApp.getActivePresentation();
var presentationId = presentation.getId();
var slides = presentation.getSlides();
var requests = [];
slides.forEach(function(slide, i) {
var slideNote = slide.getObjectId();
var slideNotesPage = slide.getNotesPage();
var shape = slideNotesPage.getSpeakerNotesShape();
var shapeText = shape.getText();
if(shapeText != undefined){
shapeText.clear();
}
})
if(requests.length > 0){
var batchUpdateResponse = Slides.Presentations.batchUpdate({requests: requests}, presentationId);
}
}
As a newbie, it involved lots of try and error, debug and follow the guide here: https://developers.google.com/apps-script/reference/slides/text-range.html#clear()
So far, it's the only solution I've found to batch delete all notes in a Google Slides presentation.
Hope this helps,
Rafa.

Here is how I did it.
function clearNotes(){
var presentation = SlidesApp.getActivePresentation();
var presentationId = presentation.getId();
var slides = presentation.getSlides();
var requests = [];
slides.forEach(function(slide, i) {
var slideNote = Slides.Presentations.Pages.get(presentationId, slide.getObjectId());
var slideNoteId = JSON.parse(slideNote).slideProperties.notesPage.notesProperties.speakerNotesObjectId;
var slideNotesPage = JSON.parse(slideNote).slideProperties.notesPage;
var shapeText = slideNotesPage.pageElements[1].shape.text;
if(shapeText != undefined){
requests.push({
deleteText: {objectId: slideNoteId,textRange:{type: 'ALL'}}
});
}
})
if(requests.length > 0){
var batchUpdateResponse = Slides.Presentations.batchUpdate({requests: requests}, presentationId);
}
}
Hope it helps.

Google has now integrated this option into the Slides program. When you make a copy you can choose/check to include notes or not.

Related

Grab Answer Key from Short Answer Google Forms

I am attempting to grab the answer key from the short answer in Google forms.
I am attempting to grab the following answer key from a short answer question (refer to the screenshot below). Below the Short answer text, it shows you the correct answer.
However, when reading the documentation, there seems there is no way to do so. Is there an alternative way to grab the answer key from the short answer in Google Forms?
The following is the script I am using to grab the information from the quiz:
function extractFormData(fullNme) {
var form = FormApp.getActiveForm();
var items = form.getItems();
var quizAdded = new Date().toLocaleString("en-US");
var uniqueQuizID = Utilities.getUuid(), question_listID = uniqueQuizID.concat("-questions");
var constructedJSON = {};
var answer_val = false;
var errorJSON = {};
var email = form.getEditors()[0].getEmail();
var quizInfo = {
"quiz_name": form.getTitle(),
"quiz_owner": fullNme,
"quiz_description": form.getDescription(),
"quiz_owner_email": email,
"quiz_submited_date":quizAdded
};
//console.log(JSON.stringify(quizInfo));
for (var i = 0; i < items.length; i++) {
var item = items[i];
switch(item.getType()) {
case FormApp.ItemType.MULTIPLE_CHOICE:
var question = item.asMultipleChoiceItem();
var ques = question.getTitle();
var question_type = "Multiple Choice";
var optns = [];
var answr;
var answers = question.getChoices();
answer_val = false;
for (var j = 0; j < answers.length; j++) {
var clean = answers[j].getValue();
optns.push(clean);
if(answers[j].isCorrectAnswer()){
answr = answers[j].getValue();
for(var x = 0; x < optns.length; x++){
if(answr == optns[x]){
answer_val = true;
break;
}
}
}
}
var multiJSON = makeJSON(ques, question_type, optns, answr);
constructedJSON[i+1] = multiJSON;
break;
case FormApp.ItemType.CHECKBOX:
var question = item.asCheckboxItem();
var ques = question.getTitle();
var question_type = "CheckBox";
var optns = [];
var answr = [];
var answers = question.getChoices();
for (var j = 0; j < answers.length; j++) {
var clean = answers[j].getValue();
optns.push(clean);
if(answers[j].isCorrectAnswer()){
answr.push(answers[j].getValue());
}
}
var checkJSON = makeJSON(ques, question_type, optns, answr);
constructedJSON[i+1] = checkJSON;
break;
case FormApp.ItemType.PARAGRAPH_TEXT:
var question = item.asParagraphTextItem();
var ques = question.getTitle();
var question_type = "free response";
var optns = [];
var answr;
var paraJSON = makeJSON(ques, question_type, optns, answr);
constructedJSON[i+1] = paraJSON;
break;
case FormApp.ItemType.TEXT:
var question = item.asTextItem();
var ques = question.getTitle();
var question_type = "free response";
var optns = "";
var answr = "";
var textJSON = makeJSON(ques, question_type, optns, answr);
constructedJSON[i+1] = textJSON;
break;
}
if(!answer_val){
errorJSON = {"Question":ques, "Options":optns, "Answer": answr, "Sucess": false};
//error(ques);
break;
}
}
if(answer_val){
notifyUser();
} else {
return errorJSON;
}
}
The method that you are looking for is not yet supported in Apps Script.
Therefore, you have two options in this situation:
Create a feature request on Google's Issue Tracker here and provide all the necessary details.
Make use of Forms API by using the Forms API advanced service in Apps Script and try Tanaike's proposed solution.
If you check the documentation, you can see that resources of type CorrectAnswer have a field available:
{
"value": string
}
A single correct answer for a question. For multiple-valued (CHECKBOX) questions, several CorrectAnswers may be needed to represent a single correct response option.
Reference
Forms API.
I believe your goal is as follows.
You want to retrieve the correct answer from each question of Google Form using Google Apps Script.
In this case, when I checked the method for directly achieving your goal using Google Form service (FormApp), unfortunately, I couldn't find it. But fortunately, I confirmed that when Google Forms API is used, your goal can be achieved. So, in this answer, I would like to propose to achieve your goal using Google Forms API.
Usage:
1. Linking Google Cloud Platform Project to Google Apps Script Project for New IDE.
In order to use Forms API, please link Google Cloud Platform Project to Google Apps Script Project for New IDE, and please enable Forms API at API console. Ref
2. Sample script.
function myFunction() {
const formId = "###"; // Please set your Google Form ID.
const url = "https://forms.googleapis.com/v1/forms/" + formId + "?fields=*";
const res = UrlFetchApp.fetch(url, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } });
const obj = JSON.parse(res.getContentText());
const values = obj.items.map(({ title, questionItem }) => (
{ title, point: questionItem.question.grading.pointValue, answer: questionItem.question.grading.correctAnswers ? questionItem.question.grading.correctAnswers.answers.map(({ value }) => value) : [] }
));
console.log(values)
}
In this script, please include the scope of https://www.googleapis.com/auth/forms.body.readonly.
3. Testing.
When this script is run to the Google Form, the following sample value is obtained.
[
{"title":"sample question 1","point":5,"answer":["sample1","sample2"]},
{"title":"sample question 2","point":3,"answer":["Option 2","Option 3"]},
{"title":"sample question 3","point":3,"answer":["Option 2"]}
]
This is a sample value.
Note:
When you want to simply check this, you can also use "Try this method" of Forms API.
When the correct answer is not set, an error occurred. So I modified it. By this, when the correct answer is not set, [] is returned.
References:
Linking Google Cloud Platform Project to Google Apps Script Project for New IDE
Method: forms.get

How to remove Google Sheets Chart from Google Slide if Chart has no data

I am inserting an embedded chart from Sheets to Slides using app script. But I would like to remove the chart from the slide if on Google Sheets the chart is empty/has no data.
I want to remove the chart from slides ONLY when it doesn't have data. But keep the chart if there is data
Can you please help me add the right line that would create this condition ?
This is my chart code:
function onOpen() {
// Get the Ui object.
var ui = SpreadsheetApp.getUi();
// Create a custom menu.
ui.createMenu('Present Data')
.addItem("Generate Report","generateLandingPagesReport")
.addToUi();
}
function generateLandingPagesReport() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Copy of Overall Performance 1');
var values = sheet.getRange('A2:J23').getValues();
var chartRegion1 = sheet.getCharts()[0];
var chartGender1 = sheet.getCharts()[1];
// Access the template presentation
var templateId = "1bXAYGCKkpZhksXz8gTCgFYbNoI1BIhAZakd68VlXHeo";
var template = SlidesApp.openById(templateId);
var templateSlides = template.getSlides();
// Create a Slides presentation, removing the default
// title slide.
var presentationTitle =
ss.getName() + " Presentation";
var slides = SlidesApp.create(presentationTitle);
var defaultSlides = slides.getSlides();
defaultSlides.forEach(function(slide) {
slide.remove()
});
var defaultSlide = defaultSlides [1];
// Insert slides from template
var index = 0;
templateSlides.forEach(function(slide) {
var newSlide = slides.insertSlide(index);
var elements = slide.getPageElements();
elements.forEach(function(element) {
newSlide.insertPageElement(element);
});
index++;
});
values.forEach(function(page){
if(page[0]){
var landingPage = page[0];
var sessions = page[1];
var newSessions = page[2];
var pagesPer = page[5];
var goalRate = page[7];
var goalValue = page[9];
// Insert slides from template
var index = 0;
templateSlides.forEach(function(slide) {
var newSlide = slides.insertSlide(index);
var elements = slide.getPageElements();
elements.forEach(function(element) {
newSlide.insertPageElement(element);
});
index++;
});
defaultSlides = slides.getSlides(); //update the slides array for
indexes and length
defaultSlide = defaultSlides[1];
newSlide = defaultSlide;
newSlide2 = defaultSlides[2];
var shapes = (newSlide.getShapes());
shapes.forEach(function(shape){
shape.getText().replaceAllText('{{landing page}}',landingPage);
shape.getText().replaceAllText('{{sessions}}',sessions);
shape.getText().replaceAllText('{{new sessions}}',newSessions);
shape.getText().replaceAllText('{{pages per session}}',pagesPer);
shape.getText().replaceAllText('{{goal rate}}',goalRate);
shape.getText().replaceAllText('{{goal value}}',goalValue);
})
var shapes = (newSlide2.getShapes());
shapes.forEach(function(shape){
shape.getText().replaceAllText('{{landing page}}',landingPage);
shape.getText().replaceAllText('{{sessions}}',sessions);
shape.getText().replaceAllText('{{new sessions}}',newSessions);
shape.getText().replaceAllText('{{pages per session}}',pagesPer);
shape.getText().replaceAllText('{{goal rate}}',goalRate);
shape.getText().replaceAllText('{{goal value}}',goalValue);
});
presLength = defaultSlides.length;
newSlide.move(presLength);
newSlide2.move(presLength);
defaultSlides[0].remove();
defaultSlides[3].remove();
} // end our conditional statement
}); //close our loop of values
//Get the charts
var defaultSlides=slides.getSlides();
var defaultSlide = defaultSlides [1]
var position = {right: 490, bottom: 190};
var size = {height: 140, width: 230};
defaultSlide.insertSheetsChart(
chartRegion1,
position.right,
position.bottom,
size.width,
size.height);
var defaultSlides=slides.getSlides();
var defaultSlide = defaultSlides [1]
var position = {right: 200, bottom: 190};
var size = {height: 140, width: 230};
defaultSlide.insertSheetsChart(
chartGender1,
position.right,
position.bottom,
size.width,
size.height);
// Create and display a dialog telling the user where to
// find the new presentation.
var slidesUrl = slides.getUrl();
var html = "<p>Find it in your home Drive folder:</p>"
+ "<p><a href=\"" + slidesUrl + "\" target=\"_blank\">"
+ presentationTitle + "</a></p>";
SpreadsheetApp.getUi().showModalDialog(
HtmlService.createHtmlOutput(html)
.setHeight(120)
.setWidth(350),
"Report Generated!"
);
}
Thank you for your help.
I believe your current situation and your goal are as follows.
You have Google Slides including some charts.
When the chart is "No data", you want to remove the chart from the Google Slides.
You want to achieve this using Google Apps Script.
From your sample Spreadsheet including the sample "No data" chart, your "No data" chart has no values.
In this case, how about the following sample script?
Sample script:
Please copy and paste the following script to the script editor of the Google Spreadsheet including the charts. And, please set the Google Slides ID to presentationId.
function myFunction() {
const presentationId = "###"; // Please set the Google Slides ID.
// 1. Retrieve the charts with "No data".
const ss = SpreadsheetApp.getActiveSpreadsheet();
const obj = ss.getSheets().reduce((o, sheet) => {
sheet.getCharts().forEach(chart => {
const check = chart.getRanges().some(e => {
const temp = e.getDisplayValues();
return temp[0].map((_, c) => temp.map(r => r[c])).some(col => col.join("") == "");
});
if (check) o[chart.getChartId()] = check;
});
return o;
}, {});
// 2. Remove the charts with "No data".
const slides = SlidesApp.openById(presentationId).getSlides();
slides.forEach(slide => {
slide.getSheetsCharts().forEach(chart => {
if (obj[chart.getChartId()]) chart.remove();
});
});
}
When this script is run, first, the charts of "No data" are retrieved in an object. And, using this object, the charts in Google Slides are removed.
Note:
This sample script is for your sample Spreadsheet. If the condition of "No data" is changed, this script might not be able to be used. So, please be careful about this.
References:
reduce()
forEach()
remove() of Class SheetsChart

Apps Script getEventById() returns null

I am new to Apps Script and struggling with the "getEventById()" function.
My goal is to delete an event entry on Google Calendar via Google Sheets when you press a button.
I already managed to get the event id via Apps Script and it´s Google API V3, but when I hand it over to "getEventById" as parameter, it returns null, even when I "hardcode" the id.
Here´s my code. I removed some parts since those aren´t important I think:
function calDate(){
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getActiveSheet();
var calId = spreadsheet.getRange("N1").getValue();
var calEvent = CalendarApp.getCalendarById(calId);
var ui = SpreadsheetApp.getUi();
var selection = spreadsheet.getSelection();
var selectedRow = selection.getActiveRange().getA1Notation();
var rowRange = sheet.getRange(selectedRow);
var rowNumber = rowRange.getRow();
var colRange = sheet.getRange(selectedRow);
var colNumber = colRange.getColumn();
if (colNumber !== 15){
//wait for showtime
}
else{
// its showtime
var combinedRange = "O" + rowNumber;
var sheetData = sheet.getRange(rowNumber, 3, 1, 15).getValues();
if(sheetData[0][12] == false){
var dateStart = new Date(sheetData[0][7]);
var dateEnd = new Date(sheetData[0][8]);
var KdName = sheetData[0][0];
var BV = event_id[0][4];
var combinedNames = KdName + " - " + BV;
var items = Calendar.Events.list(calId, {
timeMin: dateStart.toISOString(),
timeMax: dateEnd.toISOString(),
q: combinedNames
}).items;
}
else{
var testVar = calEvent.getEventById(/*This is where I would put the htmlLink (the event-id)*/);
console.log(testVar);
}
}
}
Hopefully those informations are enough and if not, feel free to ask for more.
I really hope you guys can help me out!
Kind regards
EDIT & SOLUTION
Okay guys, thanks to Mateo Randwolf, who kindly opened an issue at Google about this, I was able to figure it out. This is the link with an example how to get the the ID from the event and hand that id over to the "getEventById()" function. Or here as a code-block:
function findEventID() {
var now = new Date();
var nextEvent = new Date(now.getTime() + (2 * 60 * 60 * 1000));
var event = CalendarApp.getDefaultCalendar().getEvents(now, nextEvent);
ID = event[0].getId();
Logger.log('EventID: ' + event[0].getId());
Logger.log(CalendarApp.getDefaultCalendar().getEventById(ID));
}
Now it gets funny. This line:
Logger.log('EventID: ' + event[0].getId());
returns the event-id like it should.
But this one:
Logger.log(CalendarApp.getDefaultCalendar().getEventById(ID));
doesn´t show anything except "{}", which is weird.
But if you apply "deleteEvent()" on it, like so:
calEvent.getEventById(ID).deleteEvent(); //calEvent is a CalendarApp, see above
It actually deletes the event from the calendar!
With that, I´d say we found the solution or at least a bypass.
Issue
Hi ! So it seems to me that getEventById() has a bug that returns null instead of the event object as I was getting the exact same behaviour you were reporting in this question. I have filed this behaviour to the public issue tracker, you can find it here with all the discussion on this behaviour.
I hope this has helped you. Let me know if you need anything else or if you did not understood something. :)
Using the Calendar API search query to find events in a calendar
function calDate(){
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sh=ss.getActiveSheet();
var calId=ss.getRange("N1").getValue();
var calEvent=CalendarApp.getCalendarById(calId);
var row=ss.getActiveRange().getRow();
var col=ss.getActiveRange().getColumn()
if (col!=15){
//wait for showtime
}else{
var vs=sh.getRange(row, 3, 1, 15).getValues();
if(vs[0][12] == false){
var dateStart=new Date(vs[0][7]);//col J
var dateEnd=new Date(vs[0][8]);//col K
var KdName=vs[0][0];//col 3
event_id below is not defined
var BV=event_id[0][4];//col G
var combinedNames=KdName + " - " + BV;
var items=Calendar.Events.list(calId, {timeMin: dateStart.toISOString(),timeMax: dateEnd.toISOString(),q: combinedNames}).items;
}
else{
var testVar=calEvent.getEventById(/*This is where I would put the htmlLink (the event-id)*/);
console.log(testVar);
}
}
}
Since you couldn't share your spreadsheet I share mine with an example
One thing that helps a lot is playing with the API explorer to figure what works and what doesn't. If you want to display all of the fields you can use * and this example proved very helpful as well
Here's the code:
function myOwnEventSearch() {
var calendarId='***********calendar id**************';
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Sheet235');
var sr=2;
var sc=2
var rg=sh.getRange(sr,sc,sh.getLastRow()-sr+1,sh.getLastColumn()-sc+1);
var vA=rg.getValues();
var hA=sh.getRange(sr-1,sc,1,sh.getLastColumn()-sc+1).getValues()[0];
var idx={};//locates the data index from column header names
hA.forEach(function(h,i){idx[h]=i;});
var cal=CalendarApp.getCalendarById(calendarId);
var html='<style>td,th{}</style><table><tr><th>Summary</th><th>Start</th><th>End</th><th>Id</th></tr>'
for(var i=0;i<vA.length;i++) {
if(!vA[i][idx['Id']] && vA[i][idx['DateFrom']] && vA[i][idx['DateTo']] && vA[i][idx['SearchString']]) {
var request={timeMin:new Date(vA[i][idx["DateFrom"]]).toISOString(),timeMax:new Date(vA[i][idx["DateTo"]]).toISOString(),q:vA[i][idx["SearchString"]],showDeleted: false,singleEvents:true,maxResults:10,orderBy:"startTime"};
var resp=Calendar.Events.list(calendarId, request);
if(resp.items.length>0) {
var idA=[];
resp.items.forEach(function(item,j){
html+=Utilities.formatString('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>', item.summary,item.start,item.end,item.id);
idA.push(item.id);
});
sh.getRange(i+sr,idx['Id']+sc).setValue(idA.join(', '))
}
}
}
html+='<table>';
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html).setWidth(800), "My Events")
}
Here's the spreadsheet before the script runs.
Here's the dialog that displays the search results.
Here's what the spreadsheet looks like after running script:
The Event Ids were copied into the Id Column
And these were the four events I created on my calendar::
Here is how I worked around this. I stored all the events (from the range I was interested in) in a JavaScript Map() so I can find them later:
var cal = CalendarApp.getCalendarById("/* supply your calendar ID here*/");
if (!cal) {
Logger.log("Calendar not found for ID:" + calendarID);
} else {
var calEvents = cal.getEvents(new Date("March 8, 2010"), new Date("March 14, 2025"));
// Store them by eventId for easy access later
var calEventMap = new Map();
for (var j in calEvents) {
calEventMap.set(calEvents[j].getId(), calEvents[j]);
}
/* Later when you need to look up by iCalID... */
var calEvent = calEventMap.get(eventID);
}
Works for me when you get the calendar by id like this:
const calendar = CalendarApp.getCalendarById("theCalendarId");
const event = calendar.getEventById("someEventId");
Now the event is not null, but the actual event, and you can do whatever you want with it from here!

Write from Google Firebase to Google Sheets using Google Apps script

Trying to retrieve form entries which are stored in google firebase under the node called entries and append to a google sheet using the script editor in google sheets.
I have added the FirebaseApp library to google sheet script editor. Then my code looks like this:
function getAllData() {
var firebaseUrl = "https://myapp.firebaseio.com/";
var secret = "pCOCwKCC582jpqdZe2EqPqnW3IAd3UyO9oB4uaEL2";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl, secret);
var data = base.getData();
Logger.log(data);
}
when I run this nothing happens. Any ideas?
Next I need to add the returned data from firebase to the google sheet. I was using this code to do this via the sheets api, however I'm not sure how this works in the google script editor?
function addEntries() {
gapi.client.sheets.spreadsheets.values.append({
spreadsheetId: '10lyQpQtEA7euCfdU2isrqB_bgPuy-eSbW74h7oDP3ko',
range: "Sheet1!A1:D100",
majorDimension: "ROWS",
"values": [
["testa", "testb", "testc", "testd"]
],
valueInputOption: 'USER_ENTERED'
}).then(function(response) {
}, function(response) {
appendPre('Error: ' + response.result.error.message);
});
}
I'm using the newest Firebase version. This snippet code works for me.
function getFacturasClientesExistentes() {
var firebaseUrl = "https://test.firebaseio.com/FacturasBLP/clienteExistente";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl);
var data = base.getData();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Facturas Clientes Existentes");
var num = 2;
range = sheet.getRange("A"+num+":F"+num+"");
for(var i in data) {
var values = [
[ data[i].fecha, data[i].sucursal, data[i].cantidad, data[i].cliente, data[i].correo, data[i].estatus ]
];
range.setValues(values);
num += 1;
range = sheet.getRange("A"+num+":F"+num+"");
}
}
Some notes:
I have previously write the headers for my data in the spreadsheet
In the line range = sheet.getRange("A"+num+":F"+num+""); from A to F I have my headers
I hope this helps someone, this worked for me.
function writeSheets() {
var ss = SpreadsheetApp.openById("10lyQpQtEA7euCfdU2isrqB_bgPuy-eSbW74h7oDP3ko");
var sheet = ss.getSheets()[0];
var firebaseUrl = "https://myapp.firebaseio.com/";
var secret = "pCOCwKCC582jpqdZe2EqPqnW3IAd3UyO9oB4uaEL2"; // get this from firebase project settings
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl);
var data = base.getData();
var keys = Object.keys(data.entries);
var sheetRow = [];
var entryKeys;
for (index in keys) {
sheetRow = [];
entryKeys = Object.keys(data.entries[keys[index]])
for (i in entryKeys) {
sheetRow.push(data.entries[keys[index]][entryKeys[i]]);
}
//Logger.log(sheetRow);
sheet.appendRow(sheetRow);
}
}
Note: in order for this code to work, you need to install the firebaseapp library in the script editor as per these instructions, https://sites.google.com/site/scriptsexamples/new-connectors-to-google-services/firebase

Uploading Google Spreadsheet to a Google Site

I'd like to begin by stating that the end goal is to display our company directory (a list of our employees names/job title/extension#/office location/email), which is in a Google Sheet, on a page in one of our Google Sites.
I tried to use Google's embed function, and it works... but it is very clunky, does not have a "Sort" function, and it just looks weird.
I pulled a Google Apps Script from somewhere online like 3 months ago and it actually did pull in a way that made me happy:
(This is as it appears currently on the Google Sites page. So in this screenshot, the embedded Sheet is at the top. The Sheet when, imported via the script, is below. Yes, they are both on the same page. I'm in testing!)
This is the code I used (I THINK - I don't remember how I implemented it):
function myFunction() {
}
function onOpen(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
if(ScriptProperties.getProperty("page url") == null){
ss.addMenu("List page", [{name: "Create list", functionName: "create_list"},null,
{name: "Fetch list items", functionName: "fetch_items"}]);
}
else{
ss.addMenu("List page", [{name: "Push Items", functionName: "push_items"}]);
}
}
function create_list() {
var data = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
var parent_page = Browser.inputBox("URL of the parent page:");
var title = Browser.inputBox("Choose a name for your list page:");
var data = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
var list = SitesApp.getPageByUrl(parent_page).createListPage(title, title.split(' ').join(''), '', data[0]);
ScriptProperties.setProperty("page url", list.getUrl());
onOpen();
push_items();
}
function push_items(){
var done = false;
while(!done){
try{
var data = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
var list = SitesApp.getPageByUrl(ScriptProperties.getProperty("page url"));
var list_items = list.getListItems();
for(i in list_items){
list_items[i].deleteListItem();
}
for(var i = 1; i < data.length; i++){
var item = list.addListItem(data[i]);
}
done = true;
}
catch(e){
}
}
SpreadsheetApp.getActiveSpreadsheet().toast(ScriptProperties.getProperty("page url"), "List page updated", 10);
}
function fetch_items(){
var url = Browser.inputBox("URL of your list page:");
var col_number = Browser.inputBox("Number of columns in the list:");
var data = new Array();
var list_items = SitesApp.getPageByUrl(url).getListItems();
for(i in list_items){
var row = new Array();
for(j = 0; j < col_number; j++){
row.push(list_items[i].getValueByIndex(j));
}
data.push(row);
}
SpreadsheetApp.getActiveSheet().getRange(1, 1, data.length, data[0].length).setValues(data);
}
[I do not take credit for writing this!]
So I would like to ask (since this ceases to make much sense to me) is if this is viable code for a Google Apps Script, and if so, how do I implement it to output Sheet data similarly in the same type of format as in the screenshot?
Alternatively, is there a better way to display this Sheet data in Google Sheets?
A totally different alternative would be to use Romain Vialard's "awesome tables" gadget. It works... awesome, and it is really easy to use. Besides, it admits filters, ...