Add Spreadsheet file in a folder - javascript

Anyone know how create a Spreadsheet file in a specific folder on Google Drive?
I have already tried the answer from this link.
EDIT - Tried this answer :-D :
//"Move" file to folder-------------------------------//
var fileID = '12123123213321'
var folderID = '21321312312'
var file = DriveApp.getFileById(fileID).getName()
var folder = DriveApp.getFolderById(folderID)
var newFile = file.makeCopy(file, folder)
//Remove file from root folder--------------------------------//
DriveApp.getFileById(fileID).setTrashed(true)
But the "correct answer" gives me the follow error "Uncaught TypeError: Cannot find function makeCopy in object Spreadsheet."
I saw other answers but none of them work. I have already tried enable "Drive API" from "Advanced Google Services", but it's kind of complicate to work with.
UPDATE!
Just to explain, my problem is that I was creating the Spreadsheet
var sheetId = SpreadsheetApp.create("filename").getId();
And then trying to makeCopy, or addFile in a folder. Something like that:
<someFolder>.addFile(sheet);
What I detect is that to work I have to get a File type, not a string like after. So I change to the code;
var sheetId = SpreadsheetApp.create("filename").getId();
var file = DriveApp.getFileById(sheet);
<someFolder>.addFile(file);

Instead of making a copy, why don't you just move it?
var file = DriveApp.getFileById(fileID),
folder = DriveApp.getFolderById(folderID),
parents = file.getParents();
folder.addFile(file);
while( parents.hasNext() )
parents.next().removeFile(file);

Related

why my app script code makes copy of the spreadsheet to the root directory of google drive in addition to the specific directory?

i have a spreadsheet and i save this sheet to a particular folder with the code below. if a file with the same name exists in this folder, it deletes the old one and then adds the new one. it was working well. but a few weeks ago it has started also to make copy to the root directory of google drive. it makes two copies of the sheet. one is to the directory i give and the other one (which is not wanted)is to the root directory.
i have been looking and looking but can't see the reason. can anyone help me about what is wrong with my code?
function copyToFolder_trigger(){
copyToFolder(folderID_ARSIV, sheet_Parklar);
}
function copyToFolder(folderid, spreadsheet){
var sheet = SpreadsheetApp.openById(spreadsheet);
var destFolder = DriveApp.getFolderById(folderid);
var date = getDailyDate();
if(isinFolder(folderid, date)){
var fileIterator = destFolder.getFilesByName(date);
while(fileIterator.hasNext()){
var file = fileIterator.next();
destFolder.removeFile(file);
}
}
DriveApp.getFileById(sheet.getId()).makeCopy(date, destFolder);
}
function isinFolder(folderId, filename){
var folder = DriveApp.getFolderById(folderId);
var files = folder.getFiles();
var res = false;
while (files.hasNext()) {
var file = files.next();
if(file == filename){
res = true;
break;
}
}
return res;
}
archive folder
root folder
Frankly, I have no idea what's going on. But when I changed the line:
destFolder.removeFile(file);
to:
file.setTrashed(true);
It started work well. For me. For now...

Finding and changing Google file owners

I want to be able to check a given folder that I've shared, for files that someone else put into the folder, and then take ownership of those files. I've tried this:
function changeUser() {
var folderID = "<folder ID here>"
var newUser = "<my email address>"
var folder = DriveApp.getFolderById(folderID);
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
if(file.getOwner() <> "DriveUser") {
file.setOwner(newUser);
}
}
}
I'm using "DriveUser" because that's the user it says it is, when I run Logger.log(file.getOwner()); But I'm certainly not sure that's right.
When I try to run this, it tells me that there's an unexpected token '>' in the IF statement line. Hey - I'm new to this. In any case, any suggestions as to how I could make this work?
I believe there are two issues with your code:
Javascript uses != for 'not equals' rather than the <> used in some other languages.
The DriveUser you are seeing logged is not a string value, but rather an instance of the User class, documented here. To get a meaningful identifier of the user, you need to call this class's method .getEmail(). You can then compare that to your own email address.
So the updated code looks like this:
var folderID = "..."
var newUser = "(an email address)"
var folder = DriveApp.getFolderById(folderID);
var files = folder.getFiles();
console.log(folder.getOwner())
while (files.hasNext()) {
var file = files.next();
if(file.getOwner().getEmail() != newUser) {
file.setOwner(newUser);
}
}
But there's a third issue you'll encounter: This will only work if you are transferring ownership from you to another user (i.e. you own the files and newUser is not your email address). Apps Script runs scripts on your behalf, which means it will not execute an action that you wouldn't have permission to do manually--only the owner of a file can transfer that ownership to another user. If you run the script on files you don't own, you'll get a vaguely worded error Action not allowed.

Google picker make a copy when uploading

I have replicated the google file picker in a web app.
My question is how would I tell the google picker to make a copy of the file when uploading it to google drive ?
Any help would be much appreciated.
I realised that google picker could not do what I needed so Google App Script to the rescue.
Firstly you need to create a new google spreadsheet
Under "Tools->Script Editor" add the following code
Thought trial an error I came up with the following.
function copyFiles() {
var dApp = DriveApp; // Get the drive app
var folderIter = dApp.getFoldersByName('parentFolder'); //Get folder my id
var folder = folderIter.next(); // Get the first folder
var fileIter = folder.getFiles(); // File iterator
var storageFolder = folder.getFoldersByName('childFolder').next(); // Get target folder
var subFolderIter = storageFolder.getFiles(); // sub folder File iterator
while(fileIter.hasNext()) {
var file = fileIter.next(); // Get the current File
var fileName = file.getName();
// Check if the current file exists in a coped folder
// If false make a copy else do noting
// This check prevents duplicate, Becasue makeCopy generates uniques ID everytime
if(!storageFolder.getFilesByName(fileName).hasNext()) {
//Logger.log('Files does NOT exists');
file.makeCopy(storageFolder);
} else {
//Logger.log('Files does exists');
}
}
}
Hope this helps anyone who might need.
Note: You will need to set up triggers for the script to run when required

cannot find method copyTo error after creating new file in sheet

Would really appreciate your help here.
I'm creating a two step process where:
1. Create a new file named after a cell from the file to be copied from.
2. Copy the sheet to the newly created file.
I'm doing this because we will be creating unique files for several clients and I'd like to automate it.
Since I'm still new, I've been putting together code from various sources and modifying it to put what I want. However, this code creates a new file perfectly, but refuses to copy the content to the newly created file. I keep on getting a "cannot find method CopyTo error" and despite a ton of research and tweaking, I cannot get it to work. Help!?
function copy2() {
var folder=DriveApp.getFoldersByName("Dummy").next();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0,1];
var cellWithFileName = ss.getRange("A1");
var name = cellWithFileName.getValue();
var file=SpreadsheetApp.create(name);
var fileID = file.getId()
var copyFile=DriveApp.getFileById(fileID);
var destination = DriveApp.getFileById(fileID)
folder.addFile(copyFile);
DriveApp.getRootFolder().removeFile(copyFile);
ss.getSheetByName("Sheet1").copyTo(fileID);
}
Thanks
At copyTo(destination), destination is not file ID. It's Spreadsheet. So how about the following modification?
From :
ss.getSheetByName("Sheet1").copyTo(fileID);
To :
ss.getSheetByName("sheet1").copyTo(file);
Reference :
copyTo(spreadsheet)
If this didn't work, please tell me. I would like to modify.

I need to overwrite an existing Google Sheets file with an attached Script

I have a Google Sheets file with an attached Script. The script does a number of things, one is it makes a clone of it self using makeCopy. This portion works. Now I want to be able to keep the same cloned Google file name and same Google file ID and just update the content which includes a Spreadsheet and the associated Google script.
if (!fileFound){
var file = masterSSFile.makeCopy(reportFileName, RepFolder);
} else {
oldFile.setContent(masterSSFile.getBlob());
}
When I use makeCopy with the same file name it creates a second file with the same name but with a different file ID.
The else portion fails because .setContent argument seems to just accept text. The result is the word "Blob" in the oldFile, everything else is gone.
I have other scripts that update the contents of a existing spreadsheet by overriding the contents of the various sheets, but I also want the associated script to also be included in the updated file keeping the same file ID.
I found this....
Overwrite an Image File with Google Apps Script
and tried using
var masterSpreadsheetID = SpreadsheetApp.getActiveSpreadsheet().getId();
var masterSpreadsheetFile = DriveApp.getFileById(masterSpreadsheetID);
var oldFileID = oldFile.getId();
var oldFileName = oldFile.getName();
var newBlob = masterSpreadsheetFile.getBlob();
var file = {
title: oldFileName,
mimeType: 'application/vnd.google-apps.spreadsheet'
};
var f = Drive.Files.update(file, oldFileID, newBlob);
I get error: "We're sorry, a server error occurred. Please wait a bit and try again. " on this line: "Drive.Files.update(file, oldFileID, newBlob);"
After reading this:
https://github.com/google/google-api-nodejs-client/issues/495
it looks like Drive.Files.update(), does not support bound scripts.

Categories

Resources