I have a Google Slide that has an embedded image in it that I get from a public URL. I'd like for that image to automatically update every day at a specific time, rather than me having to open the slide and replace the image by URL every day.
Here's the code I tried to use, (replacing the placeholders 'SLIDE_ID' and 'IMAGE_URL' with the actual values) but it's not working.
function updateEmbeddedImage() {
// Get the slide ID and the image URL
var slideId = "SLIDE_ID";
var imageUrl = "IMAGE_URL";
// Open the slide and get the existing image
var slide = SlidesApp.openById(slideId);
var existingImage = slide.getImages()[0];
// Replace the existing image with the new image
var newImage = UrlFetchApp.fetch(imageUrl).getBlob();
slide.replaceImage(existingImage, newImage);
}
// Set a time-based trigger to run the script every day at a specific time
function setTrigger() {
ScriptApp.newTrigger("updateEmbeddedImage")
.timeBased()
.atHour(9)
.everyDays(1)
.create();
}
I get the message:
Error
Exception: Not found
updateEmbeddedImage # Code.gs:7
Issue in the OP code:
Error Exception: Not found updateEmbeddedImage # Code.gs:7. I can only speculate that the code included in the question is NOT the code that is in code.gs, since this error means that the script can't find a specific function.
In any event, the OP's code as written is OK.
But there are major flaws in the code:
var existingImage = slide.getImages()[0];
getImages() is a slide method. But slide is (in this case) the variable used to describe the presentation.
To get the slides use getSlides(); like var slides = slide.getSlides(). Even then you also have to nominate a specific slide, such as slides[0], or slides1.
the [0] at the of the line has no effect.
slide.replaceImage(existingImage, newImage);
There is no method replaceImage
There is a replaceImage Request that is part of the Google Slides API but this is irrelevant in this context.
Replacing the image url
Google Slides has an image method specifically designed to do this
replace(imageUrl): Replaces this image with another image downloaded from the provided URL.
The OP's trigger code can be re-used.
Revised updateEmbeddedImage
function updateEmbeddedImage() {
// Get the slide ID and the image URL
var slideId = "<<insert slideID>>"
var imageUrl = "<<insert imageurl>"
// Open the slide and get the existing image
var slide = SlidesApp.openById(slideId)
// assume the image is on slide#2 (zero-based=1)
var slides = slide.getSlides()
var targetSlide = slides[1]
// assume there is on one image on this slide
var images = targetSlide.getImages()
// replace the source URL
images[0].replace(imageUrl)
}
Code alternative
The OP's script requires that the source url must be hard coded into the script. This is inconvenient as well as error-prone.
this script in this answer should be bound to a Spreadsheet.
the Source URL should be entered in Column B.
Column A can contain an image() formula to show the image (and also confirm the url is valid).
the script returns all the slides (getSlides()) but assumes the embedded image is on the second slide.
The script gets all the images (getImages()) on that slide but assumes that the image to be replaced is the first image on the slide.
The existing SourceURL is returned with .getSourceUrl()
The new SourceURL is obtained from the spreadsheet
There is error checking to make sure that the existing SourceURL could be found AND that it wasn't the last URL on the spreadsheet.
// this script is bound to the spreadsheet containing the urls of the images.
// URL are in column B, beginning in row 1
// Image() formula is in Column A to display the image associated with the url
// to automatically update every day at a specific time, create a Time driven Installatble trigger.
function replaceurl() {
// get the slide
var slideId = "<<insert ID>>"
var slide = SlidesApp.openById(slideId)
// get the slides; assume the embedded image is on the second slide
var slides = slide.getSlides()
var targetSlide = slides[1]
// get images
// assume that image to replace is the first image on the slide
var images = targetSlide.getImages()
// get the source url of the existing image
var existingSourceURL = images[0].getSourceUrl()
Logger.log("DEBUG: Existing Source URL: "+existingSourceURL)
// get the source url of the next image in the spreadsheet
// slide urls are in column B
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet = ss.getSheetByName("SlideDetails")
var urlRange = sheet.getRange(1,2,sheet.getLastRow())
Logger.log("DEBUG: URL Range: "+urlRange.getA1Notation())
// get the values and flatten to return a 1D array
var urlValues = urlRange.getValues().flat()
Logger.log(urlValues) //DEBUG
// get the number of URLs on the spreadsheet
var valCount = urlValues.length
Logger.log("DEBUG: # of values in the sheet: "+valCount)
// find the index of the existing source url (zero-based)
var existingIdx = urlValues.indexOf(existingSourceURL)
Logger.log("DEBUG: Index of existing url: "+existingIdx);
// test if idx of existing url wasn't found AND
// test if idx of existing url = num of urls
// indexOf returns -1 if idx is not found
if (existingIdx != -1 && existingIdx != (valCount-1)){
// existing Source URL was found and the idx isn't greater than number of urls on the list
// new Source URL is next on the list
var newSourceURL = urlValues[existingIdx+1]
Logger.log("DEBUG: new source url: "+newSourceURL)
// replace the source URL
images[0].replace(newSourceURL)
}
else{
// don't change or replace the url
// don't replace the url
Logger.log("DEBUG: Image not changed because existing URL is either not found OR was last in the list")
}
Logger.log("DEBUG: Done")
}
Spreadsheet Layout
Related
On the 19th January 2022, the CellImageBuilder class was added to the Google Sheets Spreadsheet service.
This class now allows you to import an image into a cell in Google Sheets, previously you could only add an image above the cell.
Ive been trying to use this new class to take a URL link from a Google sheet, and then create an image in the cell next to the URL. This works perfectly fine if I can hard code the URL into the script (example below)
**function insertImageIntoCell()**
{
var sheet = SpreadsheetApp.getActiveSheet();
var url='Google_Docs_Image_URL'
let image = SpreadsheetApp.newCellImage().setSourceUrl(url).setAltTextDescription('TestImage').toBuilder().build();
SpreadsheetApp.getActive().getActiveSheet().getRange('C2').setValue(image);
}
The problem I am having is that once I create an array to iterate through the column the below script creates a valid array and posts it into the correct column and rows, but when it posts it back into the spreadsheet it only returns the URL and does not convert it into an image in a cell
**function insertImageIntoCell()**
{
var sheet = SpreadsheetApp.getActiveSheet();
var myStringArray = sheet.getRange('B2:B10');
var myStringArray = sheet.getRange('B2:B10').getValues();
//Logger.log(myStringArray)
let image = SpreadsheetApp.newCellImage().setSourceUrl(myStringArray).setAltTextDescription('test').toBuilder().build();
SpreadsheetApp.getActive().getActiveSheet().getRange('C2:C10').setValues(myStringArray);
}
Im using the followign code to create the initial table of data, this pull the file name and DownloadURL from a Google Drive location and then saves this into a sheet
/* modified from #hubgit and http://stackoverflow.com/questions/30328636/google-apps-script-count-files-in-folder
for this stackexchange question http://webapps.stackexchange.com/questions/86081/insert-image-from-google-drive-into-google-sheets by #twoodwar
*/
function listFilesInFolder(folderName) {
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow(["Name","URL","Image"]);
//change the folder ID below to reflect your folder's ID (look in the URL when you're in your folder)
var folder = DriveApp.getFolderById("Google_Drive_Folder");
var contents = folder.getFiles();
let image=[];
var cnt = 0;
var file;
while (contents.hasNext()) {
var file = contents.next();
cnt++;
data = [
file.getName(),
file.getDownloadUrl(),
];
sheet.appendRow(data);
};
};
I am looking for the script to refresh the file information from Google Drive into sheets, then to save the image into a cell, it now appears that this functionality exists, but Im not able to get it to take an array of URL's
Suggestion
Perhaps you can try this sample implementation below.
Sample Tweaked Script
function listFilesInFolder(folderName){
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow(["Name","URL","Image"]);
//change the folder ID below to reflect your folder's ID (look in the URL when you're in your folder)
var folder = DriveApp.getFolderById("DRIVE_FOLDER_ID");
var contents = folder.getFiles();
let image=[];
var cnt = 0;
var file;
while (contents.hasNext()) {
var file = contents.next();
cnt++;
data = [
file.getName(),
file.getDownloadUrl(),
];
sheet.appendRow(data);
};
insertImageIntoCell(); //Insert the images on column C
};
function insertImageIntoCell(){
var sheet = SpreadsheetApp.getActiveSheet();
var row = 1;
sheet.getDataRange().getValues().forEach(url =>{
if(url[1] == "URL")return row += 1;
let image = SpreadsheetApp.newCellImage().setSourceUrl(url[1]).setAltTextDescription('TestImage').toBuilder().build();
SpreadsheetApp.getActive().getActiveSheet().getRange('C'+row).setValue(image);
row += 1;
});
}
Sample Drive Folder with sample images
Sample Result:
After running the function listFilesInFolder:
Update:
This issue is filed. Add a star to this issue for Google developers to prioritize fixing this.
Issue:
setValues() is NOT working with CellImage, while setValue() does.
If/when it starts working, You need to convert each value to cellImage using map :
function insertImagesIntoCell() {
const sheet = SpreadsheetApp.getActiveSheet(),
range = sheet.getRange('B2:B10');
range.setValues(
range.getValues().map(url => [
SpreadsheetApp.newCellImage()
.setSourceUrl(url[0])
.build(),
])
);
}
For anyone struggling with importing images from Google Drive you should know that you have to set the "Sharing" setting on every individual file for CellImageBuilder to work properly.
Like this:
const imageFileUrl = imageFolder.getFilesByName(filename).next()
.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW)
.getDownloadUrl();
const cellImage = SpreadsheetApp.newCellImage().setSourceUrl(imageFileUrl).build();
Additionally, there appears to be a rate limit on the drive download URLs, causing the '.build()' function to fail randomly on a valid URL. Retries might be necessary.
Also, the .toBuilder() call on CellImageBuilder is completely redundant.
I would like to do the following with Google Apps Script:
Search an specific cell in Google Sheets with multiple URL's
Split the URL's and get them as separate links in order to avoid using the split function in sheets (watch the image
Attach each URL into a Google Doc by using tags
I've done this before, but I'm only able to obtain the URL's in one array and not separated (watch image 1 and image 2)
for (var i=0; i<row[rownumber].length; i++){
if (row[rownumber].includes(","))
img=row[rownumber].split(",");
body.replaceText('{{TagName}}',img);
}
Here you have the example in Google Sheets in order to apply the mentioned steps (link). Any help would be appreciated. Thanks!
You can refer to this sample code:
var doc = DocumentApp.openById('YourDocId');
var body = doc.getBody();
var sheet = SpreadsheetApp.getActiveSheet();
var rowValues = sheet.getRange(1,1,sheet.getLastRow(),1).getValues().flat();
//Combine all row values into a single url array
var urls = [];
rowValues.forEach(row => {
if(row.includes(",")){
var tmp = row.split(",");
urls = urls.concat(tmp);
}
});
Logger.log(urls);
Logger.log(urls.length);
if(urls.length > 0){
var tag = "{{TagName}}";
var newLine = "\n\n";
var element = body.findText(tag);
if(element){ // if found a match
var start = element.getStartOffset();
var text = element.getElement().asText();
//remove tag in the docs
text.deleteText(start,start+tag.length-1);
//Add url
urls.forEach(url => {
url = url.trim(); //remove whitespaces on both ends of the url string
Logger.log("START: "+start);
Logger.log(url);
Logger.log("URL LENGTH: "+url.length);
text.appendText(url).setLinkUrl(start, start+url.length-1, url);
text.appendText(newLine);
start = start + url.length + newLine.length;
Logger.log(text.getText());
Logger.log("*****");
});
doc.saveAndClose();
}
}
Note:
You can remove the logs if you felt like you don't need them. I just used them to debug the code.
What it does?
Get the url links from column A starting row 1 up to the last available row.
Parse each row. Split the url string into individual urls' then concatenate it to urls array.
Find your tag to be replaced in the document's body using Body.findText(searchPattern)
Get the start offset of the matched text using RangeElement.getStartOffset()
Get the element that corresponds to the RangeElement using RangeElement.getElement()
Get the element as text using Element.asText()
Delete the tag string in your document using Text.deleteText(startOffset, endOffsetInclusive)
Loop each url in the array.Take note to remove whitespaces in the current url string. Add the url text using Text.appendText(text). Once the url text was appended, include it's url link using Text.setLinkUrl(startOffset, endOffsetInclusive, url). Add a new line using Text.appendText(text) then adjust the start offset based on the url length and the new line length. (Repeat until all the url links were added in the document)
Output:
(UPDATE:)
If you want to give a different name in your hyperlink, you can replace the appended text and modify the offsets in the setLinkUrl()
Sample Code Changes:
//Add url
urls.forEach((url, index) => {
url = url.trim(); //remove whitespaces on both ends of the url string
var name = "Image"+(index+1);
Logger.log("START: "+start);
Logger.log(url);
Logger.log("URL LENGTH: "+url.length);
Logger.log("NAME LENGTH: "+name.length);
text.appendText(name).setLinkUrl(start, start+name.length-1, url);
text.appendText(newLine);
start = start + name.length + newLine.length;
Logger.log(text.getText());
Logger.log("*****");
});
Output:
I've made my way through all threads about this topic. From blob to URLs and more, to insert an image into a cell via apps-script but nothing seems to work. And most of the posts haven't gotten the solution laid out well enough to traceback the errors. So I'm trying to get an answer to my problem here. Below my code. I would also love to discuss the advantages of different methods. Blob seems to be one of the easiest when working with images already existing in G-Drive as far as I see.
function getGDriveFilesIntoCell() {
var dApp = DriveApp; // Store GDrive App in a function
var folderIter = dApp.getFoldersByName("Training_folder"); // Get folder by name
var foundfolder = folderIter.next(); // next allows to Iterate through the found folders
Logger.log(foundfolder); // Print into the logs the found folder of foundfolder
var ss = SpreadsheetApp.getActiveSpreadsheet(); //.getActiveSheet(); // Calls the Spreadsheet App and the current active Spreadsheet
var sheet = ss.getSheets()[0]; // Get first sheet
var filesIter = foundfolder.getFiles(); // Get files in found folder
var i = 1; // Define a var with value 1
while(filesIter.hasNext()){ // While loop for all files in folder found by name
var file = filesIter.next();
var filename = file.getName(); // Get Name
var filesize = file.getSize() / 1024; // Get size in kb
var file_id = file.getId(); // Get ID
var file_url = file.getUrl(); // Get Url to file
sheet.insertImage(file.getBlob(), i, 1); // Insert Image
Logger.log(filename + filesize + file_id);
Logger.log(filesize);
Logger.log(file_id);
i++; // increment i by one
// file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW) // Set file permission
// var file_blob = file.getBlob(); // Get blob
// Insert Image via custom bblob
// var file_mime_type = file.getMimeType(); // Get Mime Type
// var response = UrlFetchApp.fetch(file_url);
// var binaryData = response.getContent();
// var blob = Utilities.newBlob(binaryData, file_mime_type, filename);
// sheet.insertImage(blob, i, 1);
// Inser image via Link
// ss.getRange(i, 1).setValue("=image(\"https://drive.google.com/uc?export=view&id=" + file.getId() +"\")"); // Adds an Image via Link
// var img = Drive.Files.get(file.getId()).webContentLink;
}
}
I believe your goal as follows.
You want to put the images to Google Spreadsheet using insertImage with the blob.
You want to retrieve the images from the specific folder.
For this, how about this answer?
Modification points:
When the image is put to the Spreadsheet, please be careful the following points.
In your script, when the files except for the image are included in the folder of Training_folder, an error occurs.
When the size of images are over the maximum limitation, an error occurs. Ref
I thought that these might be the reason of your issue. So I would like to propose the following modification.
Modified script:
When your script is modified, please modify as follows. In this modification, "ImgApp" which is Google Apps Script library is used. So before you run the script, please install the GAS library. You can see how to install it at here.
From:
while(filesIter.hasNext()){ // While loop for all files in folder found by name
var file = filesIter.next();
var filename = file.getName(); // Get Name
var filesize = file.getSize() / 1024; // Get size in kb
var file_id = file.getId(); // Get ID
var file_url = file.getUrl(); // Get Url to file
sheet.insertImage(file.getBlob(), i, 1); // Insert Image
Logger.log(filename + filesize + file_id);
Logger.log(filesize);
Logger.log(file_id);
i++; // increment i by one
}
To:
while(filesIter.hasNext()){
var file = filesIter.next();
if (file.getMimeType().indexOf("image") != -1) {
var blob = file.getBlob();
var size = ImgApp.getSize(blob);
if (size.width * size.height > 1048576) {
var resized = ImgApp.doResize(file.getId(), 512);
blob = resized.blob;
}
sheet.insertImage(blob, i, 1); // Insert Image
i++; // increment i by one
}
}
In this modified script, the image files are retrieved. And, when the image size is over the maximum size for Spreadsheet, the image is resized.
Note:
From your script, you might use the script without V8. So I modified for it.
References:
SpreadsheetApp.insertImage server error
In this thread, the limitation of image for putting to Spreadsheet is discussed.
Limitations for Inserting Images to Google Docs
ImgApp
This GAS library can be retrieve from the blob of image, and the image can be resized.
I've made my way through all threads about this topic. From blob to URLs and more, to insert an image into a cell via apps-script but nothing seems to work. And most of the posts haven't gotten the solution laid out well enough to traceback the errors. So I'm trying to get an answer to my problem here. Below my code. I would also love to discuss the advantages of different methods. Blob seems to be one of the easiest when working with images already existing in G-Drive as far as I see.
function getGDriveFilesIntoCell() {
var dApp = DriveApp; // Store GDrive App in a function
var folderIter = dApp.getFoldersByName("Training_folder"); // Get folder by name
var foundfolder = folderIter.next(); // next allows to Iterate through the found folders
Logger.log(foundfolder); // Print into the logs the found folder of foundfolder
var ss = SpreadsheetApp.getActiveSpreadsheet(); //.getActiveSheet(); // Calls the Spreadsheet App and the current active Spreadsheet
var sheet = ss.getSheets()[0]; // Get first sheet
var filesIter = foundfolder.getFiles(); // Get files in found folder
var i = 1; // Define a var with value 1
while(filesIter.hasNext()){ // While loop for all files in folder found by name
var file = filesIter.next();
var filename = file.getName(); // Get Name
var filesize = file.getSize() / 1024; // Get size in kb
var file_id = file.getId(); // Get ID
var file_url = file.getUrl(); // Get Url to file
sheet.insertImage(file.getBlob(), i, 1); // Insert Image
Logger.log(filename + filesize + file_id);
Logger.log(filesize);
Logger.log(file_id);
i++; // increment i by one
// file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW) // Set file permission
// var file_blob = file.getBlob(); // Get blob
// Insert Image via custom bblob
// var file_mime_type = file.getMimeType(); // Get Mime Type
// var response = UrlFetchApp.fetch(file_url);
// var binaryData = response.getContent();
// var blob = Utilities.newBlob(binaryData, file_mime_type, filename);
// sheet.insertImage(blob, i, 1);
// Inser image via Link
// ss.getRange(i, 1).setValue("=image(\"https://drive.google.com/uc?export=view&id=" + file.getId() +"\")"); // Adds an Image via Link
// var img = Drive.Files.get(file.getId()).webContentLink;
}
}
I believe your goal as follows.
You want to put the images to Google Spreadsheet using insertImage with the blob.
You want to retrieve the images from the specific folder.
For this, how about this answer?
Modification points:
When the image is put to the Spreadsheet, please be careful the following points.
In your script, when the files except for the image are included in the folder of Training_folder, an error occurs.
When the size of images are over the maximum limitation, an error occurs. Ref
I thought that these might be the reason of your issue. So I would like to propose the following modification.
Modified script:
When your script is modified, please modify as follows. In this modification, "ImgApp" which is Google Apps Script library is used. So before you run the script, please install the GAS library. You can see how to install it at here.
From:
while(filesIter.hasNext()){ // While loop for all files in folder found by name
var file = filesIter.next();
var filename = file.getName(); // Get Name
var filesize = file.getSize() / 1024; // Get size in kb
var file_id = file.getId(); // Get ID
var file_url = file.getUrl(); // Get Url to file
sheet.insertImage(file.getBlob(), i, 1); // Insert Image
Logger.log(filename + filesize + file_id);
Logger.log(filesize);
Logger.log(file_id);
i++; // increment i by one
}
To:
while(filesIter.hasNext()){
var file = filesIter.next();
if (file.getMimeType().indexOf("image") != -1) {
var blob = file.getBlob();
var size = ImgApp.getSize(blob);
if (size.width * size.height > 1048576) {
var resized = ImgApp.doResize(file.getId(), 512);
blob = resized.blob;
}
sheet.insertImage(blob, i, 1); // Insert Image
i++; // increment i by one
}
}
In this modified script, the image files are retrieved. And, when the image size is over the maximum size for Spreadsheet, the image is resized.
Note:
From your script, you might use the script without V8. So I modified for it.
References:
SpreadsheetApp.insertImage server error
In this thread, the limitation of image for putting to Spreadsheet is discussed.
Limitations for Inserting Images to Google Docs
ImgApp
This GAS library can be retrieve from the blob of image, and the image can be resized.
I am just beginning to learn Javascript and Google Apps Script. I have looked at and played with a few scripts, and so am attempting to create my own. What I want to do is take a list of students (Name and Email) and run a script to create "dropboxes", or folders that uses their name and is shared to their email address. This way, they can easily submit work to me in an organized manner. I have written this rough script, which I know will not work.
I was wondering if anyone can give me some tips?
function createDropbox () {
// Get current spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var data = sh1.getDataRange().getValues();
// For each email address (row in a spreadsheet), create a folder, name it with the data from the Class and Name column, then share it to the email
for(n=1;n<data.length;++n){
var class = sheet.getSheetValues(n, 1, 1, 1);
var name = sheet.getSheetValues(n, 2, 1, 1);
var email = sheet.getSheetValues(n, 3, 1, 1);
var folder = DocsList.createFolder('Dropbox');
folder.createFolder(class . name);
var share = folder.addEditor(email);
}
}
You've got the basic structure of your script right, it's only the semantics and some error handling that need to be worked out.
You need to determine how you want to access the contents of your spreadsheet, and be consistent with that choice.
In your question, you are first getting all the contents of the spreadsheet into a two-dimensional array by using Range.getValues(), and then later trying to get values directly from the sheet multiple additional times using .getSheetValues().
Since your algorithm is based on working through values in a range, use of an array is going to be your most effective approach. To reference the content of the data array, you just need to use [row][column] indexes.
You should think ahead a bit. What will happen in the future if you need to add more student dropboxes? As your initial algorithm is written, new folders are created blindly. Since Google Drive allows multiple folders with the same name, a second run of the script would duplicate all the existing folders. So, before creating anything, you will want to check if the thing already exists, and handle it appropriately.
General advice: Write apps script code in the editor, and take advantage of auto-completion & code coloring. That will help avoid mistakes like variable name mismatches (ss vs sh1).
If you are going to complete the exercise yourself, stop reading here!
Script
This script has an onOpen() function to create a menu that you can use within the spreadsheet, in addition to your createDropbox() function.
The createDropbox() function will create a top level "Dropbox" folder, if one does not already exist. It will then do the same for any students in the spreadsheet, creating and sharing sub-folders if they don't already exist. If you add more students to the spreadsheet, run the script again to get additional folders.
I've included comments to explain some of the tricky bits, as a free educational service!
/**
* Create menu item for Dropbox
*/
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Create / Update Dropbox",
functionName : "createDropbox"
}];
sheet.addMenu("Dropbox", entries);
};
function createDropbox () {
// Get current spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var data = ss.getDataRange() // Get all non-blank cells
.getValues() // Get array of values
.splice(1); // Remove header line
// Define column numbers for data. Array starts at 0.
var CLASS = 0;
var NAME = 1;
var EMAIL = 2;
// Create Dropbox folder if needed
var DROPBOX = "Dropbox"; // Top level dropbox folder
try {
// getFolder throws an exception if folder not found.
var dropbox = DocsList.getFolder(DROPBOX);
}
catch (e) {
// Did not find folder, so create it
dropbox = DocsList.createFolder(DROPBOX);
}
// For each email address (row in a spreadsheet), create a folder,
// name it with the data from the Class and Name column,
// then share it to the email
for (var i=0; i<data.length; i++){
var class = data[i][CLASS];
var name = data[i][NAME];
var email = data[i][EMAIL];
var folderName = class + ' ' + name;
try {
var folder = DocsList.getFolder(DROPBOX + '/' + folderName);
}
catch (e) {
folder = dropbox.createFolder(folderName)
.addEditor(email);
}
}
}
Even though the question is ~6 years old it popped up when I searched for "create folders from sheets data" .
So , taking the answer as inspiration, I had to update the code to allow for changes in the Google API, i.e. no more DocsList.
So here it is.
function createMembersFolders () {
// Get current spreadsheet
var MembersFolder = DriveApp.getFolderById("1Q2Y7_3dPRFsblj_W6cmeUhhPXw2xhNTQ"); // This is the folder "ADI Members"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var data = ss.getDataRange().getValues() // Get array of values
// Define column numbers for data. Array starts at 0.
var NAME = 1;
// For each name, create a folder,
for (var i=1; i<data.length; i++){ // Skip header row
var name = data[i][NAME];
Logger.log(name);
if(MembersFolder.getFoldersByName(name).hasNext()){
Logger.log("Found the folder, no need to create it");
Logger.log(Object.keys(MembersFolder.getFoldersByName(name)).length);
} else {
Logger.log("Didn't find the folder so I'll create it");
var newFolder = MembersFolder.createFolder(name);
}
}
}
Note that I'm taking the parent folder directly using it's ID (which you get from the URL when viewing the folder).
You could also do this by name using the DriveApp.getFoldersByName("Folder Name").hasNext() condition which checks if the folder exist. If it does exist then you can access that folder you have found via DriveApp.getFoldersByName("Folder Name").next()
I didn't find that use of hasNext and next very intuitive but there it is.