So I have the script below which allows me to automatically create google drive hyperlinks of files within the same directory:
function myFunction() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var s=ss.getActiveSheet();
var c=s.getActiveCell();
var fldr=DriveApp.getFolderById(*[insert id]*);
var files=fldr.getFiles();
var names=[],f,str;
while (files.hasNext()) {
f=files.next();
str='=hyperlink("' + f.getUrl() + '")';
str2 = f.getName();
names.push([str2,str]);
}
s.getRange(c.getRow(),c.getColumn(),names.length,2).setValues(names);
}
I am very novice, however, so I can't really figure out how I would get this to search through each of the subfolders as well to get their hyperlinks too. I feel as if this is probably relatively simple, but I am not well versed enough in google scripts to do this (if it was python, I could do this easily). Any help would be greatly appreciated.
I believe your goal as follows.
You want to retrieve all files under the specific folder, and put the values of URL and filename to the Spreadsheet.
The specific folder has the subfolders.
You want to achieve this using Google Apps Script.
Modification points:
In your script, the files are retrieved from just under the specific folder.
In order to retrieve all files under the specific folder including the subfolders, it is required to traverse all subfolders.
When above points are reflected to your script, it becomes as follows. In this modification, Drive service is used.
Modified script:
function myFunction() {
// Method for retrieving the file list from the specific folder including the subfolders.
const getAllFiles = (id, list = []) => {
const fols = DriveApp.getFolderById(id).getFolders();
let temp = [];
while (fols.hasNext()) {
const fol = fols.next();
temp.push(fol.getId());
const files = fol.getFiles();
while (files.hasNext()) {
const file = files.next();
list.push([`=hyperlink("${file.getUrl()}")`, file.getName()]);
}
}
temp.forEach(id => getAllFiles(id, list));
return list;
}
const folderId = "###"; // Please set the folder ID.
const names = getAllFiles(folderId);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
var c = s.getActiveCell();
s.getRange(c.getRow(), c.getColumn(), names.length, 2).setValues(names);
}
References:
Drive Service
About the file list from the specific folder including the subfolders, this thread might be useful.
Related
i need your help.
so i have a spreadsheet with 2 sheets: "file to copy" and "folder name"
"file to copy" has 5 column where in column C i have full link to files (are in different Drive folders), and in column E i have ID files. this list of files could contain also 4/500 files
I have a function that it works, but when save files it give me back html files (but there are pictures)
So i am at point that i can create the folder, but i cannot copy files
Is there someone that could help me to complete the function? i am a rookie here and i didn't find any right solution here.
thank you very much for your help
here the code until now
function copyImg() {
var ss = SpreadsheetApp.getActive(),
iniTime = Date.now()/1000,
lr = ss.getSheetByName("file to copy").getLastRow(),//sheet where i have files to copy
nameFolder = ss.getRange("folder name!$A$2").getValue() + " " + ss.getRange("folder name!$B$2").getDisplayValue();//name of the destination folder
var sourceFileId = ss.getRange("e1:e").getValues();//range where i have ID files
var folders = DriveApp.getFoldersByName(nameFolder)
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(nameFolder);
}
}
//here i have problems to get files and push into the new folder
I have a large directory of workbooks that I need to change the parameters of a named range. I have recorded a Macro that can do this and I'm sure there's a quick way to apply?
I have a Tab in a directory workbook called 'Planner Fixes' & I have a list of Sheet ID's to send the amendment too.
The Macro is as below:
function ElementsEdit() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('A1').activate();
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('API BootstrapStatic'), true);
spreadsheet.getRange('A2:BK514').activate();
spreadsheet.setNamedRange('Elements', spreadsheet.getRange('A2:BK1000'));
spreadsheet.getActiveSheet().hideSheet();
};
I know that the line var spreadsheet = SpreadsheetApp.getActive(); needs to change to look for the spreadsheet ID and 'open' that?
I'm very new to scripts and have generally only used ones I have found online but I can't seem to find anything to do this at all.
If you have multiple workbooks, and if you know the id of each of them, try
var spreadsheet = SpreadsheetApp.openById(YOUR_SPREADSHEET_ID);
for each
You can loop through a list of id
const ids = [
'1T7ixa-JGLgh8oxxxxxxxxxo4UzbivflUlwL9zLGVkgg',
'16uEeVNEBzBbGVTgKa98yyyyyyyyyyyy6mU-yKIZ0fKM',
'1d3ZHizzzzzzzzzzzzzzzzzzzLkmM4bFHyDn8RFtAlkk'
]
function myFunction() {
ids.forEach((id, i) => {
var spreadsheet = SpreadsheetApp.openById(id)
// your script here
})
}
I`m trying to get output of all the files URLs form the current folder, but I only get URL of the first file from the forlder here:
function listFolderContents() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Hub 2');
var foldername = sheet.getRange('D160').getValue();
var linkoutput = sheet.getRange('W160');
var folders = DriveApp.getFoldersByName(foldername);
var folder = folders.next();
var contents = folder.getFiles();
Logger.log(linkoutput);
var file;
var link;
while(contents.hasNext()) {
file = contents.next();
link = file.getUrl();
linkoutput.setValue(link);
}
};
3 more things:
I`d like to have this script looped through the whole column, so it would check each folder name in column D and output files links in the column W;
the best outcome would be if it could output all the 3 links(as each folder would have only 3 files anyways) in the range of W:Y of the same row with the foder name;
and the last if this script could run automatically without a need to open Scripts tool and running the code every time.
thanks in advance!
For this question:
and the last if this script could run automatically without a need to open Scripts tool and running the code every time. thanks in advance!
You can set a Trigger to run when the spreadsheet is opened. Or you could set time triggers, to run daily for example.
Regarding the code, It looks like your are setting the link url always to the same cell (W60).
I'm passing information from Google Sheets to a Document via Google Apps Script. All the information transfers with two exceptions...
The link of the picture shows rather than the image. How can I insert the image rather than the link?
In the folder it saves to, I get 2 versions of the document. One with the name I want, and another named 'Copy of Template'. I don't want the copy of the template, how can I either not create it, or delete it in the script?
Any help would be greatly appreciated.
function myFunction(e) {
var timestamp = e.values[0];
var studentName = e.values[1];
var firstName = e.values[2];
var studentNumber = e.values[3];
var dateOfBirth = e.values[4];
var studentImage = e.values[5];
var file = DriveApp.getFileById('fileId');
var folder = DriveApp.getFolderById('folderId')
var copy = file.makeCopy(studentName, folder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
body.replaceText('{{Time}}', timestamp);
body.replaceText('{{Name}}', studentName);
body.replaceText('{{Preferred Name}}', firstName);
body.replaceText('{{Student Number}}', studentNumber);
body.replaceText('{{DOB}}', dateOfBirth);
body.replaceText('{{Image}}', studentImage);
doc.saveAndClose();
}
The expected output is a document with relevant information, an image of the student, and only 1 version of the document in the folder.
I am unsure of why your code creates an extra copy of your file. This might be due to something else.
However, to change "{{image}}" to an image from an URL you can do this:
body.findText('{{Image}}').getElement().asParagraph()
.setText("") //Clears text
.appendInlineImage(UrlFetchApp.fetch(studentImage).getBlob()); //Adds image element from URL
I'm trying to code something that search for a PDF (gmail) with a serial number I already have, save it in Drive, get OCR on it and read the content.
No problem with the first step, and the second one is managed with the following code, but the last two lines to open the document with DocumentApp in order to getText(), are not working :
var serial = "123456789";
var ret = DriveApp.searchFiles('fullText contains "' + serial + '"');
if (ret.hasNext()) {
var file = ret.next();
var n_blob = Utilities.newBlob(file.getBlob().getDataAsString(), MimeType.PDF);
n_blob.setName(serial);
var n_file = DriveApp.createFile(n_blob);
var rt = DocumentApp.openById(n_file.getId()); **//not working**
var text = rt.getBody().getText(); **//not working**
}
I tried many differents ways, including the solution based on Drive.Files.insert() which is not working anymore..
I'm pretty stuck here, if anyone has any idea or suggestion to help me out?
Thanks
You want to convert a PDF file to Google Document file.
file of var file = ret.next(); is always PDF file.
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
Unfortunately, var n_blob = Utilities.newBlob(file.getBlob().getDataAsString(), MimeType.PDF) and var n_file = DriveApp.createFile(n_blob) cannot create Google Document. By this, an error occurs.
Pattern 1:
In this pattern, Drive.Files.copy is used for converting PDF to Google Document. Because in your question, I saw Drive.Files.insert() which is not working anymore.
Modified script:
Please modify your script as follows. Before you run the script, please enable Drive API at Advanced Google services.
From:
if (ret.hasNext()) {
var file = ret.next();
var n_blob = Utilities.newBlob(file.getBlob().getDataAsString(), MimeType.PDF);
n_blob.setName(serial);
var n_file = DriveApp.createFile(n_blob);
var rt = DocumentApp.openById(n_file.getId()); **//not working**
var text = rt.getBody().getText(); **//not working**
}
To:
if (ret.hasNext()) {
var file = ret.next();
if (file.getMimeType() === MimeType.PDF) {
var fileId = Drive.Files.copy({mimeType: MimeType.GOOGLE_DOCS}, file.getId()).id;
var rt = DocumentApp.openById(fileId);
var text = rt.getBody().getText();
Logger.log(text)
}
}
Pattern 2:
I thought that Drive.Files.insert might be able to be used. So in this pattern, I propose the modified script using Drive.Files.insert. Could you please test this?
Modified script:
Please modify your script as follows. Before you run the script, please enable Drive API at Advanced Google services.
From:
if (ret.hasNext()) {
var file = ret.next();
var n_blob = Utilities.newBlob(file.getBlob().getDataAsString(), MimeType.PDF);
n_blob.setName(serial);
var n_file = DriveApp.createFile(n_blob);
var rt = DocumentApp.openById(n_file.getId()); **//not working**
var text = rt.getBody().getText(); **//not working**
}
To:
if (ret.hasNext()) {
var file = ret.next();
if (file.getMimeType() === MimeType.PDF) {
var fileId = Drive.Files.insert({title: serial, mimeType: MimeType.GOOGLE_DOCS}, file.getBlob()).id;
var rt = DocumentApp.openById(fileId);
var text = rt.getBody().getText();
Logger.log(text)
}
}
Note:
Unfortunately, I cannot understand about Drive.Files.insert() which is not working anymore. So if above modified script didn't work, please tell me. I would like to think of other methods.
When you check the log, if you cannot see the texts of Google Document converted from PDF, it means that all files of var file = ret.next(); are not PDF type. Please be careful this.
References:
Advanced Google services
Files: copy
Files: insert
If I misunderstood your question and this was not the direction you want, I apologize.