Unable to Pull Parent Folder Name Using getParents - google-apps-script

I am trying to get the name of the Parent Folder for a spreadsheet that is determined by url and then place the name in a specified cell. Debugging the script below tells me "TypeError: Cannot find function getParents in object Spreadsheet." I have tried every tweak I can think of and read multiple similar articles that may answer my question, but I am unable to understand them. (Forgive the newbie?) Can somebody tell me what I am doing wrong?
function getParent(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("VALUES");
var ll = s.getRange("B11");
var url = ll.getValue();
var driveFile = SpreadsheetApp.openByUrl(url);
var parentFolder = driveFile.getParents();
while (parentFolder.hasNext()) {
var folder = parentFolder.next();
var title = folder.getName();
}
s.getRange("B5").setValue(title);
}

It seems like this code has two small issues which we'll fix to get you up and running on this.
If possible, it is generally a better practice to work with document
IDs rather than URLs. Also, for a reason I'm not aware of, DriveApp
does not have a getFileByURL method. So I have changed your "url" variable for "fileId", and changed the contents of cell B11 to the Id of the file, which is part of the URL itself.
In order to return a Drive File, you should call getFileByID() not on your Spreadsheet itself, but on the DriveApp service.
I've tested the following code and I believe it does what you expect:
function getParent(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("VALUES");
var ll = s.getRange("B11");
var fileId = ll.getValue();
var driveFile = DriveApp.getFileById(fileId);
var parentFolder = driveFile.getParents();
while (parentFolder.hasNext()) {
var folder = parentFolder.next();
var title = folder.getName();
}
s.getRange("B5").setValue(title);
}

Try this:
function getParent(){
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName("VALUES");
var url=sh.getRange("B11").getValue();
var file=DriveApp.getFileById(url.split('/')[5]);//gets the id out of the url
var parentFolder=file.getParents();
while (parentFolder.hasNext()) {
var folder = parentFolder.next();
var title = folder.getName();
}
sh.getRange("B5").setValue(title);
}

Related

Is there a way to copy a specific sheet from one workbook to a specific (and different) folder as its own stand alone sheet in google?

I am not a developer or coder, just trying to learn and automate tasks*. This is what I have so far:
function saveAsSpreadsheet() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[6];
var destFolder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxx");
DriveApp.getFileById(sheet.getSheetId()).makeCopy("desired file name", destFolder);
} //END function saveAsSpreadsheet
I get the error "Exception: Unexpected error while getting the method or property getFileById on object DriveApp."
Any tweaks that might make this work?
Issues:
You are trying to use the sheet id instead of spreadsheet id in DriveApp.getFileById(file id).
Using makeCopy(name, destination) will copy the content of the whole spreadsheet.
Try this:
function saveAsSpreadsheet() {
var folderId = "id";
var fileName = "new File";
var file = Drive.Files.insert({title: fileName, mimeType: MimeType.GOOGLE_SHEETS, parents: [{id: folderId}]});
var newFile = SpreadsheetApp.openById(file.id);
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[0];
var sheetName = sheet.getSheetName();
sheet.copyTo(newFile).setName(sheetName);
}
Note: Make sure to add Drive API to the project Services. See how to add Services in Apps Script.
Example:
Source file:
Destination:
Reference:
Drive.Files.insert()

How to remove a parent from a file or folder in google app script

I have files with multiple parents. I want to extras and keep only ones I like. How to achieve this. Something similar to the statement illustrated in the code below
var parentCount=0;
var driveFile = DriveApp.getFileById(id);
var parentFolder = driveFile.getParents();
while (parentFolder.hasNext()) {
var folder = parentFolder.next();
parentCount++;
if(folder.getName()=="I don't want this")
driveFile.removeParentLocation(folder) //Not a legal Method. needs workaround
}
Its easy to do from the web interface. see the x button next to locations.
Answered in comments above
var parentCount=0;
var driveFile = DriveApp.getFileById(id);
var parentFolder = driveFile.getParents();
while (parentFolder.hasNext()) {
var folder = parentFolder.next();
parentCount++;
if(folder.getName()=="I don't want this")
driveFile.removeParentLocation(folder)
}
Editor Comment: Note first comment above from #tanaike folder.removeFile(driveFile)

How to fix error - Invalid argument: file.contentType, when creating new Google Sheet

I am trying to create a new Google Sheet in a created folder, but am having issues with the content Type.
I have searched for this error but haven't found anything. Most searches come up with a MimeType error, but I don't think that's the issue. Below is the code I'm using:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var newFolder = DriveApp.getFolderById("MyID").createFolder("New Folder");
newFolder.createFile("myFileName",ss,MimeType.GOOGLE_DOCS);
Whenever I run this in my spreadsheet, I get the following error:
Invalid argument: file.contentType (line 3, file "Code")
I have tried using "" for the content for createFile.
How about following sample? I cannot use MimeType of GOOGLE_SHEETS and GOOGLE_DOCS, too. I don't know why. So I propose use of SpreadsheetApp.create(). The flow is as follows.
Create spreadsheet using SpreadsheetApp.create().
Add destination folder information to the spreadsheet.
Remove original folder information from the spreadsheet.
By this, you can create a spreadsheet to a folder you want.
Script:
var sheetfile = "myFileName";
var destfolder = "MyID";
var sheet = SpreadsheetApp.create(sheetfile);
var file = DriveApp.getFileById(sheet.getId());
var destfolder = DriveApp.getFolderById(destfolder).addFile(file);
var docfile = file.getParents().next().removeFile(file);
Updated: November 25, 2020
At July 27, 2020, the method of moveTo(destination) was added. And, the methods of addFile and removeFile will be deprecated. Ref So, when the method of moveTo(destination) is used for above script, it becomes as follows.
var sheetfile = "myFileName";
var destfolder = "MyID";
var sheet = SpreadsheetApp.create(sheetfile);
var file = DriveApp.getFileById(sheet.getId());
var destfolder = DriveApp.getFolderById(destfolder);
var docfile = file.moveTo(destfolder);
When the method of Files: insert of Drive API is used, the following script can be also used. Ref
var sheetfile = "myFileName";
var destfolder = "MyID";
Drive.Files.insert({title: sheetfile, mimeType: MimeType.GOOGLE_SHEETS, parents: [{id: destfolder}]});
this methode work with me
function myFunction() {
var sheetfile = "myfilename";
var destfolder = "MYFOLDER";
var sheet = SpreadsheetApp.create(sheetfile);
var file = DriveApp.getFileById(sheet.getId());
var destfolder = DriveApp.getFoldersByName(destfolder).next();
var docfile = file.moveTo(destfolder);
}
without next(); it not working for me
I faced the same issue and instead of trying to create a file on the fly, I thought of having a cleaner solution where by I am keeping one empty spreadsheet (Just create a spreadsheet in the drive and name as "Template") as a template to make copies out of.
var templateFileId = "asfashfkhsfkhfkhkashf"; //This is something you have to define as a constant
var destinationFolderId = "sdfashfkhaskf"
var newSpreadsheet = DriveApp.getFileById(templateFileId).makeCopy("NewSpreadsheet", destinationFolderId);

Google docs script create a file in a folder

I wrote a code to create a new file this file I put a page of my spreadsheet after I move it to another folder, the problem is on the move it. I've tried to makecopy function and addtofolder but neither worked all returned an error.
this is my code:
function pasta(){
var fonte = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var root = DocsList.getRootFolder()
var base = DriveApp.getFoldersByName('Violino').next();
var pasta1 = base.createFolder('Subfolder2');
var destino = SpreadsheetApp.create("teste");
var destinoF = DocsList.getFileById(destino.getId());
fonte.copyTo(destino);
destinoF.makeCopy("x",pasta1);
destinoF.removeFromFolder(root);
//Browser.msgBox();
}
I corrected the problem by adding this line
var pasta2 = DocsList.getFolderById(pasta1.getId());
was a problem types, even both folder1 and folder2 varying types having the same name, they belong to different classes
My corrected and running code looked like this:
function pasta(){
var fonte = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var root = DocsList.getRootFolder()
var base = DriveApp.getFoldersByName('Violino').next();
var pasta1 = base.createFolder('Subfolder2');
var pasta2 = DocsList.getFolderById(pasta1.getId());
var destino = SpreadsheetApp.create("teste");
var destinoF = DocsList.getFileById(destino.getId());
fonte.copyTo(destino);
destinoF.addToFolder(pasta2);
destinoF.removeFromFolder(root);
}

Google script Can't get SheetID to return value

I'm trying to get the following code, what am I missing? Bottom line, I need to move or create the NEW spreadsheet in the folder. But it seems I need an ID for that, which I can seem to pull.
Thanks!
Rudy
var ss =SpreadsheetApp.create('Credit Card Issues with EZ-Pay')
Logger.log('CREATING FILE.');
//var folder = DocsList.getFolder("EZ-Pay Reports");
//var sheet = ss.getSheetByName('Sheet1');
var sheet = ss.getSheets()[0];
Logger.log(ss.getSheetId('Sheet1'));
var ssID = ss.getSheetId('Sheet1');
DocsList.getFileById(ssID).addToFolder(DocsList.getFolder("Credit Card Issues with EZ-Pay/EZ-Pay Reports"));
code is much simpler :
function createInFolder(){
var ss =SpreadsheetApp.create('Credit Card Issues with EZ-Pay')
DocsList.getFileById(ss.getId()).addToFolder(DocsList.getFolder("Credit Card Issues with EZ-Pay/EZ-Pay Reports"));
DocsList.getFileById(ss.getId()).removeFromFolder(DocsList.getRootFolder());
}
The DocsList service has been deprecated. Use the Drive Service instead:
var ss = SpreadsheetApp.create("Credit Card Issues with EZ-Pay");
var id = ss.getId();
var file = DriveApp.getFileById(id);
DriveApp.addFile(file); // adds to the root folder
You can also add the file to a folder other than the root:
var folder = DriveApp.getFolderbyId(id);
folder.addFile(file);
If you don't know the id of the folder:
var folderIter = DriveApp.getFoldersByName("My Folder");
while (folderIter.hasNext()) { // returns true if the collection has a next item
var folder = folderIter.next(); // throws an exception if there's no next item
}
folder.addFile(file);