I'm on GSuite Business and i have made a Google Apps Script for read the content on a GDrive folder and write on Column A the name of the file and on Column B the GDrive Link of the file.
I have about 8800 Files on this folder and i go over the 30 minutes execution time quota.
at this time i don't have idea to solve this problem..
I past here my script...
This script are useful for see the list of images of the product for sync with my ecommerce.
function ImageDatabaseUpdate() {
//read file on my drive foldeer -> 06 - usato fine serie
var foldername = '06 - Usato e Fine serie';
var folderlisting = 'Database GTLG ';
var folders = DriveApp.getFoldersByName(foldername)
var folder = folders.next();
var contents = folder.getFiles();
var contents = folder.getFiles();
//Set file id and sheet Immagini
var ss = SpreadsheetApp.openById("1ok2tfpLFRHE6I4ehR9lfsLwtFy1UfTdJqbi-NCqGVS0");
var sheet = ss.getSheetByName('immagini');
//Write heading on first sheet row
sheet.appendRow(['name','link']);
var file;
var name;
var link;
var row;
//start reading and writing
while(contents.hasNext()){
file = contents.next();
name = file.getName();
link = file.getUrl();
sheet.appendRow([name, link]);
}
}
Your code goes into an infinite loop because you need contents.next() to move to the next file. Since the folderIterator doesn't increment, while(contents.hasNext()) will continue forever.
Related
I'm currently have a Google Sheet (Pushed to a website via PHP) with all my clients beer data. I'd like to take that data and copy it into a Google Doc Template for easy printing. In my example I can move the first row of data from the Sheet into the Doc but all the other rows from the sheet do not copy over.
I could use some help with the forEach statement, I'm thinking I need to parse the array and iterate through it in a different way than I'm currently attempting. (First time using Apps Script)
Here is what I've currently coded up.
function onOpen() {
const ui = SpreadsheetApp.getUi();
const menu = ui.createMenu('Print Menu');
menu.addItem('Create New Print Menu', 'createNewMenu')
menu.addToUi();
}
function createNewMenu() {
//Google Doc Template ID and Where to Save the New File
const googleDocTemplate = DriveApp.getFileById('1xzlvVOSW_LsgOrm2N2o1-FKYzfqp_2EAbhqrLTn53yk');
const destinationFolder = DriveApp.getFolderById('11HU0TvSPMMXUZaK5gTgg8jvofxTTt02j');
//Get all spreadsheet sheets and add values as 2D arrays.
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Draft List');
const rows = sheet.getDataRange().getValues();
//Create date for new filename.
const dateData = new Date();
const curr_date = dateData.getDate();
const curr_month = dateData.getMonth() + 1; //Months are zero based
const curr_year = dateData.getFullYear();
const theDate = curr_year + "-" + curr_month + "-" + curr_date;
const newFileName = theDate + ' - Bar Print Menu';
//Using the row data in a template literal, we make a copy of our template document in our destinationFolder
const copy = googleDocTemplate.makeCopy(newFileName, destinationFolder)
//Once we have the copy, we then open it using the DocumentApp
const doc = DocumentApp.openById(copy.getId())
//All of the content lives in the body, so we get that for editing
const body = doc.getBody();
rows.forEach(function(rowData) {
//In these lines, we replace our template replacement tokens with values from our spreadsheet rows.
body.replaceText('{{onTapName}}', rowData[0]);
body.replaceText('{{onTapDescription}}', rowData[1]);
body.replaceText('{{onTapPrice}}', rowData[2]);
//Logger.log(rowData);
});
//We make our changes permanent by saving and closing the document
doc.saveAndClose();
}
This code will create a copy of the template file, copy the first row of data from Google Sheets and paste it into the template in the {{onTapName}}, {{onTapDescription}} & {{onTapPrice}} areas but the other rows from the Google Sheet do not copy over.
- Screenshot of Google Sheet, Google Doc Template and Result after running above code
If I uncomment out the "Logger.log(rowData);" line, I can see the code is going through each line of the data from the Google Sheet.
- Screenshot of Execution Log
How do I modify this forEach area to copy through each line of code into the template? I feel like I'm missing something very obvious here.
Thanks in advance for the help.
I am looking for a GoogleScript which can automatically insert the image in the cell based on File Name. The steps are below:
Get Name (in Column A)
Lookup the image file in "Image Folder"
Insert the image with fixed size (Column B)
I am attaching the sheet for your understanding.
GDoc
Folder
Script that I use but is not working:
function listFilesInFolder(folderName) {
//writes the headers for the spreadsheet
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow(["Image"]);
var folderId = "1AV5pTs3l7GGMNH7-C8rixjcWNNTsmbpE";
var folder = DriveApp.getFolderById(folderId);
var contents = folder.getFiles();
var cnt = 0;
var file;
while (contents.hasNext()) {
var file = contents.next();
cnt++;
Logger.log(file);
Logger.log(cnt);
// writes the various chunks to the spreadsheet- just delete anything you don't want
data = [
"https://docs.google.com/uc?export=download&confirm=no_antivirus&id=" + file.getId(),
file.getDescription(),
"=image(\"https://docs.google.com/uc?export=download&id=" + file.getId() +"\")",
];
sheet.appendRow(data);
};
};
I need to transfer ownership of thousands of files I own to someone else with editing access, but I've learned that Google Drive requires you to do this one file at a time. With intermediate but growing JS experience I decided to write a script to change the owner from a list of file IDs in a spreadsheet, however I've run into trouble and I have no idea why. The debugger just runs through the script and everything looks sound for me. I'd greatly appreciate any help.
function changeOwner() {
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/********/').getSheetByName('Sheet1');
var range = ss.getRange(1,1,2211);
for (i = 0; i < range.length; i++){
var file = range[i][0].getValue();
var fileid = DriveApp.getFileById(file);
fileid.setOwner('******#gmail.com');
}
}
Tested below code working fine with IDs,
function myFunction() {
var spreadsheet = SpreadsheetApp.openById('ID');
var range = spreadsheet.getDataRange().getValues();
for (i = 0; i < range.length; i++){
var file = range[i][0].toString();
var fileid = DriveApp.getFileById(file);
fileid.setOwner('***#gmail.com');
}
}
Your issue is that the Range class had no length property. Instead, perform a getValues() call on the range to efficiently create a JavaScript array, and iterate on it:
function changeOwner() {
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/********/').getSheetByName('Sheet1');
var values = ss.getRange(1, 1, 2211).getValues();
for (i = 0; i < values.length; ++i){
var fileid = value[i][0];
var file = DriveApp.getFileById(fileid);
file.setOwner('******#gmail.com');
}
}
There are other improvements you can make, such as:
dynamic range read (rather than the fixed assumption of 2211 rows of data)
writing to a second array to keep track of which files you have yet to process
checks for if the file exists
checks for if the file is actually owned by you
checks for execution time remaining, to allow serializing any updates/tracking you do that prevents the next execution from repeating what you just did
and so on. I'll let you research those topics, and the methods available in Apps Script documentation for the DriveApp, SpreadsheetApp, Sheet, and Range classes. Note that you also have all features of Javascript 1.6 available, so many of the things you find on a Javascript Developer Reference (like MDN) are also available to you.
Please help make the script. As written below, I wrote a script that worked for some time. Now it does not work and I need help writing a new one.
The challenge is this: when you make changes in column F, K and O - occurs first check the availability of the text in the column to the - then if there is a text should start sorting first by F column - then sorting by a column O
There is a scheme of action sequences by the link:
https://drive.google.com/file/d/0B5qSx6LqB8U-d01URS1BcEVtNGs/view?usp=sharing
I will be happy if someone can help me.
In any case, thanks for your time and attention :) Have a nice day :)
29/03/17 I need help "Service error: spreadsheets"
A very recently worked script:
function onEdit() {
var ss = SpreadsheetApp.getActiveSheet();
var r = SpreadsheetApp.getActiveRange();
var cols = r.getColumn();
var rows = r.getRow();
var who = ss.getRange(rows,11).getValue();
if (who !== "") {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0]
sheet.sort(6);
sheet.sort(15);}
}
Today received an error:
Service error: spreadsheets
The script stopped working at all, help, please.
I'm not following how this completes your action sequence flow chart, but I believe this should get it running as before. I've seen other posts where people get this same Service Error message form previously working scripts, and I believe Google is trying to change how certain tasks are done to help their server loads.
function onEdit() {
var ss = SpreadsheetApp.getActive();
var r = SpreadsheetApp.getActiveRange();
var cols = r.getColumn();
var rows = r.getRow();
var who = ss.getActiveSheet().getRange(rows,11).getValue();
if (who !== "") {
var sheet = ss.getSheets()[0];
sheet.sort(6);
sheet.sort(15);}
}
I removed the duplicate definition of var ss and tweaked var ss, var who and var sheet to work without it.
Could anyone please help me optimise this Google Sheets script?
It's painfully slow. It barely makes 300 copies in 24 hours (I need the Drive API to make the copies as "view only users can't copy/print/download")
function addCopies() {
var count = 10;
var input = DriveApp.getFileById('1GQI5m0g5XsCWi1dOTBWFs3VJkzW7e8N__09C3-2BEGI')
var results = DriveApp.getFileById('1gkOCTPJuqTQnNNlaE3jD2Hq2COU-lO02PmlO_xMepx0')
var indexSH = SpreadsheetApp.openById('1o6ZfweVylhnDXoVc9u_R8afKdVfXYgtdqtj_lSCdFEk').getSheetByName('Index')
for(var i=0;i<count;i++)
{
//make copies of both files (input & results)
var inputCopy = input.makeCopy(input.getName(), DriveApp.getFolderById('0B0go-fsdFA3ISG0xNGlhTDZoM0U'))
inputCopy.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.EDIT)
var inputID = inputCopy.getId()
//make results to be restricted using API
var resultsCopy = results.makeCopy(results.getName(), DriveApp.getFolderById('0B0go-fsdFA3ISG0xNGlhTDZoM0U'))
resultsCopy.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW)
var resultsID = resultsCopy.getId()
var apiFile = DriveAPI.Files.get(resultsID)
apiFile.labels.restricted = true
DriveAPI.Files.update(apiFile, resultsID)
//save IDs of both files to an index for later re-use
var lastRow = indexSH.getRange(1,1).getValue()
var addRng = indexSH.getRange(lastRow+1, 1,1,3)
addRng.setValues([['free',inputID,resultsID]])
}
}
Edit: techydesigner said "we don't optimise code on SO" . So please let me rephrase : am I using the wrong Drive services ? Is there a method to make those copies faster ?