Copying active spreadsheet to all spreadsheet documents in a folder - google-apps-script

I am attempting to copy an individual spreadsheet to all spreadsheet files within a folder. I could not figure out how to do it, so I am using a previous code I found that lists all of the files, but it ends up listing all of the files in my drive, not just in that folder.
Could I get assistance either in making a script to copy it to all files in a specific folder, or change it so that the below code shows only that of the folder it is in? From what I have seen/changed DriveApp.getFiles() should only be listing those files in the folder?
function List()
{
var app = UiApp.createApplication();
app.setTitle("Copy Sheet in Multiple Spreadsheets");
var form = app.createFormPanel();
var flow = app.createFlowPanel();
var label = app.createLabel("Select Spreadsheet where you want to copy the current sheet:").setId('selectLabel');
flow.add(label);
var allfiles = DriveApp.getFiles();
var verticalPanel = app.createVerticalPanel().setId('verticalPanel');
var i = 0;
while (allfiles.hasNext())
{
var file = allfiles.next();
var temp = app.createCheckBox(file.getName()).setName('cb'+i).setId('cb'+i);
var tempvalue = app.createHidden('cbvalue'+i, file.getId());
verticalPanel.add(temp);
verticalPanel.add(tempvalue);
i++;
}
var scrollPanel = app.createScrollPanel().setId('scrollPanel');
scrollPanel.add(verticalPanel);
scrollPanel.setSize("400", "250")
flow.add(scrollPanel);
var buttonsubmit = app.createSubmitButton("Copy");
flow.add(buttonsubmit);
form.add(flow);
app.add(form);
SpreadsheetApp.getActiveSpreadsheet().show(app);
return app;
}
function doPost(eventInfo) {
var app = UiApp.getActiveApplication();
var allfiles = DriveApp.getFiles();
var tempSsId = "";
var i = 0;
while (allfiles.hasNext())
{
var temp = eventInfo.parameter['cb'+i];
if(temp == 'on')
{
tempSsId = eventInfo.parameter['cbvalue'+i];
var activeSheet = SpreadsheetApp.getActiveSheet().copyTo(SpreadsheetApp.openById(tempSsId));
activeSheet.setName(SpreadsheetApp.getActiveSheet().getSheetName());
}
i++;
}
var label = app.createLabel('statusLabel');
label.setText("Copied Active sheet in all selected Spreadsheets...");
label.setVisible(true);
app.add(label);
return app;
}

DriveApp.getFiles(); will get every file in your Drive.
DriveApp.getFolderById('folder id').getFiles(); If you want to get files in a specific folder (this will get the files in that folder but not in subfolders).
This script has nothing to do with the question you asked and I think you may have worded your question incorrectly.
Do you mean you are attempting to copy an individual sheet from a spreadsheet to all of the other spreadsheets in a particular folder?
EDIT
function copyTo() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetName = ''; // ENTER THE NAME OF THE SHEET YOU WANT TO COPY
var targetFolder = DriveApp.getFolderById(''); //ENTER THE ID OF THE TARGET FOLDER HERE
var sheet = ss.getSheetByName(sheetName);
var getFiles = targetFolder.getFiles();
while (getFiles.hasNext()) {
var file = getFiles.next();
if (file.getMimeType() == 'application/vnd.google-apps.spreadsheet') {
var targetSheet = SpreadsheetApp.openById(file.getId());
sheet.copyTo(targetSheet).setName(sheetName);
}
}
}

Related

Copy a Google sheet to multiple spreadsheets in a folder using the Folder ID

I currently have a script that I'm using, which I based on a script that I found, to copy a Google sheet to all the other Spreadsheets that are in the same Google Drive folder. I'd like to modify this to copy the sheet to all the other Spreadsheets that are in a different folder using the folder ID. I've tried modifying the var folderFiles to use the DriveApp.getFolderByID to direct it to a specific folder but just keep getting errors. I'm more of a novice so any help or guidance would be greatly appreciated.
function copySheetVA() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getActiveSheet();
var sourceFile = DriveApp.getFileById(source.getId());
var sourceFolder = sourceFile.getParents().next();
var folderFiles = DriveApp.getFolderById('1zZDvtFzIvmD-7Z5f5Sbi4G3-XXXXX');
var thisFile;
while (folderFiles.hasNext()) {
thisFile = folderFiles.next();
if (thisFile.getName() !== sourceFile.getName()){
var currentSS = SpreadsheetApp.openById(thisFile.getId());
var actualSheetName = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
sheet.copyTo(currentSS);
currentSS.getSheets()[currentSS.getSheets().length-1].setName(actualSheetName);
}
};
}
I updated your code and tested it on my end.
The fix is to call getFiles() after get the folder,
var folderFiles = DriveApp.getFolderById('YOUR_FOLDER_ID').getFiles();
function copySheetVA() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getActiveSheet();
var sourceFile = DriveApp.getFileById(source.getId());
var folderFiles = DriveApp.getFolderById('YOUR_FOLDER_ID').getFiles();
while (folderFiles.hasNext()) {
var thisFile = folderFiles.next();
if (thisFile.getName() !== sourceFile.getName()){
var currentSS = SpreadsheetApp.openById(thisFile.getId());
var actualSheetName = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
sheet.copyTo(currentSS);
currentSS.getSheets()[currentSS.getSheets().length-1].setName(actualSheetName);
}
};
}

Google Apps Script - Move folder from Root not working

I have the following code in a Spreadsheet app that:
Creates a folder in a given location;
Finds and copies a set of template folders and files from a master directory;
Moves them into the folder created in step 1.
However, periodically, the template folders are not moved during step 3 and remain under the Root. It seems to consistently happen with one specific set of templates that contains 21 folders and 38 files with a total size of 2.64 MB.
There are no errors that are highlighted in the App Script editor. The script message ends as expected.
Can anyone suggest why this may be happening and help with the code to prevent this from occurring.
Update: When this error occurs, I am left with a copy of the template folder in the Root of MyDrive. If I then run the 'moveFolder()' function on its own the problematic template folder move works 100%.
My Code:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Admin')
.addItem('Create Project', 'createProjectFolder')
.addItem('Get Template Folder', 'start')
.addItem('Move Template Folder', 'moveFolder')
.addToUi();
}
//******************************************************************************** */
//Create new Project Folder
//******************************************************************************** */
function createProjectFolder(FolderName, TargetFolder)
{
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName('Config');
var newFolderName = sh.getRange('NewProjectName').getValue();
//Change 'parentFolder' ID to the Verification Projects
var parentfolder = DriveApp.getFolderById('ID'); //Folder ID of Verification Projects folders
var newFolder = DriveApp.createFolder(newFolderName);
var currentFolders = newFolder.getParents();
while (currentFolders.hasNext())
var currentFolder = currentFolders.next();
currentFolder.removeFolder(newFolder);
parentfolder.addFolder(newFolder);
var newFolderID = newFolder.getId();
Logger.log(newFolderID)
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var configSheet = spreadSheet.getSheetByName('Config');
var range = configSheet.getRange('NewProjectNameID').setValue(newFolderID);
start();
return newFolderID;
}
//**************************************************************** */
//Copy master folder structure
//**************************************************************** */
function start() {
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var configSheet = spreadSheet.getSheetByName('Config');
var sourceFolder = configSheet.getRange('SourceFolder').getValue();
var targetFolder = configSheet.getRange('ProjectFolderLibraryName').getValue();
Logger.log(sourceFolder);
Logger.log(targetFolder);
var source = DriveApp.getFoldersByName(sourceFolder);
var target = DriveApp.createFolder(targetFolder);
if (source.hasNext()) {
copyFolder(source.next(), target);
}
}
function copyFolder(source, target) {
var folders = source.getFolders();
var files = source.getFiles();
while (files.hasNext()) {
var file = files.next();
file.makeCopy(file.getName(), target);
}
while (folders.hasNext()) {
var subFolder = folders.next();
var folderName = subFolder.getName();
var targetFolder = target.createFolder(folderName);
copyFolder(subFolder, targetFolder);
}
moveFolder();
}
function moveFolder(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('Config');
var folderName = sh.getRange('ProjectFolderLibraryName').getValue();
Logger.log(folderName);
var folderNameID = sh.getRange('NewProjectNameID').getValue();
Logger.log(folderNameID);
var folder = DriveApp.getFoldersByName(folderName).next();
var destination = DriveApp.getFolderById(folderNameID);
destination.addFolder(folder);
folder.getParents().next().removeFolder(folder);
}
This has been resolved. I was calling the next function from within the current function. I suspect that the call to execute the next function was placed too early and conflicts then arose.
Solution: I created a separate function that contained the functions in order. This allowed each function to complete before the next was executed.
EG:
function allFunctions(){
function1();
function2();
function3();
}

Populate Google sheet with file names from folder on Google drive and add checkbox Google Script

Can anyone help me with a script I am currently butchering to import file names into a sheet and add a checkbox to the appended row...
I am trying to get the file names into K7:K with a checkbox next to it in L7:L, Ive been playing around for hours and decided I may as well swallow my pride and ask a silly question on here!
My current code is:
function listFilesInFolder(folderName) {
SpreadsheetApp.getActive().toast("Populating Register...");
var sheetName = "Register"
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
//change the folder ID below to reflect your folder's ID
var folder = DriveApp.getFolderById("18KVczz-XW_3OSmCsVVIxd8p38maDzNm3");
var contents = folder.getFiles();
var cnt = 0;
var file;
while (contents.hasNext()) {
var file = contents.next();
cnt++;
data = [
file.getName(),
];
sheet.appendRow(data);
var checkbox = SpreadsheetApp.newDataValidation().requireCheckbox().build();
sheet.getRange("L:L").setDataValidation(checkbox).setValue("FALSE");
}
}
Obviously, its pretty far off, if anyone could help me out I'll be forever grateful! :)
Try this
function listFilesInFolder(folderName) {
SpreadsheetApp.getActive().toast("Populating Register...");
var sheetName = "Register"
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var folder = DriveApp.getFolderById("18KVczz-XW_3OSmCsVVIxd8p38maDzNm3");
var contents = folder.getFiles();
var cnt = 0;
var file;
while (contents.hasNext()) {
var file = contents.next();
cnt++;
sheet.getRange("K"+(6+cnt)).setValue(file.getName());
}
var checkbox = SpreadsheetApp.newDataValidation().requireCheckbox().build();
sheet.getRange("L7:L"+(6+cnt)).setDataValidation(checkbox).setValue("FALSE");
}
If you want to add new data :
function listFilesInFolder(folderName) {
SpreadsheetApp.getActive().toast("Populating Register...");
var sheetName = "Register"
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var folder = DriveApp.getFolderById("18KVczz-XW_3OSmCsVVIxd8p38maDzNm3");
var contents = folder.getFiles();
var cnt = sheet.getLastRow();
var file;
while (contents.hasNext()) {
var file = contents.next();
cnt++;
sheet.getRange("K"+(cnt)).setValue(file.getName());
}
var checkbox = SpreadsheetApp.newDataValidation().requireCheckbox().build();
sheet.getRange("L7:L"+(cnt)).setDataValidation(checkbox).setValue("FALSE");
}

How to write google script to automatically call data from a google folder drive that contains a CSV file into one Google Sheets

I am trying to write a google script that will allow me to go into my google drive folder called "MeadJohsnon" and pull 'Temperature Calibration.csv' to google sheets. I have never used google script before. Currently I have the "Save Email and Attachment" Add-ons. This add-on is pulling .cvs files that my team is sending me from the field. They use "TapForms" and then send the form via email to my gmail. So, I got the email sending that attachment to my google drive but I need help with the script, so Drive will automatically get those .cvs files and put the information into one google sheet. I say ONE google sheet because although I have a team sending in forms, all the forms have the same information on them.
This is what I have done so far. The fourth line gives me a
function loadingCSV() {
var ss=SpreadsheetApp.getActiveSpreadsheet()
var sht=ss.getActiveSheet();
sht.clearContents();
var data = loadFile();
var dataA =Utilities.parseCsv(data);
var rng = sht.getRange(1, 1, dataA.length, dataA[0].length);
rng.setValues(dataA);
}
I would just like feedback on how to fix my error or what I could do instead. As stated this is my first time using google script, my specialty is ASP.net lol not script. Thank you.
function loadingCSV() {
var ss=SpreadsheetApp.getActiveSpreadsheet()
var sht=ss.getActiveSheet();
sht.clearContents();
var data = loadFile();
var dataA =Utilities.parseCsv(data);
var rng = sht.getRange(1, 1, dataA.length, dataA[0].length);
rng.setValues(dataA);
}
function loadFile(filename,folderID)
{
var filename = (typeof(filename) !== 'undefined')? filename : 'Temperature Calibration.csv';
var folderID = (typeof(folderID) !== 'undefined')? folderID : '0B8m9xkDP_TJxUUlueHhXOWJMbjg';
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var s = '';
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
s = fi.getBlob().getDataAsString();
}
}
return s;
}
Okay this will append the files to the active spreadsheet you'll probably have to open the spreadsheet by id and use getSheetByName to get the sheet you want because this spreadsheet probably won't be active all the time when the trigger is running. I assume the the files all end in .csv. I rename them to .old after reading the data so that the program won't read them multiple times.
function appendingCSV() {
var ss=SpreadsheetApp.getActiveSpreadsheet()
var sht=ss.getActiveSheet();
var drng = sht.getDataRange();
var lastRow = drng.getLastRow();
var data = loadFiles();
var dataA =Utilities.parseCsv(data);
if(dataA.length>0)
{
var rng = sht.getRange(lastRow + 1, 1, dataA.length, dataA[0].length);
rng.setValues(dataA);
}
else
{
SpreadsheetApp.getUi().alert('No Data Returned from LoadFiles');
}
}
function loadFiles(folderID)
{
var folderID = (typeof(folderID) !== 'undefined')? folderID : '0B8m9xkDP_TJxUUlueHhXOWJMbjg';
var fldr = DriveApp.getFolderById(folderID);
var files = fldr.getFiles();
var s='';
var re = /^.*\.csv$/i;
while (files.hasNext())
{
var file = files.next();
var filename = file.getName();
if(filename.match(re))
{
s += file.getBlob().getDataAsString() + '\n';
file.setName(filename.slice(0,-3) + 'old');
}
}
return s;
}

A script to copy one sheet to various spreadsheets in a specific folder in Google Drive

I have a sheet which I need to copy to hundreds of spreadsheets in a given folder in Google Drive. I am just beginning with script and I do not know how to proceed because the script below just gives me an error. Thanks.
function myFunction() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[0];
var folder = DriveApp.getFoldersByName('TEST FOR SCRIPT');
var contents = folder.getFiles();
for (var i = 0; i < contents.length; i++) {
file = contents[i];
}
sheet.copyTo(contents).setName('ANSWERS');
}
I was given this answer by someone within a community in Google+ and it works:
function copyToSheets() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[1];
var folders = DriveApp.getFoldersByName('ID');
var firstFolder = folders.next();
var folderFiles = firstFolder.getFiles();
var thisFile;
while (folderFiles.hasNext()) {
thisFile = folderFiles.next();
var currentSS = SpreadsheetApp.openById(thisFile.getId());
sheet.copyTo(currentSS);
currentSS.getSheets()[currentSS.getSheets().length-1].setName('NAME');
}
}
This line of code:
var folder = DriveApp.getFoldersByName('TEST FOR SCRIPT');
returns a FolderIterator. Even if you only have one folder by that name, the getFoldersByName() method returns an object, that you can't use the getFiles() method on directly. The getFiles() method works on the Files Class. It is not available to the Folder Iterator. After you get the Folder Iterator, you must use the next() method to get the first (and probably only) folder in the object.
function getAllFilesInFolder() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[0];
var folders = DriveApp.getFoldersByName('Folder Name Here');
var firstFolder = folders.next();
var folderFiles = firstFolder.getFiles();
var thisFile;
while (folderFiles.hasNext()) {
thisFile = folderFiles.next();
Logger.log(thisFile.getName());
};
};
And also use hasNext() to loop through the files. There doesn't seem to be an length property of the Files object.