Get spreadsheet id or url from the spreadsheets name - javascript

I have multiple named spreadsheets in a folder on google drive. How would I get their id or url by passing one of the names to a function?
I can get the file using DriveApp, but I dont know how to get the id from that.
function getFile(name)
{
var folder = DriveApp.getFolderById('id');
var file = folder.getFilesByName(name);
//get file id
}
Is there a way to get the id or url using DriveApp or SpreadsheetApp?

The command folder.getFilesByName(name);potentially retrieve more than one file (has it's name say it- getFiles) so it give you a file iterator that you need to parse with a while loop.
If you are absolutely sure that there is at least one file with that has the name, you can avoid the loop with a little dirty code like this:
var file = folder.getFilesByName(name).next();
and then retrieve the id with:
var id = file.getId()
-- EDIT:
If you are not sure to retrieve a file (You don't know if it exist or has the right name....) you'll need to check the result of the file iterator.
Instead of writing :
var file = folder.getFilesByName(name);
prefer to write:
var files = folder.getFilesByName(name); // you could have zero or more than one file
And then you can do a while loop if you believe there is more than one file with that name:
var out = [];
while(files.hasNext()) {
var file = files.next();
out.push(file.getId());
Logger.log(file.getId());
}
return out;
or if there is only one or zero file a simple if will do the job:
if (files.hasNext()) {
var file = files.next();
Logger.log(file.getId());
return file.getIt(); // eventually
}
else {
Logger.log("there is no file with that name");
return "no id"; // eventually
}

Related

Error of duplication in root drive with google script while copying a file from one folder to another

So, I'm trying to copy a file which is updated automatically in my computer in a folder.
Thing is that every time the script runs, it copies the file in the selected folder but also creates a duplication in the root folder despite root isn't referred in the whole script
function moveFiles() {
var olderfiles = DriveApp.getFolderById("idfromdestinyfolder").getFiles();
while (olderfiles.hasNext()) {
var olderfile = olderfiles.next();
var pull = DriveApp.getFolderById("idfromdestinyfolder");
pull.removeFile(olderfile)
}
var files = DriveApp.getFolderById("idfromstartingfolder").getFiles();
while (files.hasNext()) {
var file = files.next();
var destination = DriveApp.getFolderById("idfromdestinyfolder");
file.makeCopy("nameofthefile",destination);
}
}
The first part olderfiles checks if a file exist in the destiny, and if exists, it removes it.
The second part copies the file from the starting folder to destination.
Thing is, every time it runs, it creates a copy in root which should not happen.
Is the first time I'm using google script
From the question
... it copies the file in the selected folder but also creates a duplication in the root folder despite root isn't referred in the whole script
The problem might be caused by the use of Class Folder.removeFile(child). Pleaser bear in mind that it's a deprecated method, the docs instructs to use Folder.moveTo(destination) instead.
If you are looking to send the file to the trash, then use Class File.setTrashed(true)
Related
Permanently delete file from google drive
Delete or Trash specific file in Drive
Try this makeCopy()
function makeCopy() {
var folderid = "folderid";
var fileid = "fileid";
var folder = Drive.Files.get(folderid, { "supportsAllDrives": true });
var newFile = { "fileId": fileid, "parents": [folder] };
var args = { "resource": { "parents": [folder], "title": "new Title" }, "supportsAllDrives": true };
Drive.Files.copy(newFile, fileid, args);
}

Creating XLSX (Excel) spreadsheet (or Zip files) in Javacript Server Side

I'm looking for some guidance or ideas on how to create a proper formatted Excel (XLSX) spreadsheet using Javascript Serverside.
I've found multiple sites/libraries (such as SheetJS) which can create the file, but depend on web functions (ie. blobs and the like).
Alternatively a JS library which similarly can create a zip file without using blobs/web functions (ie. i can create the XML files structured within the XLSX file/zip but cannot compress server side.
The reason for this is the need to export these files on Server Side scripts within NetSuite/SuiteScript... so far I've come up empty.
You may be able to get what you are looking for using the 'N/file' SuiteScript module. Create a file using file.Type.EXCEL
Here's a scheduled script code sample that will take saved search results and create an excel file that is saved to the file cabinet. You can reference Suite Answer Id 93557. Also the "file.Type" enum does allow for the type Zip, reference Suite Answer Id 43530
define(['N/search','N/file'], function(search, file) {
function execute(scriptContext){
//Load saved search
var mySearch = search.load({id: '47'});
//Run saved search
var mySearchResultSet = mySearch.run();
//Headers of CSV File separated by commas and ends with a new line (\r\n)
var csvFile = 'Internal ID,Item Name,Average Cost\r\n';
//Iterate through each result
mySearchResultSet.each(iterator);
function iterator(resultObject){
//get values
var internalid = resultObject.getValue(mySearch.columns[0])
var itemid = resultObject.getValue(mySearch.columns[1])
var formulacolumn = resultObject.getValue(mySearch.columns[2])
//Add each result as a new line on CSV
csvFile += internalid+','+itemid+','+formulacolumn+'\r\n'
return true;
}
//Variable for datetime
var date = new Date();
//Creation of file
var fileObj = file.create({
name: 'Saved Search Result - ' + date.toLocaleDateString() +'.xlsx',
fileType: file.Type.EXCEL,
contents: csvFile,
description: 'This is a CSV file.',
encoding: file.Encoding.UTF8,
folder: 123
});
//Save the CSV file
var fileId = fileObj.save();
}
return {
execute: execute
};
});

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.

In Google Apps Script, how can I have a single function iterate over a data structure that keeps track of many different pairs of variables?

I'm trying to figure out a way for a single function to iterate over many different pairs of variables.
Because I'm running into limits with 45 different scripts running during the same hour, I'm instead trying to write one script that could iterate over a data structure that keeps track of two different variables at a time, in particular, pairs of folder IDs for particular Google Drive folders.
I have a function moveFiles:
function moveFiles() {
var source_folder = DriveApp.getFolderById("xxxxxxxxxxSomeParticularSourceFolderxxxxxxxxxx")
var dest_folder = DriveApp.getFolderById("xxxxxxxxxxSomeParticularDestinationFolderxxxxxxxxxx")
var files = source_folder.getFiles();
while (files.hasNext()) {
var file = files.next();
dest_folder.addFile(file);
source_folder.removeFile(file);
}
}
What data structure could I add to this script to keep track of different pairs of folder IDs for particular source and destination folders, and how can I add the whole moveFiles function into a for loop to make it all work?
Try this:
function moveFiles() {
var fldrIdA=[{src:'id',des:'id'},...];
for(var i=0;i<fldrIdA.length;i++) {
var srcfldr = DriveApp.getFolderById(fldrIdA[i].src)
var desfldr = DriveApp.getFolderById(fldrIdA[i].des)
var files = srcfldr.getFiles();
while (files.hasNext()) {
var file = files.next();
desfldr.addFile(file);
srcfldr.removeFile(file);
}
}
}

Read a file with dynamic file name in JavaScript

Is it possible to read a file with file name as Sometext_ddmmyy.xls in JavaScript?
The file name changes daily but date ddmmyy are random date in that week or previous.
But the path of the file never changes.
Can you help to code in JavaScript to read the file?
Code:
var filename = /^path\\sometext_.*.xls$/;
....
var neobjectexcel = new ActiveXObject("Excel.Application");
var sheet = neojectexcel.Workbooks.Open(filename).ActiveSheet;
...
I used Regex but I am getting "Sorry, we couldn't find /^path\sometext_.*.xls$/ Is it possible it was moved, renamed or deleted?" Error!
Even the regex /^path\\sometext_\d\d\d\d\d\d.xls$/ is giving the same error.
Also tried \d+ instead of \d\d\d\d\d\d does not works.
Please help!
Update: The file will be in a folder on a server along with other files of similar names like sometext_ddmmyy.xls randomtext_ddmmyy.xls randomothertext_ddmmyy.xls and will be accessed with script on the same server.
With FileSystemObject you can filter a filename with a RegExp and find the latest filtered file added to a folder like so:
function getLatestFile (path, filter) {
var fileIO = new ActiveXObject('Scripting.FileSystemObject'),
folder = fileIO.GetFolder(path), // Get a folder object
files = new Enumerator(folder.files), // Create files collection
latest = 0,
file, date, isTargetFile, temp, target;
while (!files.atEnd()) { // Iterate files collection
file = files.item(); // Get a file from the collection
temp = new String(file); // Convert a file object to string
isTargetFile = filter.test(temp); // Filter the filename
date = new Date(file.DateCreated).getTime(); // Get the creation date of the file
if (isTargetFile && date > latest) { // Check if this file passed the filter and is newer than the previous filter-passed file
target = temp;
latest = date;
}
files.moveNext(); // Continue iteration
}
return target;
}
An example call for your case would be:
var filename = getLatestFile(path_to_folder, /sometext_\d{6}\.xls$/);
Arguments: path = the path to the folder where to search files. filter = a RegExp object (literal or constructed) to filter the filename. When creating the RegExp, note that the converted file object (temp) uses a backslash as a folder separator, though the RegExp can be created to filter the filename only. If the function returns undefined, none of the filenames has matched the RegExp.

Categories

Resources