Google Apps Script opening a document by name? - google-apps-script

I'm trying to make a program where if a document doesn't exist yet, create it, but if it does, edit it.
I tried to do it like this:
if(check == false){
var doc = DocumentApp.create('Announcements for '+ data[0][2]);
}
else{
var doc = DocumentApp.openById('Announcements for '+ data[0][2]);
}
Here, 'check' is true when the file exists, and false if it doesn't.
I'm assuming that the problem is that I'm using 'openById' incorrectly.
What is the document id, and how can my code know what it is?
Thanks in advance!
(First-time user here, sorry for any formatting errors)
edit: I'll be making multiple docs, and all I know about the doc I need to open is its name

The parameter of openById() is the file id of the document you are trying to access. File id is the value between the "/d/" and the "/edit" of your Google Document URL.
Example: https://docs.google.com/document/d/12345/edit where 12345 is the id.
DocumentApp does not have method for opening documents using file name. The only available methods are openById() and openByUrl().
An alternative is to use DriveApp to get the name, id, and mimetype of the files inside your Drive or Drive folder.
Example:
The code below will open a document if it matches the fileName 'Announcement 1' :
Code:
function openByName() {
//open specific folder and get the files
var files = DriveApp.getFolderById('insert folder id here').getFiles();
var fileName = 'Announcement 1';
//The code below will search for Announcement 1 file and open it if found.
while (files.hasNext()) {
var file = files.next();
var fileType = file.getMimeType();
//Check if the filename matches 'Announcement 1' and the file type should be google-apps.document
if(file.getName() == fileName && fileType == 'application/vnd.google-apps.document'){
//Open document
DocumentApp.openById(file.getId());
}
}
}
Test Folder:
References:
Class DocumentApp
Class DriveApp

Related

google apps script. copy files to one drive

I would have files stored in google drive and I would like to copy (or move) those files to my OneDrive. I have managed to connect OneDrive to google drive and I can successfully create folders and upload files by file ID. I am trying to copy (or move) multiple files at once from google drive to OneDrive though without any luck yet. I am not good at programming just doing everything by tutorials only but yet could not find any working one. Maybe anyone could guide me how to do it? For the final idea I would like to achieve that files from google drive would be copied even to separate folders by the part of file title (name and surname, if to be exact). Currently I have "developed" such script:
function moveFiles(source, dest_folder) {
var source = DriveApp.getFolderById("1faFbaXJNziwIGyer2H2IPALQ8ahBfGMc");
var prop = PropertiesService.getScriptProperties();
var odapp = OnedriveApp.init(prop);
var files = DriveApp.getFiles();
while (files.hasNext()) {
var file = files.next();
var dest_folder =
OnedriveApp.init(PropertiesService.getScriptProperties()).uploadFile(files,
"/samplefolder");
}
}
I believe your current situation and your goal are as follows.
You are using OnedriveApp.
You have already been finished the authorization process. So you have already been had the access token and refresh token in the PropertiesServices.
You want to upload the files in a specific folder of Google Drive to a specific folder in OneDrive.
The number of files is 10 - 20.
The file size is small.
From your following reply
I have changed accordingly to: var files = file.getId(); but then I receive such error: TypeError: Cannot read property 'getId' of undefined moveFiles # srcpt.gs:5 If I use DriveApp.getFiles() or source.getFiles(), I receive such error: Exception: Unexpected error while getting the method or property getFileById on object DriveApp. convToMicrosoft # code.gs:629 OnedriveApp.uploadFile # code.gs:460 Appreciated for any help.
About var files = file.getId(); and If I use DriveApp.getFiles() or source.getFiles(), I receive such error:, unfortunately, I cannot understand it.
In this case, how about the following modification?
Modified script:
function myFunction() {
var prop = PropertiesService.getScriptProperties();
var odapp = OnedriveApp.init(prop);
var source = DriveApp.getFolderById("###"); // Please put your folder ID.
var files = source.getFiles();
while (files.hasNext()) {
var file = files.next();
odapp.uploadFile(file.getId(), "/samplefolder/"); // Please set the destination folder name. In this case, the folder name in OneDrive.
}
}
When "/samplefolder" is used, an error occurs. Please enclose the folder name by / like "/samplefolder/". Please be careful about this.
When this script is run, the files in the specific folder of Google Drive are copied to the destination folder of /samplefolder/ in OneDrive.
References:
OnedriveApp
getFolderById(id)
getFiles()

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())

Google Apps Script - get URL of File in Drive with File Name

I am attempting to create a form in Google Spreadsheets which will pull an image file from my Drive based on the name of the file and insert it into a cell. I've read that you can't currently do this directly through Google Scripts, so I'm using setFormula() adn the =IMAGE() function in the target cell to insert the image. However, I need the URL of the image in order to do this. I need to use the name of the file to get the URL, since the form concatenates a unique numerical ID into a string to use the standardized naming convention for these files. My issue is that, when I use getFilesByName, it returns a File Iteration, and I need a File in order to use getUrl(). Below is an snippet of my code which currently returns the error "Cannot find function getUrl in object FileIterator."
var poNumber = entryFormSheet.getRange(2, 2);
var proofHorizontal = drive.getFilesByName('PO ' + poNumber + ' Proof Horizontal.png').getUrl();
packingInstructionsSheet.getRange(7, 1).setFormula('IMAGE(' + proofHorizontal + ')');
If you know the file name exactly, You can use DriveApp to search the file and getUrl()
function getFile(name) {
var files = DriveApp.getFilesByName(name);
while (files.hasNext()) {
var file = files.next();
//Logs all the files with the given name
Logger.log('Name:'+file.getName()+'\nUrl'+ file.getUrl());
}
}
If you don't know the name exactly, You can use DriveApp.searchFiles() method.
You're close - once you have the FileIterator, you need to advance it to obtain a File, i.e. call FileIterator.next().
If multiple files can have the same name, the file you want may not be the first one. I recommend checking this in your script, just in case:
var searchName = "PO + .....";
var results = DriveApp.getFilesByName(searchName);
var result = "No matching files";
while (results.hasNext()) {
var file = results.next();
if (file.getMimeType() == MimeType. /* pick your image type here */ ) {
result = "=IMAGE( .... " + file.getUrl() + ")");
if (results.hasNext()) console.warn("Multiple files found for search '%s'", searchName);
break;
}
}
sheet.getRange( ... ).setFormula(result);
You can view the available MimeTypes in documentation

Google apps script: How to create a downloadable html file?

Starting with 'google apps script'. I've created a simple script that logs some information with 'Logger.log("message");' with this lines being in a loop, so the log message is quite large.
I'd like now to create an html file with that same information and either being able to download that file locally or have it downloaded to my google drive.
Any idea how that could be achieved? I've tried looking examples for a while but I cannot have anything working...
Many thanks!
Yes you can, you should read first. Have a look this documentation
function createMyHTMLlog()
{
var folders = DriveApp.getFoldersByName('ff');// ff:your folder name on drive
if (folders.hasNext())
{
var folder = folders.next(); //select the folder
folder.createFile('Log','<b> your message here </b>', MimeType.HTML); //create the file
}
}
Update: Add more content later
function logUpdate()
{
var children = folder.getFilesByName('Log');// log is the created file name
if (children.hasNext())
{
var file = children.next();
var logContent = file.getAs('text/plain').getDataAsString();// get available msg
logContent = logContent.concat('<br>your<b> updated message </b> here'); // combine with new msg
file.setContent(logContent);
}
}

Overwrite an Image File with Google Apps Script

Can I overwrite an image file with Google Apps Script? I've tried:
file.setContent(newBlobImage);
file.replace(newBlobImage);
Neither of those work. .setContent() will delete whatever data was in the file, and it looks like maybe it just writes the variable name as text, or something like that. I'm assuming that both .setContent() and .replace() are meant for text documents, and maybe that's why they don't work.
If it were a text file, or a spreadsheet, I might be able to clear it, then append new content.
I can trash the file, then create a new one, but I'd rather not if there is some other way.
If I write a file with the same name, it won't overwrite the existing file, it creates a another file with the same name.
The only way I've been able to trash the file is with DocsList and the only success I've had with creating an image file is with DriveApp. So I have to trash the file with DocsList, then create another file with DriveApp.
Well, I've figured out how to delete the file without sending it to the trash, so I won't need to clean out the trash later. The Google Drive SDK inside of Apps Script has a remove method that didn't send the file to trash, it's just gone.
var myFolder = DriveApp.getFolderById('3Bg2dKau456ySkhNBWB98W5sSTM');
thisFile = myFolder.getFilesByName(myFileName);
while (thisFile.hasNext()) {
var eachFile = thisFile.next();
var idToDLET = eachFile.getId();
Logger.log('idToDLET: ' + idToDLET);
var rtrnFromDLET = Drive.Files.remove(idToDLET);
};
So, I'm combining the DriveApp service and the DriveAPI to delete the file without sending it to the trash. The DriveAPI .remove needs the file ID, but I don't have the file ID, so the file gets looked up by name, then the file ID is retrieved, then the ID is used to delete the file. So, if I can't find a way to overwrite the file, I can at least delete the old file without it going to the trash.
I just noticed that the DriveAPI service has a Patch and an Update option.
.patch(resource, fileId, optionalArgs)
Google Documentation Patch Updates file metadata.
The resource arg is probably the metadata. The fileId is self explanatory. I'm guessing that the optionalArgs are parameters that follow the HTTP Request Patch semantics? I don't know.
It looks like both Patch and Update will update data. Update is a PUT request that will
clears previously set data if you don't supply optional parameters.
According to the documentation. So it's safer to use a Patch request because any parameters that are missing are simply ignored. I haven't tried it yet, but maybe this is the answer.
I'm getting an error with Patch, so I'll try Update:
.update(resource, fileId, mediaData)
That has a arg for mediaData in the form of a blob. And I think that is what I need. But I'm not sure what the resource parameter needs. So I'm stuck there.
An image file can be overwritten with Google Apps Script and the DriveAPI using the update() method:
.update(File resource, String fileId, Blob mediaData)
Where file resource is:
var myFileName = 'fileName' + '.jpg';
var file = {
title: myFileName,
mimeType: 'image/jpeg'
};
I'm getting the file ID with the DriveApp service, and the Blob is what was uploaded by the user.
In order to use DriveAPI, you need to add it through the Resources, Advanced Google Services menu. Set the Drive API to ON.
var allFilesByName,file,myFolder,myVar,theFileID,thisFile;
//Define var names without assigning a value
file = {
title: myFileName,
mimeType: 'image/jpeg'
};
myFolder = DriveApp.getFolderById('Folder ID');
allFilesByName = myFolder.getFilesByName(myFileName);
while (allFilesByName.hasNext()) {
thisFile = allFilesByName.next();
theFileID = thisFile.getId();
//Logger.log('theFileID: ' + theFileID);
myVar = Drive.Files.update(file, theFileID, uploadedBlob);
};
Thank you for this track !
This allowed me to find a solution to my problem : move a bound form after copying and moved his spreadsheet.
The Drive app advanced service must be activated in the "Resource Script Editor" to run this script.
function spreadsheetCopy() {
// Below is the file to be copied with a bound form.
var fileToCopy = DriveApp.getFileById("file_key"); // key is fileId
var saveFolder = DriveApp.getFolderById("folder_key"); // key is folderId
var currentFolder = "";
( fileToCopy.getParents().next() ) ? currentFolder = fileToCopy.getParents().next() : currentFolder = DriveApp.getRootFolder();
Logger.log(currentFolder)
var copyFile = fileToCopy.makeCopy(saveFolder),
copyName = copyFile.getName();
Utilities.sleep(30000);
moveFormCopy(currentFolder, saveFolder, copyName);
}
function moveFormCopy(currentFolder, saveFolder, copyName) {
var formsInFolder = currentFolder.getFilesByType(MimeType.GOOGLE_FORMS);
var form, copyForm, copyFormMimeType, copyFormName, copyFormId;
while ( formsInFolder.hasNext() ) {
form = formsInFolder.next();
if ( copyName === form.getName() ) {
copyForm = form;
copyFormMimeType = copyForm.getMimeType();
copyFormName = copyForm.getName();
copyFormId = copyForm.getId();
break;
}
};
var resource = {title: copyName, mimeType: copyFormMimeType};
Drive.Files.patch(resource, copyFormId, {addParents: saveFolder.getId(), removeParents: currentFolder.getId()})
}