Zac Henson Zac Henson - 1 month ago 19
Javascript Question

How to I get the ID of a Gsheet file by using its name in google apps script

I am pulling my hair out. I have the following code and am stuck trying to figure out how to get the id of a gsheet file using its name. My goal is to look up a file by its name, then get the id, then grab a range from that file and output it into the active sheet



function onOpen() {
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('Master Analysis Functions')
.addItem('Update Sheet', 'updateSheet')
.addSeparator()
.addSubMenu(ui.createMenu('Test Menu')
.addItem('Test Function', 'menuItem2'))
.addToUi();
}

function updateSheet() {

/* Top Level Google Drive Folder ID & General Settings */
var TopDrivefolderId = "0B2rN5b8fW77ldXZXOXFLZGlSamc";
var BaseNumberOfFilesInFolder = 5;
var filesInFolderBeforeTemplate = 4;
/* End General Settings */

var parentFolder = DriveApp.getFolderById(TopDrivefolderId);
var childFolders = parentFolder.getFolders();

while(childFolders.hasNext()) {
var child = childFolders.next();
// Logger.log(child.getName() + " |Drive_ID: " + child.getId());
var folderId = child.getId();
// **the folderId Variable is also the folder ID,
// hence they are used interchangeably **

var myFolder = DriveApp.getFolderById(folderId);

/* Name of combined Spreadsheet*/
//var tradeName = Drive App.getFolderById(folderId).getName();
var tradeName = DriveApp.getFolderById(folderId).getName();

/* Get all spreadsheets that resided on that folder */
var spreadSheets = myFolder.getFilesByType("application/vnd.google-apps.spreadsheet");
var spreadSheetName = myFolder.getName();

/* Check if a file needs to be created or if one already exists*/
var theFolder = DriveApp.getFolderById(folderId);
var files = theFolder.getFiles();
var fname = theFolder.getName();

var cnt = 0;
var file;

/* Check the quantity of files in a folder to see if you need to combine the sheets and create a file*/
while (files.hasNext()) {
cnt++;
file = files.next();
//Logger.log(file.getName());
if (cnt > BaseNumberOfFilesInFolder) {
Logger.log("File already exists")
break;
}
;
};

// If a file needs to be created this checks it and creates it
Logger.log(cnt + " is the number of files '"+ tradeName+ "' has.");
if (cnt > BaseNumberOfFilesInFolder){
Logger.log("The Data for " +tradeName+ " is already in the sheet.")
} else if(cnt == filesInFolderBeforeTemplate){
Logger.log("ERROR: You need to run the template adder script to add the template to " +tradeName)
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow(["ERROR: You need to run the template adder script to add the template to " +tradeName]);
continue;
}else{
/* Create the new spreadsheet to verify this trade is in the master sheet */
var newSpreadSheet = SpreadsheetApp.create("Added to Master");

var spreadSheet = DriveApp.getId(tradeName);
Logger.log(spreadSheet);


Logger.log(tradeName + " It has been logged");

var sheetCurrent = SpreadsheetApp.getActiveSheet();
//sheetCurrent.appendRow([tradeName,data]);


/* In order to move the file to the folder we want and because
google considers the SpreadSheet a Google Spreadsheet
instead of a file, we have to convert the SpreadSheet to a file in
order to move it.Thats what the next 2 lines of code do.*/
var getNewSSid = newSpreadSheet.getId();
var SStoGFile = DriveApp.getFileById(getNewSSid);
/* Actually moving the file*/
DriveApp.getFolderById(folderId).addFile(SStoGFile);

/* Deleting the duplicate file that was created in the process*/
var rootFolder = DriveApp.getRootFolder();
DriveApp.getRootFolder().removeFile(SStoGFile);

}
getSubFolders(child);

};

SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.alert('All Trades updated! Please check the sheet for errors.');

};

function getSubFolders(parent) {
parent = parent.getId();
var childFolder = DriveApp.getFolderById(parent).getFolders();
while(childFolder.hasNext()) {
var child = childFolder.next();
Logger.log(child.getName());
getSubFolders(child);
}
return;
}
/* End iterate through Sub Folders */



function menuItem2() {

var files = DriveApp.searchFiles("tradeName");
Logger.log(files,tradeName);
var spreadsheet = SpreadsheetApp.open(tradeName);
var sheet = spreadsheet.getSheets()[0];
Logger.log(sheet.getName());



SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.alert('You clicked the second menu item!');
};





.

Answer

Your code is a bit too messy for me to actually find where exactly your issue is and what you try to accomplish with it, however based on your question itself, what you need to do is

fileList = DriveApp.getFilesByName('This_name')
while (fileList.hasNext()) {
  Logger.log(fileList.next().getId())
}

This will log each file ID that matches that name. The spreadsheet service can only open by ID, so you need to use the drive service (what I mean is that the google-spreadsheet tags do not really fit here as this should only be handled as a drive thing).

If you want to get the file fro the spreadsheet service you can always do SpreadsheetApp.open(fileList.next()) to directly open it from the file object