Can I add a script to a Google Sheet using another script? - google-apps-script

I have a script populate() to run an automation script on Google Sheets. I want this script to be run on over a hundred Google Sheets files. Is there a way to write a script to add to (or at least run) my populate() script on all those files? I prefer to be able to add the script to each file because we may need to run the scripts multiple times for each file. Otherwise, I will have to manually copy/paste the script to each sheet, which takes time.
Update: Removed the part about converting Excel files to Google Sheets because I found the answer for that on another thread here.

Solution
From what I have understood from your post, your question is about how to convert a series of Excel files inside a Drive folder into Google Sheets to then execute a function in them.
For that, you could iterate over all the files of your folder and convert them with the use of Drive.insert from the Drive API. For that, you will have to enable in your script the Advanced Google Services. If you do not know how to do so, please follow these indications.
The follow script performs what I think you are aiming for, it has self explanatory comments:
function convertExcelToGoogleSheets() {
// Id of the folder where you have all your excel files
var folderId = 'FOLDERID';
var folder = DriveApp.getFolderById(folderId);
// Get all the files in your folder and iterate over them
var files = folder.getFiles();
// For each file:
while (files.hasNext()){
var file = files.next();
// Get its blob (content)
var blob = file.getBlob();
// Create the resource to insert the Google Sheet file. Put the same name
// as the original and set the type of the file to Google sheets and its
// parent folder to where the excel files are located
var resource = {
title: file.getName(),
mimeType: MimeType.GOOGLE_SHEETS,
parents: [{id: folderId}],
};
// User Drive API to insert the actual file and get its ID
var id = Drive.Files.insert(resource, blob).getId();
// Whatever function you want to perform in the newly created Google Sheet
// pasing the parameter of the file id
myScript(id);
}
}
// Set the first cell of all the converted sheets to "IT WORKED"
function myScript(id){
SpreadsheetApp.openById(id).getActiveSheet().getRange('A1').setValue('IT WORKED!');
}
EDIT: If you want to run a script for each of this converted sheets you can simply call it in the while loop and pass the new file id as a parameter to then be able to use the script (remember to encapsulate this script in a function).
I hope this has helped you. Let me know if you need anything else or if you did not understood something. :)

Related

Apps Script - Search Gmail label for all attachments and overwrite files to google drive folder

Using prior articles and questions found within stack overflow I was able to find a snippet of App Script that searches Gmail labels for attachments and moves them to a specific folder in Google Drive.
function saveAttachmentInFolder(){
var folder = DriveApp.getFolderById('xxosi2');
var userId = "please.thanks#gmail.com";
var query = "label:thankyoucards-reports";
var res = Gmail.Users.Messages.list(userId, {q: query});//I assumed that this works
res.messages.forEach(function(m){
var attA=GmailApp.getMessageById(m.id).getAttachments();
attA.forEach(function(a){
folder.createFile(a.copyBlob()).setName(a.getName());
});
});
}
I need to modify this code to perform the following additional functions:
If file exists, overwrite and retain version history
I have also played around with the answer found in the following thread to no avail as I believe this is hard coded in some way and too specific to the one file type (xlsx) Copying attachments from Gmail to Google Drive folder and overwriting old files with Apps Script.
I believe your goal is as follows.
You want to check this using the filename between the existing file in the folder and the attachment file.
You want to overwrite the existing file with the attachment file.
In this case, how about the following modification? In this case, Drive API is used. So, please enable Drive API at Advanced Google services.
From:
folder.createFile(a.copyBlob()).setName(a.getName());
To:
var filename = a.getName();
var files = folder.getFilesByName(filename);
if (files.hasNext()) {
Drive.Files.update({}, files.next().getId(), a.copyBlob(), {supportsAllDrives: true});
} else {
folder.createFile(a.copyBlob()).setName(filename);
}
When this modified script is run, the existing file is searched from the folder using the filename of the attachment file. When the file is found, the file is overwritten by the attachment file. When the file is not found, the file is created as a new file.
Note:
In this modified script, the existing file is overwritten. So, please be careful about this. I would like to recommend using a sample file for testing the script.
Reference:
Files: update of Drive API v2

google script openByUrl autorization, trigger activation

I'm quite new to programming and struggling with apps authorization :
I created a code that has to access other files of my Gdrive, with the command openByUrl, which sends back an error message, telling me it doesn't have the authorization to perform openByUrl.
I went through the oauth2 scopes but can't understand how to give the authorization to my script.
I already have an internet copied script that runs DriveApp.getFolderById, but it runs through a menu.
I want both getFolderById and openByUrl to run on a trigger (each day at midnight) thus, it can't run through a menu.
The goal of my script is to list all files in a specified folder, get the spreadsheet ones, and extract specific cells from these spreadsheets.
I got something running with importance, but clearly, it's too bulky to run properly on more than 3000 files.
Could anyone explain to me how to give authorizations to openByUrl please? (even better if in French ;-) )
Many thanks in advance for your help.
Answer
I would create a new project and copy the whole code.
If you want to check why in a particular project you have this error, you can open the manifest file that has the required scopes. You can find it clicking on Project Settings on the left bar and then Show "appsscript.json" manifest file in editor. The field oauthScopes has to contain all the required scopes or has to be deleted.
Methods explanation:
DriveApp.getFoldersByName(name) get all the folders with a specified name. Take the first one with .next()
Folder.getFilesByType get all the files with a specific mimetype
SpreadsheetApp.openById open a specific Spreadsheet document
Spreadsheet.getSheets() get all the sheets in an array
Sheet.getRange() get a specific range
Range.getValues() get the values of a specified range
Updated code:
function main() {
var folderName = 'folder'
var type = MimeType.GOOGLE_SHEETS
var folders = DriveApp.getFoldersByName(folderName).next().getFolders()
while (folders.hasNext()) {
var folder = folders.next()
console.log(folder.getName())
var files = folder.getFilesByType(type)
while (files.hasNext()) {
var file = files.next()
console.log(file.getName() + ': ' + file.getid())
var sheets = SpreadsheetApp.openById(file.getid()).getSheets()
var values = sheets[0].getRange('A1:B2').getValues()
console.log(values)
}
}
}

File Iterator is moving phantom files

The app script I'm running to move files with a certain name in the title to a new folder is copying the same files every time the script is run. Removing the files from the source folder doesn't seem to work.
Form responses are collected in a spreadsheet and an add-on is used to put the responses into a form that generates a new Google doc. The Google Docs is for all of our various buildings, which each have a unique name. The script should iterate through the file names and add the file to the specific buildings folder and then remove it from the folder that has every building altogether. When I run the script, it works, but on subsequent runs, all of the files that were copied before keep getting copied again with any new files in addition to it.
function movePittsburghFiles() {
var sourceFolder=DriveApp.getFolderById('taqwdGs4MUEyUEl1WQ8');
var destFolder = DriveApp.getFolderById('taqwV085WTVtdTdf');
var files = DriveApp.searchFiles('title contains "3N - Pittsburgh Weekly"');
while (files.hasNext()) {
var file = files.next();
destFolder.addFile(file);
sourceFolder.removeFile(file);
}
The script works, but it keeps finding the same files in the source folder that were already moved in previous runs of the code and copying them again. When I go to the folder in Google Drive, those files are not listed, but somehow the script keeps finding them.
Issue:
You're searching the whole drive, When you're calling .searchFiles() on DriveApp.
Solution:
Call .searchFiles() on the sourceFolder instead.
Snippet:
var files = sourceFolder.searchFiles('title contains "3N - Pittsburgh Weekly"');
References:
Folder#SearchFiles

How do I delete a specific type of file (CSV files) within a specific folder with google app script on a shared google drive folder

I am having trouble adding files to the shared google drive folder as well as not being able to remove specific types of files of any kind within my script. The shared google drive file gives me issues. The code below works for me on my own personal google drive folder for adding and removing CSV's from one google drive folder to any another that I specify. However, it does not work with our general shared google drive folder. I have been authorized permission via the google cloud console API for Drive & Sheets but I am still having permission issues. Any help or clarification on this issue would be greatly appreciated.
Here are two different pieces of code. The first one with function moveFiles() works on my personal drive but not in the shared folders. Here is also some more code that I was playing around with to test the shared folders in a simpler manner. I was able to get the putFile() function to put a newDoc inside a shared google drive folder but not able to remove it.
function moveFiles(source_folder, dest_folder)
{
// set current destination to grab the folder from
var currentFolder=DriveApp.getFolderById("1emSsRay_WI_z_qBUpQIoccxQID28FvB0");
// grab only the csv's within current folder
var docs = DriveApp.getFilesByType(MimeType.CSV);
// set target destination where we will store old csv's that have been processed & Analyzed
var destination = DriveApp.getFolderById("1wYG1Gd5z0-nucedSMOBn8ZJs68ZgR8Hb");
// iterate through the csv's files within the currentFolder, add them to the destination and remove them from the current folder
while (docs.hasNext())
{
var doc = docs.next();
destination.addFile(doc); // get error "Cannot use this operation on a shared drive item(line 13, file "SharedDriveMove")
currentFolder.removeFile(doc);
}
}
function putFile()
{
var newDoc = DocumentApp.create('Testing Team Drive MoveTo').getId();
var file = DriveApp.getFileById(newDoc);
var moveFile = DriveApp.getFolderById('1emSsRay_WI_z_qBUpQIoccxQID28FvB0').addFile(file);
}
function takeFile()
{
var filesIterator = DriveApp.getFilesByName('Testing Team Drive MoveTo');
while (filesIterator.hasNext())
{
var file = filesIterator.next();
}
var cleanup = DriveApp.getFolderById('1wYG1Gd5z0-nucedSMOBn8ZJs68ZgR8Hb').addFile(file,{"supportsAllDrives": true}); // get error "Cannot find method addFile(File,Object).(line 15,file"Code")
var moveFile = DriveApp.getFolderById('1emSsRay_WI_z_qBUpQIoccxQID28FvB0').removeFile(file,{"supportsAllDrives": true});
}
DriveApp is an Apps Script class whereby it has it's limitations among Drive. Also, as the documentation says:
This method does not delete the file, but if a file is removed from
all of its parents, it cannot be seen in Drive except by searching for
it or using the "All items" view.
You should do it with the Drive API instead:
Use "supportsAllDrives", otherwise it won't find the file if it's in a Shared Drive (until this is deprecated in 2020).
Drive.Files.remove("your file ID", {"supportsAllDrives": true});
You also have to authorize the Drive.File scope.

Google Sheets - Script to “Replace” instead of “Create”, when file name is the same

EDIT to try and make this easier to understand:
Here is what I did:
I created a Google Spreadsheet. I created a SCRIPT that saves it to a Google Drive Folder using a File Name based on the date of service and Customer Name.
This is the Script I currently have:
// This creates a custom Menu Function so that I can save the file.
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Choice Menu')
.addItem('Submit Form','saveAsSpreadsheet')
.addToUi(); }
// Saves Spreadsheet in Google Drive Folder
function saveAsSpreadsheet() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var destFolder = DriveApp.getFolderById("0B8xnkPYxGFbUMktOWm14TVA3Yjg");
DriveApp.getFileById(sheet.getId()).makeCopy(getFilename(), destFolder);
}
//This Function uses a cell "G4" (Which is Date and Customer Name) to create a file name. This file name will be then used for the above Script.
function getFilename() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getSheetByName('Manifest');
var cell = sheet.getRange('G4');
var filename = cell.getValue();
return filename;}
So My code works GREAT except for one Problem.
Here is my Problem:
When I Save the Spreadsheet a 2nd time using the above Script, it saves a new file. I want to save it as a new file unless the Filename is the same. IF the file name is the same, I want to delete the original file, and then save the new file.
What I tried:
From what I understand reading the comments below, I need to run a code that "1. will need to run a query to see if any files exist with your chosen name, and then act accordingly. 2. If there are no files with that name, then go ahead and create one (using the function I listed above). If there is a file with the same name, 3. delete the original file and create a new one with the same name.
I tried for several days coming trying different options, and none of it worked, so I am looking to start over.
Appreciate any coding solutions or direction on where to go!
Your script is the container-bound script of Spreadsheet.
When the Spreadsheet with the searched filename is existing in a specific folder, you want to replace it to the active Spreadsheet.
In the current stage, a file cannot be replaced while the file ID is not changed. So in this modified script, the active Spreadsheet is copied and the searched file is deleted.
When the searched file is not existing in a specific folder, you want to copy the active Spreadsheet to the folder.
You want to use the value returned from getFilename() as the filename.
If my understanding is correct, how about this modification? I think that there are several solutions for your situation. So please think of this as just one of them.
Modified script:
Please modify saveAsSpreadsheet() as follows.
function saveAsSpreadsheet() {
var folderId = "0B8xnkPYxGFbUMktOWm14TVA3Yjg";
var folder = DriveApp.getFolderById(folderId);
var files = folder.getFilesByName(getFilename());
if (files.hasNext()) {
files.next().setTrashed(true);
}
var sheet = SpreadsheetApp.getActiveSpreadsheet();
DriveApp.getFileById(sheet.getId()).makeCopy(getFilename(), folder);
}
Note:
In order to search the file, I used getFilesByName() because I thought the filename seems constant.
setTrashed() for removing the file is used for this script. In this case, the file is put in the trash box. If you want to directly delete the file, you can achieve it using Drive API. At that time, please tell me.
References:
getFilesByName()
setTrashed()
Edit:
If you want to directly delete the file, please modify the script as follows.
From:
files.next().setTrashed(true);
To:
var params = {method: "delete", headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}};
UrlFetchApp.fetch("https://www.googleapis.com/drive/v3/files/" + files.next().getId(), params);
I used the method using UrlFetchApp because I thought that in your situation, Drive API has already been enabled. In this case, you can use the delete method of Drive API by only replacing the script.
Reference:
delete method of Drive API
You need to take a step back and change your thinking about filenames.
In GDrive, files are identified by their unique ID. The name is just a metadata property alongside timeModified, owner, mimeType, etc. So having multiple files with the same name is as natural as having multiple files with the same mimeType.
Your code will need to run a query to see if any files exist with your chosen name, and then act accordingly. If there are no files with that name, then go ahead and create one. If there are, then you have the choice to update the existing file, or delete the original file(s) and create a new one with the same name.