Get URL of a file in Google Drive thanks to its name - google-apps-script

First of all, sorry for my English (I'm learning ^^).
I want to have a script to find a file's url thanks to the name of the file, and then put the URL in my sheet called 'Suivi-des-devis!' in the range 'O2'
The files are always called "FAC_quote number", and the quote number is in sheet 'DEVIS!' in 'E6'.
I really tried to create the script alone, but it doesn't work. Can someone help me to correct the script please ?
function testenregistrement() {
const doc = SpreadsheetApp.getActive();
var f2 = doc.getSheetByName('Suivi-des-devis');
var dossier2 = DriveApp.getFolderById("1WNyBdexfylgflnDeKtMcdIN-eS578dlH")
var nom = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('DEVIS').getRange('E6').getValue();
var files = dossier2.getFilesByName("FAC_" + nom).getUrl(); f2.getRange('O2').setValue(files);
}

The Folder.getFilesByName() method gets a FileIterator object. Use the FileIterator.next() method to get a file, like this:
var files = dossier2.getFilesByName("FAC_" + nom).next().getUrl();

Related

Insert hyperlink with variable into google docs using google scripts

I have a google Form, and the responses populate a response google Sheet, which has a google Script function to generate a google Document using a template.
I am trying to get the address entered in the Form (stored in the response Sheet) to become a hyperlink in the generated Doc.
I have been using the body.replaceText() to replace all the fields I need in the Doc:
body.replaceText("{{Date}}", date);
and its working well, but the address field I would like to become a hyperlink.
I have been trying to do it this way:
body.replaceText("{{Location}}", =HYPERLINK("http://www.google.com/maps/place/'+location+'"));
But that does not become a usable hyperlink, resulting with this in the Doc (please note while it becomes a hyperlink on this page it does not become a hyperlink in Docs):
=HYPERLINK("http://www.google.com/maps/place/myplacenotyours")
I have also tried:
body.replaceText("{{Location}}", location = HYPERLINK("http://www.google.com/maps/place/"+location+));
But this throws up syntax errors.
I have this var:
var location = e.values[2];
So perhaps it better to use that to create another var as a hypertext?
I am now trying:
var loclink = 'Hyperlink("http://www.google.com/maps/place/'+location+'","'+location+'")';
but that doesnt do it either... I'm now starting to think that one can't insert a hyperlink using replace method?
Sorry for the noob question, but I can't figure this out. Can you help me find a solution and put a var into a hypertext link and put that into the Doc as a link?!
Cheers.
Something like this:
function insertLink() {
var pattern = '{{Location}}';
var url = 'https://stackoverflow.com/a/69143679/14265469';
var text = 'how to paste a link';
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var next = body.findText(pattern);
if (!next) return;
var start = next.getStartOffset();
body.replaceText(pattern, text);
body.editAsText().setLinkUrl(start, start+text.length-1, url);
}

Efficient Way of sending Spreadsheet over email using GAS function?

I am creating an addon for Google Sheets that my local High School's volunteer clubs can use to keep track of their member's volunteer hours. Most of the code is done and works very nicely, and I am currently working on a system that will send a member a spreadsheet listing all of the volunteer events that they have logged. I have GAS create a separate spreadsheet, and then send an email with that separate spreadsheet attached in PDF. When the email is received, the PDF is empty except for a singular empty cell at the top left of the page.
I am pretty new to GAS but have been able to grasp the content pretty easily. I have only tried one method of sending the Spreadsheet and that is by using the .getAs(MimeType.PDF). When I changed the "PDF" to "GOOGLE_SHEETS," GAS returned the error: "Blob object must have non-null data for this operation." I am not entirely sure what a Blob object is, and have not found any website or video that has fully explained it, so I am not sure how to go about troubleshooting that error.
I think I'm having a problem grabbing the file because it either sends an empty PDF or it returns an error claiming it needs "non-null data."
function TigerMail()
{
var Drive = DriveApp;
var app = SpreadsheetApp;
var LOOKUP = app.getActiveSpreadsheet().getSheetByName("Student
Lookup");
var Name = LOOKUP.getRange("E1").getValue();
Name = Name + "'s Hours";
//app.openById(Name+"'s Hours");
var HOURS = app.create(Name);
var ESheet = HOURS.getSheets()[0];
var ROW = LOOKUP.getLastRow();
var arr = LOOKUP.getRange("D1:J"+ROW).getValues();
var cell = ESheet.getRange("A1:G"+ROW);
cell.setValues(arr);
////////////////////////////////////////////////////
var LOOKUP = app.getActiveSpreadsheet().getSheetByName("Student
Lookup");
var cell = LOOKUP.getRange("D1");
var Addr = cell.getValue();
var ROW = LOOKUP.getLastRow();
var file = Drive.getFilesByName(Name);
var file = file.next();
var FORMAT = file.getAs(MimeType.GOOGLE_SHEETS);
TigerMail.sendEmail(Addr, "Hours", "Attached is a list of all of the
events you have volunteered at:", {attachments: [FORMAT]} );
}
the final four lines are where the errors are occurring at. I believe I am misunderstanding how the .next() and .getFilesByName() work.
(above the comment line: creating a spreadsheet of hours)
(below the comment line: grabbing the spreadsheet and attaching it to an email)
Here is the link to the Google Sheet:
https://docs.google.com/spreadsheets/d/1qlUfTWaj-VyBD2M45F63BtHaqF0UOVkwi04XwZFJ4vg/edit?usp=sharing
In your script, new Spreadsheet is created and put values.
You want to sent an email by attaching the file which was converted from the created Spreadsheet to PDF format.
If my understanding is correct, how about this modification? Please think of this as just one of several answers.
Modification points:
About Drive.getFilesByName(Name), unfortunately, there is no method of getFilesByName() in Drive.
I think that when you want to use the created Spreadsheet, HOURS of var HOURS = app.create(Name) can be used.
About var FORMAT = file.getAs(MimeType.GOOGLE_SHEETS), in the case of Google Docs, when the blob is retrieved, the blob is automatically converted to PDF format. This can be also used for your situation.
In order to save the values put to the created Spreadsheet, it uses SpreadsheetApp.flush().
When above points are reflected to your script, it becomes as follows.
Modified script:
Please modify as follows.
From:
var file = Drive.getFilesByName(Name);
var file = file.next();
var FORMAT = file.getAs(MimeType.GOOGLE_SHEETS);
To:
SpreadsheetApp.flush();
var FORMAT = HOURS.getBlob();
Note:
In your script, it seems that var ROW = LOOKUP.getLastRow() is not used.
References:
flush()
getBlob()
If I misunderstood your question and this was not the result you want, I apologize.

How to open a spreadsheet only by name of the corresponding file in Google Sheets?

I need a way to open a spreadsheet only by having the name of the corresponding file and the folder where the file is located. What I'm trying to do is creating a temporary copy of an active spreadsheet and reading information from the copy file rather than the active one. But unfortunately this copy file won't have a constant ID and URL as it's going to be erased every time after the script is done, and re-created with the next running of the script.
What I already tried is using the URL of the temporary file in order to open the spreadsheet itself, as you can see below.
But it's not useful for me, as I don't have a constant URL of this file (as it will be erased in the end of the script and have a new URL with the next script). But I have a constant name of the file, as well as this will be the only file in the respective folder.
What I also tried is looking for methods to open file only using its name (which is "temp_copy" in a 'temp_folder'). But I didn't find a working solution.
var report = SpreadsheetApp.getActiveSpreadsheet();
var temp_folder =
DriveApp.getFolderById("1EAsvVcFjIw5iGTeF_SxxQJLVlaLHl_pR");
DriveApp.getFileById(report.getId()).makeCopy("temp_copy", temp_folder);
var temp_copy = SpreadsheetApp.openByUrl(' ');
var hiddenSheet = temp_copy.getSheetByName('DATE');
var lastRow = hiddenSheet.getSheetValues(1,1,1,1);
var sheet = temp_copy.getSheetByName('forCSV');
var lastColumn = sheet.getLastColumn();
var activeRange = sheet.getRange(1,2,lastRow,lastColumn);
What I'm expecting as a result is to make the link between the 3rd line of the code (when making a copy of the basic file) and 5th line of the code onwards (when referencing specific range from the temporary file) only by using name of the file or respective folder. In theory it seems so easy, I should be missing something somewhere...
Many thanks in advance!
You can use DriveApp to get a FileIterator which contains the Sheet.
var file, files = DriveApp.getFilesByName("temp_copy");
if (files.hasNext ()){
file = files.next(); // Get first result for name
} else {
return "";
}
var sheet = SpreadsheetApp.openById(file.getId())

How to use Document App to create a file with chosen template

I need to create a app to automatically create a google doc, with our company's template (it have saved in G-suite). Here is my question, how to use the DocumentApp to create a doc with the template.
I spent some time inenter link description here, but can not find any.
Any reference or document will be appreciated, thanks!
It is quite simple to do! Here is an example what I have put together for you!
function makeDoc() {
var fileId = DriveApp.getFileById("<<FILEID>>");
var copyId = fileId.makeCopy("<<NEWFILENAME>>").getId();
var copyDoc = DocumentApp.openById(copyId);
var copyBody = copyDoc.getBody();
var doclink = copyDoc.getUrl();
// If it finds <<SOMETHING_IN_TEMPLATE>> it will replace it with "replace in doc"
copyBody.replaceText("<<SOMETHING_IN_TEMPLATE>>", "Replace in doc");
// Save and close the temporary document
copyDoc.saveAndClose();
//Move the new doc to the Unsigned Contracts folder and get a URL for it
var folder = DriveApp.getFolderById("<<WHERE TO SAVE IT>>");
var file = DriveApp.getFileById(copyId);
folder.addFile(file);
// Delete temp file
var doclink = file.getUrl();
DriveApp.getFileById(copyId).setTrashed(true);
//CTRL + Enter to get the link
Logger.log(doclink)
P.s. just noticed this is an old post! Hope this helps someone!
After researching around, I think Google dose not provide the way I could select the template while creating the doc through API. Even they might have, it probably is not the straight shot.

Google Code (Drive) createFile in parent folder/overwrite existing file in parent folder

so i created a simple google code that exports sheet to json, and I'm wondering if there's a simple way to:
Export the file to the same folder where the sheet that script running it is in,
Overwrite the file if it already exists (also in the same folder the sheet script is in)
cheers
There's no easy way, but here's how (I assume you're using Apps Script):
Get the file id of your spreadsheet https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getId()
Get its parent folders - there can be more than one - https://developers.google.com/apps-script/reference/drive/file#getParents()
See if there are existing files with the name - there can be more than one - https://developers.google.com/apps-script/reference/drive/folder#getFilesByName(String)
If it exists set its content https://developers.google.com/apps-script/reference/drive/file#setcontentcontent
If it doesn't exist create it - https://developers.google.com/apps-script/reference/drive/folder#createfilename-content
thanx to Ian for research links, made it work :)
here's the snippet if anyone else is needing the same thing
var _ID = SpreadsheetApp.getActiveSpreadsheet().getId();
var _sheet = SpreadsheetApp.getActiveSpreadsheet();
var _file = DriveApp.getFolderById(_ID);
var _folder = _file.getParents().next();
var _parentFolder = _file.getParents().next();
var _existingJsons = _parentFolder.getFilesByName(sheet.getName()+".json");
// if .json with the same name already exists in this directory, just overwrite content
if (_existingJsons.hasNext()){
while (_existingJsons.hasNext() ){
var _json = _existingJsons.next();
_json.setContent(output);
Logger.log(_json.getName());
}
}
// if not, create new one, and move it in the same folder sheet is in
else {
var _json = DriveApp.createFile(sheet.getName()+".json", output, MimeType.PLAIN_TEXT);
_json.makeCopy(_parentFolder);
_json.setTrashed(true);
}