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

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);
}
}

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

Google Apps Script moving file to Team Drive folder

Background:
At the core of the issue is I have an Alteryx job dropping files into my google drive. These files need, in actuality, in a Team Drive folder. Try as I might, nowhere have I found a way for Alteryx to do this. So hence the need for this script.
Actual problem:
So here is the criteria: I have the files being created with the same naming convention with only the date changing. I need these files to go from my drive to a team drive where they are eventually worked on.
Using the resources already here on stack I found wonderful solutions here: 1 and here 2 that I was able to cobble together a working script.
Understand I am a marginally functional python programmer for data analytics. So my JS and Google scripting are rudimentary at best. The first time I tested the script, it worked. Wonderfully, right up until it didn't.
It moved my first file with no problem. I then created a few copies of that same file in the drive to see how it handled multiple. I now get an error:
Exception: No item with the given ID could be found, or you do not
have permission to access it. (line 15, file "CodeA1")
Here is my code:
function SearchFiles() {
//searches based on naming criteria
var searchFor ='title contains "Reference Data Performance"'; //test file
var names =[];
var fileIds=[];
var files = DriveApp.searchFiles(searchFor);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();// To get FileId of the file
fileIds.push(fileId);
var name = file.getName();
names.push(name);
}
var file = DriveApp.getFileById(fileIds);
supportsTeamDrives: true;
supportTeamDrives: true;
var targetFolder = DriveApp.getFolderById('TEAMDriveID');
targetFolder.addFile(file);
}
Exception: No item with the given ID could be found, or you do not
have permission to access it.
This error occurs most often if either
The TeamDriveId is not correct
The account from which you run the script is not member of the team drive
Also note:
supportsTeamDrives: true;
supportTeamDrives: true;
are parameters
for the Drive API, not to be confused with DriveApp
Update:
I ended up going with a simplified version of this script. I had Alteryx schedule the file creation (three different files) at hour increments. Then made a trigger in Google Apps to run the script at the times directly after each Alteryx scheduled drop. Simple? Yes. Inelegant? Maybe. Been running all week and files arrive at their destination for people to work on.
function SearchFiles() {
//searches based on naming criteria
var searchFor ='title contains "Reference Data Performance"'; //looks for file that matches requirements
var files = DriveApp.searchFiles(searchFor);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();// To get FileId of the file
var file = DriveApp.getFileById(fileId); //grabs file ready to pass to google drive.
supportsTeamDrives: true;
supportTeamDrives: true;
var targetFolder = DriveApp.getFolderById('FOLDERID');
targetFolder.addFile(file);//good for getting a single file needs loop to grab multiple from Array
}
}

PDF Template Archiving

I have Created a form that generates a response sheet. I also have created a Doc which is a Template that my responses fill into. From here it was being turned into a PDF and e-mailed to specific recipients. I now need to archive these into specific folders based on a columns answer. I simply first would like to just be able to move or copy them into a specific folder. How is this possible. I have used multiple scripts but just cant see where the disconnect is. Any help would be greatly appreciated. Thank you enter link description here
You could try using some code like this:
function moveFileToFolder() {
var theFolder = DriveApp.getFolderById('your Folder ID');
var theFile = DriveApp.getFileById('Your File ID').makeCopy(theFolder);
var oldFileName = theFile.getName();
var archivedName = oldFileName.slice(5);
Logger.log('archivedName: ' + archivedName);
archivedName = "archive" + archivedName;
theFile.setName(archivedName);
}
To delete the old file without having to send it to the trash:
//This requires the Drive API To be turned on in the Advanced Google Services.
//RESOURCES menu, ADVANCED GOOGLE SERVICES
function deleteFile(idToDLET) {
//idToDLET = 'the File ID';
//This deletes a file without needing to move it to the trash
var rtrnFromDLET = Drive.Files.remove(idToDLET);
}

Downloading multiple files from google addon

Hi I'm trying to download multiple files from a google folder as txt. I'm using the google script. So far my code will successfully download the first file from a folder but it stops and wont download the rest of the files in that folder. Thanks
function doGet() {
var folder = DriveApp.getFolderById('FolderKeyHere')
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
var id = file.getId();
var doc = DocumentApp.openById(id);
var string = doc.getBody().getText();
var output = ContentService.createTextOutput();
output.setMimeType(ContentService.MimeType.TEXT);
output.setContent(string);
output.downloadAsFile(file.getName());
return output;
};
};
This won't be possible like that, the return output; will actually "return" the app and of course exit the while loop.
I think you won't be able to loop this kind of process without user action.
You might build a small Ui that would have a button to download files one by one on each button click but I guess that's not what you are looking for.
Why not create all the files in your drive, compress all the files in a single zip file, download the zip and then delete the files and the zip from your drive ?
Slightly longer to write but -I think - the only useable workflow to get multiple files in a single download.

How to delete/overwrite CSV file using google apps script?

My google apps script imports a csv file [test.csv] into a new tab, manipulates some values, then saves the manipulated tab as a csv file [test.csv]. When it saves the new version, it simply makes another copy [test(1).csv]. I wish instead to overwrite the previous file (or delete the old one then export/write the new version.) Help please?
I am using reference code from the Interacting With Docs List Tutorial
I know this is an old question, but much of the information in the accepted answer has been deprecated by Google since then. DocsList is gone, as are the clear() and append() methods on a file object.
I use the following function to create or overwrite a file:
// Creates or replaces an existing file
function updateFile (folder, filename, data) {
try {
// filename is unique, so we can get first element of iterator
var file = folder.getFilesByName(filename).next()
file.setContent(data)
} catch(e) {
folder.createFile(filename, data)
}
}
For reference, here's some code for doing the same for a folder. It assumes we're operating in the parent folder of the current sheet and want a folder
object for a new or existing folder there.
// Get folder under current folder. Create it if it does not exist
function getOrCreateFolder(csvFolderName) {
var thisFileId = SpreadsheetApp.getActive().getId();
var thisFile = DriveApp.getFileById(thisFileId);
var parentFolder = thisFile.getParents().next();
try {
// csvFolderName is unique, so we can get first element of iterator
var folder = parentFolder.getFoldersByName(csvFolderName).next();
// asking for the folder's name ensures we get an error if the
// folder doesn't exist. I've found I don't necessarily catch
// an error from getFoldersByName if csvFolderName doesn't exist.
fname = folder.getName()
} catch(e) {
var folder = parentFolder.createFolder(csvFolderName);
}
return folder
}
You could do DocsList.find(fileName) which gives you a list of files that have that name. If file names are unique, then you can just do var file = DocsList.find(fileName)[0].
If you are a Google Apps user, you can use file.clear() to remove all the contents of the old file, and then file.append() to insert all of the new contents.
Otherwise, you will have to file.setTrashed(true) and then DocsList.createFile() to make the new one.