migrate from DocsList to DriveApp - javascript

I'm new to google scripts and was able to manipulate some code to work for a project, but it will no longer work as a result of the following:
ReferenceError: "DocsList" is not defined.Dismiss
Here is the code I have:
function report() {
var folder = DocsList.getFolder("FOLDER NAME HERE");
var contents = folder.getFiles();
var file;
var data;
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clearContents();
sheet.appendRow(["URL", "Employer"]);
for (var i = 0; i < contents.length; i++) {
file = contents[i];
var qaDate,qaERName
if (file.getFileType()==DocsList.FileType.SPREADSHEET) {
var dataSheet = SpreadsheetApp.open(file).getSheetByName("data");
var configSheet = SpreadsheetApp.open(file).getSheetByName("Config");
I have a few references to DocsList, I've done some digging and cant figure out how to get something similar to getfolder

Let's start with the first line:
var folder = DocsList.getFolder("FOLDER NAME HERE");
If you go to the documentation, and look at all the methods for DriveApp that have anything to do with folders, you'll see four methods:
getFolderById(id)
getFolders()
getFoldersByName(name)
getRootFolder()
There is only one method that will get just one folder, getFolderById(id). If you are getting the same folder every time, and you can easily get the ID, then use that option. If that is not possible, then you can use getFoldersByName(name), but that gets multiple folders. Even though it gets multiple folders, you can easily get just the first folder.
var folders = DriveApp.getFoldersByName('Folder Name');
var folder = folders.next();
Logger.log('folder: ' + folder.getName());
So, start there, and make that change.

Related

Java Script to get/combine data from multiple Google Sheets that are stored in different folders (archives)

I am trying a script to scrape data form a given Sheetname and a given range into 1 main sheet. the problem in this case is that the Spreadsheets (with multiple sheets) are archived in different folders. so I have 1 main folder and in that folder I have archive folders for every year (2012-2022).
I have made script that is going through these folders and get the folder Id's that part is working.
I also have made a script to get the data from the sheet ("Rekenblad") and the range "A11:AY136". I think that also should work.
The part where I connect those 2 function is going wrong. What I would recieve is:
A main file (The script is inside the main file) with:
A sheet (blad1) with a list of all the information of the file
A sheet (blad2) with all data ranges combined. Every time I run this script the data needs to be cleared so I dont have doubles.
The most important is point 2. point 1 is just for me to check if all files are imported correctly and a link so I can easily check those files.
Script looks like this:
function listFolders(folder) {
var sheet = SpreadsheetApp.getActiveSheet().clearContents();
sheet.appendRow(["Name", "URL","ssId", "Type"]);
var folder = DriveApp.getFolderById("FOLDER_ID_PARENT_FOLDER");
var subfolders = folder.getFolders();
while (subfolders.hasNext()) {
//Logger.log(folder);
var name = subfolders.next();
while (subfolders.hasNext()) {
//Logger.log(folder);
var name = subfolders.next();
var files = name.getFiles();
var cnt = 0;
var file;
var ssID
var fileType
var combinedData = []
while (files.hasNext()) {
var file = files.next();
cnt++;
Logger.log(file);
Logger.log(cnt);
data = [
file.getName(),
file.getUrl(),
ssID = file.getId(),
fileType = file.getMimeType(),
];
sheet.appendRow(data);
if (fileType ==="application/vnd.google-apps.spreadsheet"){
ssID = files.getId();
data = GetData(ssID)
data = data.map(function(r){return r.concat([file.getName()]);});
combinedData = combinedData.concat(data);
}
}
var wss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Blad1") ;
ws.getRange("A2:AY").clearContent();
wss.getRange(2, 1, combinedData.length, combinedData[0].length).setValues(combinedData);
}
}
}
function GetData(ssID){
var aa = SpreadsheetApp.openById(ssID);
var wa = aa.getSheetByName("Rekenblad");
var info = wa.getRange("A11:AY136").getValues();
return info
}

I need 2 different buttons, to create new folder and create a new PDF in that folder

I've been struggling to build a specific weekly stock system reports. So to give you a basic overview, I have a mastersheet that I want to generate reports from, triggered by an UI button. The first step however is to create a folder for that week to place the PDF's in. I can create the folder, and I can generate the PDF in my root Google Drive folder, but I can't seem to move the PDF anywhere after that. I have attempted to use .moveTo() but I can't get that to work. Does anyone have any advise?
function onOpen(e)
{
SpreadsheetApp.getUi()
.createMenu('Physical')
.addItem('New folder','newFolder')
.addItem('Generate PDF','generatePDF')
.addToUi();
}
function newFolder(){
var today = new Date();
var week = Utilities.formatDate(today, "Europe/Amsterdam", "w"); //need to find a way to minus 1 for the current week
var spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId(); //time to create a new folder
var spreadsheetFile = DriveApp.getFileById(spreadsheetId);
var folderId = spreadsheetFile.getParents().next().getId();
var parFolder = DriveApp.getFolderById(folderId)
var destFolder = parFolder.createFolder('Week ' + week);
}
function generatePDF(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var speadsheetFile = ss.getId();
var file = DriveApp.getFileById(speadsheetFile);
var folderId = file.getParents().next().getId();
var pdf = DriveApp.createFile(ss.getBlob())
pdf.moveTo(folderId); //find way to move file either to destination folder or to parent folder
}
Description
These types of situations are hard to test because the circumstances are specific to the OP questioner. However, I believe this will work.
Using the PropertyService Script Properties, store the newly created folderId and then get that id from Script Properties to move the file.
A note of caution, I didn't check for the case if the week changes and a new folder is not created, the pdf will go to the previous week folder.
Regarding creating a button and linking a function to the button see this article Buttons in Google Sheets
Script
function newFolder(){
var today = new Date();
var week = Utilities.formatDate(today, "Europe/Amsterdam", "w"); //need to find a way to minus 1 for the current week
var spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId(); //time to create a new folder
var spreadsheetFile = DriveApp.getFileById(spreadsheetId);
var folderId = spreadsheetFile.getParents().next().getId();
var parFolder = DriveApp.getFolderById(folderId);
var folderName = 'Week '+week;
// check if folder already exists
var subFolders = parFolder.getFoldersByName(folderName);
var destFolder = null;
if( subFolders.hasNext() ) {
SpreadsheetApp.getUi().alert("Folder "+folderName+" already exists");
destFolder = subFolders.next();
}
else {
destFolder = parFolder.createFolder(folderName);
}
// store folder id to Script Properties
var props = PropertiesService.getScriptProperties();
props.setProperty("foldeId",destFolder.getId());
}
function generatePDF(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
// get folder id from Script Properties
var folderId = PropertiesService.getScriptProperties("folderId");
if( !folderId ) {
SpreadsheetApp.getUi().alert("Property folderId not found");
return;
}
var pdf = DriveApp.createFile(ss.getBlob())
pdf.moveTo(folderId); //find way to move file either to destination folder or to parent folder
}
Reference
SpreadsheetApp.getUi().alert()
PropetiesService

jQuery move local files to another directory

I would like to create a function which will count the files from a directory.
If there are 5 files, move the oldest file to another directory.
I found a code sample, but it is not working for my case.
var myFileList = Folder("C:/Test").getFiles();
var folderCount = GetFoldersCount(myFileList) ;
$.writeln(folderCount);
function GetFoldersCount(fileList) {
var folderCount = 0;
console.log(folderCount);
for (var i = 0; i < fileList.length; i++) {
var myFile = myFileList[i];
if (myFile instanceof Folder)
folderCount++;
}
return folderCount
}
I am getting the error "Folder" is not defined.
Its impossible directly access local files by JS for seccurity issue.
Another thing is that you can access files on drive over Ajax call and process
on response. Using Ajax you can send request what you want to do it on background.
You used example at InDesign forum. I dont know InDesign but I am not sure that it will work.
Otherwise look for documentation about HTML5 File API. Hope that you will find answer.
https://w3c.github.io/FileAPI/
some examples:
https://www.html5rocks.com/en/tutorials/file/dndfiles/
I found out the solution for this task, which works perfect for me.
I call the function with the initial directory:
moveErrorFiles('C:\\Folder1');
And below are the 2 simple functions I use.
function moveErrorFiles(fileDir) {
var fileSysObj, file, folder, fileCounter, currentFile;
var fileMumber = 0;
fileSysObj = new ActiveXObject("Scripting.FileSystemObject");
folder = fileSysObj.GetFolder(fileDir);
fileCounter = new Enumerator(folder.files);
for (; !fileCounter.atEnd(); fileCounter.moveNext()) {
currentFile = fileCounter.item();
fileMumber++;
if (fileMumber > 5) {
moveFile(currentFile);
}
}
} //function moveErrorFiles() ends here
function moveFile(fileToMove) {
var object = new ActiveXObject("Scripting.FileSystemObject");
var file = object.GetFile(fileToMove);
file.Move("C:\\Folder2\\");
console.log("File was moved successfully");
} //function moveFile() ends here

Delete all but x most resent files in a folder Google script

I have a folder where I store backup files and I want to keep only the 5 most recent files
All files are in a folder called New Project Backups
All files have New Project as part of their name
I found this here
Delete old files
How do I focus the Function to look in only the folder New Project Backups
Thanks
function myFunction() {
var file_iterator = DriveApp.getFiles();
var file_list = [];
while (file_iterator.hasNext()) {
var fl = file_iterator.next();
if (fl.getName().match("New Project"))
file_list.push(fl);
}
// Sort the files on date created
file_list = file_list.sort(function(fl1, fl2) {
return fl1.getDateCreated() < fl2.getDateCreated();
});
// Removing uneeded file
while (file_list.length > 5) {
var fl = file_list.pop();
// fl.setTrashed(true); // if you want it in the trash
// instead of fully removed.
DriveApp.removeFile(fl);
}
}
Using DriveApp.getFiles() will get you all files in the drive. you can fix that by replacing
var file_iterator = DriveApp.getFiles();
with
id = "0XrUxpDX-E8dpeE9EQmpYLeplOLB";
var folders = DriveApp.getFolderById(id);
var file_iterator = folders.getFiles();
the id is the folder id you want to work with, you can find it from the folder URL
Example,
Folder URL: https://drive.google.com/drive/u/1/folders/0XrUxpDX-E8dpeE9EQmpYLeplOLB
Folder ID: 0XrUxpDX-E8dpeE9EQmpYLeplOLB
enjoy ;)

Google Script: How to script an automatic import from a txt in my drive into spreadsheet?

I've never used Javascript before and i've been trying for ages to do this but with no luck, and I can't find any previous people trying.
I want to copy the text data straight from this txt document in my drive, it is possible to do this fine manually but I want it to be done daily automatically instead.
The text document;
Boxes Made,3
Target Percentage,34
Hourly Rate,2
If I import this into a spreadsheet with these settings its perfect;
Import Settings
And it imports like this;
After Import
Now I need to try and automate this so that a script imports it automatically.
The script I have so far doesn't work, please help.
Current script;
function AutoImporter (Source)
{
var Source = DriveApp.getFilesByName('DailyData.txt');
var TextContents = Source.copyText();
var Target = SpreadsheetApp.getActiveSheet();
Target.appendText(TextContents[1]);
}
--edit
Some guy just sent me a script that seems closer but still didn't work;
function autoCSV() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var s=ss.getActiveSheet();
var r=s.getActiveCell();
var id="DailyData.txt";//<<<<<enter the ID of the text file
var f3=DriveApp.getFileById(id);
var lst1=f3.getBlob().getDataAsString().split('\n').map(function(x) {return x.split(',')});
var ncols=1,i,lst2=[];
for (i in lst1) {if (lst1[i].length>ncols) ncols=lst1[i].length;}
for (i=0;i<ncols;i++) lst2.push('');
for (i in lst1) lst1[i]=lst1[i].concat(lst2.slice(0,lst2.length-lst1[i].length));
s.getRange(r.getRow(), r.getColumn(), lst1.length, ncols).setValues(lst1);
}
You may read text file from Google Drive this way:
'use strict'; // <- Always use strict mode.
function foo() {
var fileName = 'DailyData.txt';
var files = DriveApp.getFilesByName(fileName);
if (!files.hasNext()) {
throw new Error('No file with name:' + fileName);
}
// We take only the first file among all files with such name.
var file = files.next();
var text = file.getBlob().getDataAsString('utf8');
Logger.log(text);
// Now you have to parse the file.
}
Documentation:
DriveApp.getFilesByName returns collection of Files.
File.getBlob returns Blob.
Blob.getDataAsString returns String.

Categories

Resources