How to archive data with google scripts - google-apps-script

I'm new to writing scripts and am attempting to get started on archiving my data. Right now I have this script, which I thought was a good start, but am getting an error when I attempt to run it.
On the sheet named "Allergen Planner" I have a live CSS feed in cell N17 which updates every hour. I am attempting to archive that data once daily and place it in a new sheet called "Archived data". I've tried looking into researching on my own for some time now, but am struggling to find something that can help. Everything I've found is way above my capabilities. Is there anything I can edit in my script which would achieve what I'm looking for? Any help would be greatly appreciated.
{
var ssA = SpreadsheetApp.openById('1ji3Q02uOyrDXyrl7LcghWLcLjz-CeSUgSCU7QD0BVEk');
var sheetA = ssA.getSheetByName('Allergen Planner');
var dataToMove = sheetA.getRange(14,17,sheetA.getLastRow(),sheetA.getLastColumn()).getValues();
var ssB = SpreadsheetApp.openById('1ji3Q02uOyrDXyrl7LcghWLcLjz-CeSUgSCU7QD0BVEk');
var sheetB = ssB.getSheetByName('Archived Data');
dataToMove.forEach(function(elts){
sheetB.appendRow(elts)
});
}

The code pasted above worked. If you receive a red "Unkown error occurred" message in the execution log, reboot the script app and try again.

Related

Google Sheet Error: Service Spreadsheets timed out while accessing document with id

I get this error "Service Spreadsheets timed out while accessing document with id ..." every time I run a very simple code, in which I am basically copying data from one google sheet to another using getValues() and setValues().
I don't think it is because of 5M cells limit, because the same exact function is working perfectly fine in another Google Sheet with even bigger size. So I really don't understand where the problem is.
I have tried to create an empty GS and run the function, so I am only pulling data without any other calculation, but still, it gives me the same error.
Any idea what the reason could be?
Here the code as reference:
function MyFunction(){
var pm_ss_0 = SpreadsheetApp.openById('...');
var pm_tab_0 = pm_ss_0.getSheetByName('...');
var pm_data_0 = pm_tab_0.getDataRange().getValues();
var target_ss_0 = SpreadsheetApp.getActiveSpreadsheet();
var target_tab_0 = target_ss_0.getSheetByName('...');
target_tab_0.clearContents();
var target_data_0 = target_tab_0.getRange(1, 1, pm_data_0.length,
pm_data_0[0].length).setValues(pm_data_0);
}
I solved the issue inserting a flush before and after the line where the error appeared.
SpreadsheetApp.flush();
ss.insertSheet("Report "+fogl.getName(), ss.getNumSheets()); //line with the error in my code
SpreadsheetApp.flush();
This issue has also been reported on Google's Issue tracker
Go there and star the issue so you get the updates on it.
This problem is more random than 95% of the commentary on the Web about it attests to. I just had this happen to me for the first time, and it even affected a Macro that did absolutely nothing but hide the Active Tab. I couldn't do anything with Script Editor.
I tried simply duplicating the document. BION, that was the end of the problem for me. Or at least, so far.

my script "GET URL from google document" does not work any more - server failure WHY?

In general I want to print the URL of the google document I am actually working with in a text field.
If I copy the google sheet the function should also work for the new document.
I scripted a solution which was working for 20 month and now I have a problem.
Now I would like to know what could happen? Why do I have a server problem? Is is it possible to have to many google documents, (i have ~9000 - it works as a small ERP system) that the server got problems?
Formula in Google sheet:
=hyperlink(getSheetUrl()
Code in Script editor:
function getSheetUrl() {
var SS = SpreadsheetApp.getActiveSpreadsheet();
var ss = SS.getActiveSheet();
var url = '';
url += SS.getUrl();
url += '#gid=';
url += ss.getSheetId();
return url;
}
This is the error message in my document:
Error: Server error occurred. Please try saving the project again. (Row 0).
If I try to save the project in my script editor I get no failure.
If I try to run the project in my script editor I get:
A server error has occurred. Please try to save the project again.
Thanks for your answers.
Today I started the system and everything works fine.
Yesterday i was also able to run my code in a new enviroment, but i was not able to copy a existing document. there i got the failure.
Maybe it was really because the lan connection was to weak.
My company is a very rural area ;)
I will take an eye on that,
By the way.
Does anyone has another idea how to get the link from a document and print it in a textfield in the same document (hopefully you know what i mean)

Inserting Image into Google Sheets from Google Drive using Apps Script

I have been trying for 9 days to add an image that is uploaded to my drive (via the use of a google form) into my Google sheet using Apps Script, but it isn't working and I have no idea why, this is my code below:
function getImage(){
var folderImage = DriveApp.getFolderById("0B7gxdApLS0TYfm1pRHpHSG4yTm96bm1PbTZQc1VmdGpxajY4N1J4M1gtR1BiZ0lOSl9NMjQ");
Logger.log(folderImage.getFiles().next().setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.VIEW));
Logger.log(folderImage.getFiles().next().getSharingAccess());
Logger.log(folderImage.getFiles().next().getSharingPermission());
var imageFile = folderImage.getFiles().next().getBlob();
detailSheet.insertImage(imageFile, 1, 13);
}
I have even tried making the sharing and access permissions of the to be as open as possible but I keep getting this error message:
"We're sorry, a server error occurred. Please wait a bit and try again"
I find the error message ambiguous which leads me at a dead end. Usually the message gives me a good idea of where I have gone wrong.
I believe my code is correct, and during my research I have found no definitive reason this shouldn't work. Does anybody know where I am going wrong?
A solution would be great but preferably a critique on my code so I can learn :)
Couple of issues with your script:
You never bind to a specific file, so to work with the same file you have to reinitialize the iterator each time.
You don't verify its mimetype prior to using it as an image
An example that resolves those issues:
function addFolderPNGs_(sheet, folderId) {
const folder = folderId ? DriveApp.getFolderById(folderId) : DriveApp.getRootFolder(); // scope only to the root or given folder.
const imgs = folder.getFilesByType(MimeType.PNG);
var targetRow = sheet.getLastRow();
while (imgs.hasNext()) {
var img = imgs.next();
Logger.log(img.getName())
sheet.insertImage(img.getBlob(), 1, ++targetRow);
}
}
References
getFilesByType is either folder-specific (above) or operates on all of Google Drive
DriveApp
Folder
MimeTypes
Sheet#insertImage

Why Google Apps Script hangs on calling next() function

Today I can't run scripts connected to a specific Google Spreadsheet which contains .next() function calls, which I use to access other Spreadsheets by name. It shows Running script Cancel Dismiss message at the top of spreadsheet until exceeding maximum execution time. The strange thing is that I have similar files for every day with exactly same scripts, and the one for yesterday works fine. I created MWE below. So, when I run it I can get the alerts for the first 2 messages, but not the 3rd one.
function test_script_hanging() {
var ui = SpreadsheetApp.getUi();
ui.alert("before getting files by name");
var getFilefile = DriveApp.getFilesByName("file");
ui.alert("after getting files by name");
var getID = getFilefile.next().getId();
ui.alert("after getting Id");
}
In some situations I notice an error message saying something like "Authorization is needed to perform this action" on the line where the .next() function is being called. I tried to revoke authorization of the file and give authorization again, but that didn't help. I tried to give full access to a given script, but couldn't google the way to do it.
Maybe I can add some more functions in my script to require full access during authorization, and maybe that will help to run my main function.
My questions are:
Why the script hangs?
How to fix this?
Can such kind of things (randomly and without any notice) happen in a free version of Google account?
This works for me:
var fldr = DriveApp.getFolderById(folderID)
var file = fldr.getFilesByName(filename);
while(file.hasNext())
{
var fi = file.next();
if(fi.getName() == filename)
{
var id=fi.getId();
}
}

Getting "We're sorry, a server error occurred. Please wait a bit and try again." But only on one sheet

So I have (what I assume is) a fairly long script to automate giving permissions in Google Sheets. To make it work, I have to first remove all the editors, otherwise Google just puts them in every category. I can't figure out how to stop that, short of removing them completely.
In my test file, I am the owner. Though I assume I need to add something that will add the script runner's account as an editor, just in case they are not. (edited to add: Apparently you can not remove yourself as editor, so even if you are not the owner, you can still run the rest of the script. Thank you, google! EDITED AGAIN: THAT IS A FILTHY LIE. I wish I had linked to the person who said this, because they are WRONG. You can remove yourself, I'm now waiting for the owner to add me back in. 9__6)
So I'm using this:
//removes all Editors
var SpreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var editors = SpreadSheet.getEditors();
for (var i = 0; i < editors.length; i++) {
SpreadSheet.removeEditor(editors[i]);
};
Which has been working, in this exact file, every time I test it. Yesterday, however, I got this error:
"We're sorry, a server error occurred. Please wait a bit and try
again."
referencing this line specifically:
var editors = SpreadSheet.getEditors();
But it works in the other test sheets I've made. I'm worried that it is just going to randomly not work when I deploy it on the floor, and I will have no idea why, or how to fix it.
Is there a better way to accomplish this? These sheets are live already, and have been shared with tonnes of people, so I need to either remove their edit permissions or switch their edit type to 'view'.
(I know you can do it for folders, but I would like it specifically for a file, since I am ultimately not the one who owns these files and who knows how they have been organised.)
Thank you for any help!
....
October 23rd, 2016 - It's happening again, on multiple different sheets. I commented everything out, and it is definitely this bit that is causing problems:
//removes all Editors
var SpreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var editors = SpreadSheet.getEditors();
for (var i = 0; i < editors.length; i++) {
SpreadSheet.removeEditor(editors[i]);
};
The getEditors is too much, man. Is there another way to do this? Is there another way to remove editors, or set them to 'view only' and then back to 'edit' when I'm done?
(If google would just put only the emails in each protection range as I've defined it instead of everyone, I would not have this problem. But they will not, and I have to remove everyone for this script to work.)
I have already looked at a lot of the linked answers, and they didn't seem to reply. Is getEditors too heavy to use reliably?
I am really not a scripter, and could use any links or guidance anyone could give.
I also can't seem to unaccept my own answer as an answer...
edited 11/14/2016 - Problem persists. The linked answer talks about using the "string replace function", and how changing that made the script work. I am not using that. The rest of my script is a repeat of this type of thing:
//Sheet1
var sh3 = ss.getSheetByName("Sheet1");
var protection = sh3.protect().setDescription('Sheet1 - Wizards'); //protects whole sheet
protection.addEditors(['wizard1#test.com',
'wizard2#test.com',
'wizard3#test.com']);
//adds email addresses to WIZARD range
var unprotected = sh3.getRange('A10:T');
protection.setUnprotectedRanges([sh3.getRange("B3:B3"),
sh3.getRange("C1"),
sh3.getRange("B72:B72"),
sh3.getRange("C2:K8"),
sh3.getRange("A10:T70"),
sh3.getRange("A75:Q")]);
//unprotects everything but frozen header. (unprotects the Sheet1 Legend too.)
var range = sh3.getRange('C2:K8'); //selects the range
var protection = range.protect().setDescription('Sheet1 - Legend'); //names the range
var me = Session.getEffectiveUser();
protection.addEditors(['wizard1#test.com',
'wizard2#test.com',
'wizard3#test.com'
'supervisor1#test.com’]);
//put Sheet1 supervisor emails here
var range = sh3.getRange('C1'); //selects the range
var protection = range.protect().setDescription('Sheet1 - Part Number'); //names the range
var me = Session.getEffectiveUser();
protection.addEditors(['wizard1#test.com',
'wizard2#test.com',
'wizard3#test.com'
'supervisor1#test.com’]);
//put Sheet1 supervisor emails here
var range = sh3.getRange('A10:T38'); //selects the range
var protection = range.protect().setDescription('Sheet1 - worker 1'); //names the range
var me = Session.getEffectiveUser();
protection.addEditors(['wizard1#test.com',
'wizard2#test.com',
'wizard3#test.com',
'lead1#test.com’,
'worker1#test.com',
'worker2#test.com']);
//put emails here - Sheet1 worker level
var range = sh3.getRange('A43:Q'); //selects the range
var protection = range.protect().setDescription('Sheet1 - Artists 2'); //names the range`
var me = Session.getEffectiveUser();
protection.addEditors(['wizard1#test.com',
'wizard2#test.com',
'wizard3#test.com'
'lead1#test.com’
'worker1#test.com',
'worker2#test.com']);
//put emails here - Sheet1 worker level
... Omg the spacing is so off, please ignore that and any commas I might have missed going through. I needed to quickly anonymise this so I can post it. The actual code is spaced right, and does have all the proper commas.
So what am I doing wrong??? Why is google freaking out over the getEditors() bit, and why only in certain sheets??
I saw somewhere else that this is just a catch-all error for "google has no idea wth just happened, but it didn't work. Try again later, and maybe it will work? Fingers crossed????"
Which is frustrating AS HECK because this is not a fancy function at all.
November 29th, 2016: Had a few spare minutes on my hands today, so I thought I'd try this script again. Still didn't work.
But oh my god I think I've cracked it! It's to do with the sharing settings! When the file was originally created, the 'anyone with a link' was selected as the option for sharing.
Well, I thought that didn't give enough security, so I switched my template to 'only specific people'. I then manually removed everyone, thinking maybe this would work.
Ran it again, it worked.
Tried it again, without manually removing, hoping that just changing the sharing settings would work. IT DID!!! So I went to fix the one far down the pipeline that was sitting there with no protections.
Turns OUT that you CAN remove yourself through scripting, even though I had read somewhere that google would not do that. So, since I am not the owner of the sheet, I am now locked out. Which will be another problem, and another question.
But as soon as I get this licked, or get the actual owner to run the script, I will update if this has actually solved it.
I will be so much happier when this works!
Posting an answer because my problem has disappeared? I didn't change anything, but I tried it this morning and it is working. Same sheet, same code, no server error.
This exact same code ran on different copies of this sheet (of which I was also the owner) at the same time as this stupid server error popped up on one, so I really don't know what happened.
I will just pray to the Google Gods and hope that nothing goes wrong. (Best plan, y/y?)
Thank you to Rubén and noogui for their input.
Had the same thing happen to me. Had this Gscript that i couldnt get to run for the life of me. Restarted computer. Signed out of everything. Reuploaded the script. Went to bed. Next morning everything worked fine.
I had a similar problem, but here is what I found ... basically I was linking to a library that was either removed or I lost permissions to. Since I wasn't using this particular library, I removed the library and now all my sheets work again.