Clear, copy and paste from one file to another using google script - google-apps-script

I have this script running from one source file to several other files where I use the data. The script has always tended to work fine but recently started getting the error
Exception: Service Spreadsheets timed out while accessing document with id.
I only get the error when the script is running for a particular destination file, as opposed to others. It also happens that this destination file is much larger than the others (maybe the problem). Anyway, the script is below and wondering if anyone has any alternative suggestions or feedback.
function Function_name() {
var ss=SpreadsheetApp.getActiveSpreadsheet()
var sourcesheet=ss.getSheetByName("RAWFINEX")
var data=sourcesheet.getDataRange().getValues()
var destinationfile=SpreadsheetApp.openById("Sheet ID")
var destinationsheet=destinationfile.getSheetByName("RAWFINEX")
var destinationlr=lastUsableRow(destinationsheet)
var destinationlc=destinationsheet.getLastColumn
var existingdata=destinationsheet.getRange(1,1,destinationlr,5).clearContent
var destinationrange=destinationsheet.getRange(1,1,data.length,data[0].length)
var pastedata=destinationrange.setValues(data)
}

Copy Data And Log
function CopyDataAndLog() {
var log = DriveApp.getFileById("logid");
var ss=SpreadsheetApp.getActive();
var ssh=ss.getSheetByName("RAWFINEX");
var svs=ssh.getDataRange().getValues();
var ss=SpreadsheetApp.openById("Sheet ID")
var fi=DriveApp.getFileById(ss.getId())
log.setContent(log.getBlob().getDataAsString() + `${fi.getSize()},${file.getName()},${file.getId()},${file.getType()}${'\r\n'}}`;
var tsh=ss.getSheetByName("RAWFINEX")
var tlr=lastUsableRow(tsh)
tsh.getRange(1,1,tlr,5).clearContent();
tsh.getRange(1,1,svs.length,svs[0].length).trg.setValues(svs);
}

Related

Is there a way to avoid timeout errors in Google Sheets when Scripting Imports

I've got a few large databases kept on sheets right now. We have them connected for visualization purposes to many other sheets. We have previously had an Update Script that would copy & Paste info from the main large databases to a sheet within each associated Visualization. This update button has broken down and we have been receiving Timeout errors when trying to call that spreadsheet. Is there a way to get around timeout errors on the following Code?
Specifically, the timeout errors seem to occur on the
var igs = SpreadsheetApp.openByUrl('*URL_HERE*');. If there is a way to reduce the stress and increase the effectiveness of this SpreadSheet App Connection I would love to know! Thanks for the time
function UpdateIGS(){
var ssopen = SpreadsheetApp.getActiveSpreadsheet();
var opentable = ssopen.getSheetByName('IGS Open');
opentable.getRange('A:BT').clearContent();
var ssclosed = SpreadsheetApp.getActiveSpreadsheet();
var closedtable = ssopen.getSheetByName('IGS Closed');
closedtable.getRange('A:BT').clearContent();
var igs = SpreadsheetApp.openByUrl('*URL_HERE*');
var igsopen = igs.getSheetByName('1.a Solar Master Open');
var igsclosed = igs.getSheetByName('1.b Solar Master Closed');
var igsopenid = igsopen.getRange('A:BT').getValues();
var igsopencount =igsopenid.length;
var igsclosedid = igsclosed.getRange('A:BT').getValues();
var igsclosedcount =igsclosedid.length;
opentable.getRange(1,1, igsopencount, 72).setValues(igsopenid);
closedtable.getRange(1,1, igsclosedcount, 72).setValues(igsclosedid);
}
Note: The URL_Here is just a placeholder for security purposes. Thanks y'all!

File not found when using Drive.Files.get(path)

I am trying to automate attaching and sending emails using Gscripts. Each recipient has his own unique attachment so I have a Google sheet containing the details:
Column A contains the email addresses.
Column B contains the message.
Column D contains the filename of the attachment along with the file extension.
Here's my code:
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var rowEmails = sheet.getRange(1,1,3);
var rowMessage = sheet.getRange(1,2,3);
var rowAttachments = sheet.getRange(1,4,3);
var vEmails = rowEmails.getValues();
var vMessage = rowMessage.getValues();
var vAttachments = rowAttachments.getValues()
for (i in vEmails) {
var emailAddress = vEmails[1] + '';
var message = vMessage[1];
var subject = "Test"
var path = 'certs\\' + vAttachments[i]
var file = Drive.Files.get(path);
MailApp.sendEmail(emailAddress, subject, vMessage[1], {attachments: files});
}
}
Everything works well but when it comes to var file = Drive.Files.get(path), I get an error saying no file is found. I checked my drive and I'm sure it is there. I've also checked the Drive API. I don't know what is wrong.
Something like this might be a little closer to working:
function sendEmails() {
var sheet=SpreadsheetApp.getActiveSheet();
var Emails=sheet.getRange(1,1,3).getValues();
var Message=sheet.getRange(1,2,3).getValues();
var fileids=sheet.getRange(1,3,3).getValues();//you need to add file ids
Emails.forEach(function(r,i){
MailApp.sendEmail(Emails[i][0],"Test",Message[i][0],{attachments:[DriveApp.getFileById(fileids[i][0])]});
});
}
The code in the question has several flaws:
path : Google Drive doesn't use "path"
for in / vAttachments[i]: a different property name is assigned to the variable on each iteration but vAttachments hasn't named properties, so vAttachments[i] will return null on each iteration.
The files property on the options should be an Array.
How to "fix" the script
The way to directly get files in Google Drive is by using file ids.
If you want to get files by "path", first your script should get the folder, then look for the file inside that folder but bear in mind that getting a folder/file by name returns a folder/file iterator
Instead of for in use for of or use for (most of the scripts I have seen usen use for)

Which file does my script pick first when moving a file?

I have a Google Apps script that moves a Google Drive file to another Google Drive map. This happens every 4 hours because of a time-based trigger. Does anyone know which file it chooses to move? The files have a random name so should be moved randomly. However, it seems the scripts only moves the last uploaded files.
For context: I use the script in combination with IFTTT for this Twitter account.
var files = DriveApp.getFolderById("SourceFolderId").getFiles();
{
var file = files.next();
var destination = DriveApp.getFolderById("TargetFolderId");
destination.addFile(file);
var pull = DriveApp.getFolderById("SourceFolderId");
pull.removeFile(file);
}
}
Try this:
function moveRandomly(s,t) {
var files=DriveApp.getFolderById(s).getFiles();
var fA=[];
while(files.hasNext()){fA.push(files.next().getId());}
var file=DriveApp.getFileById(fA[Math.floor(Math.random()*fA.length)]);
var destination=DriveApp.getFolderById(t);
destination.addFile(file);
var pull=DriveApp.getFolderById("SourceFolderId");
pull.removeFile(file);
}

Trying to create tree-view of google drive folders

Many thanks for the comments and response. That code was a little too advanced for me and I ended up finding a very inelegant solution that I used because I ran out of time. I was able to get the code to list Folder and first level of subFolders with links, but I have not yet been able to get it to iterate through all levels of folders, mostly because I just need to back up and learn a lot of the basics. I was also able to get all folders to list using some code I found to create a tree, but I couldn't get it to format in a way that you could actually see the structure, or add links. I'm going to continue to try, and will post if I sort it out. Here is what I used, which was fine for our purposes because our shared drive is fairly limited.
For reference, this was the code I used to start with:
https://superuser.com/questions/1095578/list-of-subfolder-names-and-file-links-in-google-sheets-script
function listFolders(foldername) {
var ss = SpreadsheetApp.openById(ID);
var sheet = ss.getSheetByName("sheet name");
sheet.appendRow("Parent Folder", "Name", "Link" ]);
//change the folder ID below to reflect your folder's ID (look in the
URL when you're in your folder)
var folders = DriveApp.getFolderById(ID);
var contents = folders.getFolders();
var cnt = 0;
var folderD;
while (contents.hasNext()) {
var folderD = contents.next();
cnt++;
data = [
folders.getName(),
folderD.getName(),
folderD.getUrl(),
];
sheet.appendRow(data);
};
};
Original Post:
I am a beginner using script in google sheets and I am trying to create a list of folders in a google drive with many subfolders. Ideally it would be a tree form but I'd settle for a list at this point. I don't need to list all the files, just the folders. I have been trying to get the code below to work but it keeps hanging up at calling up the spreadsheet. Can anyone help?
I have tried calling up both the folders and the spreadsheet by both name and ID but it always tells me it can't execute the getactivespreadsheet command. I have also tried to modify the code referred to in another another question but I can't get that to work either: https://ctrlq.org/code/19923-google-drive-files-list
function generateFolderIndex(myfoldername) {
var folder = DriveApp.getFolderById('0B8vOJQUb-IIVTHdudlZSVkdtdE0');
var subFolders = folder.getFolders();
var childFolders = subFolders
var ss = SpreadsheetApp.getActiveSpreadsheet('1Trv9OtJFnD4AdSHrZKFfsSu6JMV9f78H6wwZNhF2_M4');
var sheet = ss.getSheetByName('Directory');
sheet.clear(directory);
sheet.appendRow([name, link]);
while (subFolders.hasNext())
{
var childFolder = childFolders.next();
var foldername = childFolder.getname();
var name = childFolder.getName()
var link = childFolder.getUrl()
var date = childFolder.getDateCreated()
data = [name, link]
sheet.appendRow(data);
}
};
I am trying to get a sheet that lists folders and subfolders with URL links. I am currently receiving the following error message:
[19-05-31 15:32:20:911 EDT] Execution failed: Cannot find method getActiveSpreadsheet(string). (line 5, file "Code") [0.432 seconds total runtime]
Or.. the easy way...
Use DRIVE or FS DRIVE APP for desktop in PC. Usea A CMD (windows)... AND THE FUNCTION
TREE >a.txt
The generated file a.txt will display all the tree.
IT SAVES HOURS OF RESEARCH.
SpreadsheetApp.getActiveSpreadsheet() doesn't have any parameters.
However
SpreadsheetApp.openById('ssid') does require and id. I think perhaps you meant to be using openById();
openById
getActiveSpreadsheet
This is a script that I'm currently working on but it generates a list of Spreadsheets and you can exclude folders by id and files by id.
function getAllSpreadsheets() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('FilesAndFolders');
if(sh.getLastRow()>0) {
sh.getRange(1,1,sh.getLastRow(),2).clear().clearDataValidations();
}
getFnF();
SpreadsheetApp.getUi().alert('Process Complete')
}
var level=0;
function getFnF(folder) {
var folder= folder || DriveApp.getRootFolder();
//var folder=DriveApp.getRootFolder();
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('FilesAndFolders');
var files=folder.getFilesByType(MimeType.GOOGLE_SHEETS)
while(files.hasNext()) {
var file=files.next();
if(isExcluded(file.getId(),'file')){continue;}
var firg=sh.getRange(sh.getLastRow() + 1,level + 1);
firg.setValue(Utilities.formatString('=HYPERLINK("%s","%s")',file.getUrl(),'FILE: ' + file.getName()));
firg.offset(0,1).insertCheckboxes('Exclude','Include');
}
var subfolders=folder.getFolders()
while(subfolders.hasNext()) {
var subfolder=subfolders.next();
if(isExcluded(subfolder.getId(),'folder')){continue;}
var forg=sh.getRange(sh.getLastRow() + 1,level + 1);
forg.setValue(Utilities.formatString('=HYPERLINK("%s","%s")',subfolder.getUrl(),'FOLDER: ' + subfolder.getName()));
//forg.offset(0,1).insertCheckboxes('Exclude','Include');
//level++;
getFnF(subfolder);
}
//level--;
}
function isExcluded(id,type) {//type: file or folder
var type=type||'Missing Input';
var xFldrIdA=['Excluded folder ids'];
var xFileIdA=['Excluded file ids'];
var type=type.toLowerCase();
switch(type) {
case 'file':
return xFileIdA.indexOf(id)>-1;
break;
case 'folder':
return xFldrIdA.indexOf(id)>-1;
break;
default:
throw(Utilities.formatString('Error: Invalid Type: %s in isExcluded.',type));
return true;//assume excluded
break;
}
}
Your welcome to use it, perhaps it will help.

How to open google spreadsheet using script and partial filename

My goal is to get a partial filename from a cell(B2) using a script and find the complete URL, put the resulting URL in cell B3 so I can run a series of queries in the data. I've spent more hours searching google than I care to admit on this. I'm sure the answer is there but my in-experience with google scripting is preventing me from seeing.
Thanks for any help.
Files of a Feather
The feather is the partial string which must be provided. You can use a prompt if you want it to be interactive with a user.
function getFilesOfAFeather(feather) {
var files=DriveApp.getFiles();
var fA=[];
while(files.hasNext()){
var file=files.next();
if(file.getName().indexOf(feather)>-1) {
fA.push({name: file.getName(), id: file.getId(), url: file.getUrl()});
}
}
return fA;
}
If fA.length=0 then no files were found.
If fA.length=1 then var url=fA[0].url;
If fA.length>1 then you have to pick which one you want
function findUrl() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
var feather=sh.getRange('B2').getValue();
var f=getFilesOfAFeather(feather);
if(f.length==1) {
return f[0].url;
}else{
SpreadsheetApp.getUi().alert(Utilities.formatString('Number of files found: ',f.length));
}
}