Google Drive - Automating creating multiple folders and documents templates - google-docs

Our organization creates the same folder structure with templated documents for each job. Right now staff manually creates each folder and within those folder creates each document from a template in the organizations template gallery. Is there a simple-ish way to automate this?

This is how I would approach this if you would want to create a simple automated sheet script for it.
function createFolder() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var getFolderID = ss.getRange('A2').getValue();
var setFolderName = ss.getRange('B2').getValue();
var setDocName = ss.getRange('C2').getValue();
var setTemplate = ss.getRange('D2').getValue();
var drive = DriveApp;
var parentfolder = drive.getFolderById(getFolderID);
var newFolder = parentfolder.createFolder(setFolderName);
var createDoc = DocumentApp.create(setDocName);
var getDocID = createDoc.getId();
drive.getFileById(getDocID).moveTo(newFolder).setContent(setTemplate);
}
What this does is I created a sheet template like this:
Set the Parent Folder ID on cell A2 which you can find on the folder URL "https://drive.google.com/drive/folders/{parentfolderID}?resourcekey"
Set the folder name on cell B2, as well as the document name on C2 and your template on D2.
You can run the script by going into Tools > Script Editor, or you can assign an image to act as a button and assign the script to that image.
Running the script would result into this folder hierarchy
with the value of D2 inside the Google Doc.
References:
https://developers.google.com/apps-script/reference/document/document-app
https://developers.google.com/apps-script/reference/drive/drive-app
https://developers.google.com/apps-script/reference/spreadsheet/sheet

Related

How do I add a script to a Google Sheet to automatically take data from an XLSX file on Google Drive?

I'm trying to automatically update a Google Sheet from a separate XLSX file, since the XLSX file gets regularly updated, but I need to do some data cleaning. I tried doing a query and importrange neither of which can get data from an xlsx file.
It seems like I need to write a script on the Google Sheet to automatically take the data from the xlsx. Where do I add this, and how would I go about getting started? I have access to both files, so permissions shouldn't be an issue.
Suggestion: Temporarily Convert the Excel File to Google Sheets File to Extract Data
Unfortunately, there is no direct way to extract data from Excel files to Google Sheets using Google Apps Script. As a workaround, you need to first convert your excel file to Google Sheets and then extract the data from the converted file to your output Google Sheets file. You may use the following script as a basis for yours:
function importData() {
var xlsxName = "Test 1.xlsx"; //Change source file name accordingly
var convertID = convert(xlsxName).toString();
var xLSX = SpreadsheetApp.openById(convertID).getSheetByName("Input");
var ss = SpreadsheetApp.openById("<output Sheet ID>").getSheetByName("Output"); //Change output sheet ID
var lastColumn = xLSX.getLastColumn();
var lastRow = xLSX.getLastRow();
ss.getRange(1, 1, lastRow, lastColumn).setValues(xLSX.getDataRange().getValues()); //Sets values from converted xlsx data to output sheet
DriveApp.getFileById(convertID).setTrashed(true); //deletes temporary file
}
function convert(excelFileName) {
var files = DriveApp.getFilesByName(excelFileName);
var excelFile = (files.hasNext()) ? files.next() : null;
var blob = excelFile.getBlob();
var config = {
title: "[Converted File] " + excelFile.getName(), //sets the title of the converted file
parents: [{ id: excelFile.getParents().next().getId() }],
mimeType: MimeType.GOOGLE_SHEETS
};
var spreadsheet = Drive.Files.insert(config, blob);
return (spreadsheet.id); //Returns the ID of the converted file
}
This script involves:
Converting the Excel file to a temporary Google Sheets file.
Importing the data from the temporary Google Sheets file to the desired/output Google Sheets file.
Deleting the temporary Google Sheets file.
NOTE:
Expect a longer runtime when applying this script to a bigger excel file.
You may modify the script to be suitable for your current issue.
The script should be added to your desired output Google Sheets.
Do not forget to add the Drive API service to your script.
Sample Test Case:
Input:
Expected Output:

How do I convert the excel files into spreadsheet files without changing the existing excel files type in google drive folder?

In a google sheet, I managed to filter file name and file type and list all the particular files needed from a google drive folder based on the conditions into a spreadsheet. I am having an issue to convert the excel files into spreadsheet because I'm opening the selected files using "SpreadsheetApp.openById(id)" in another function() to get the data range from the specific files.
Based on the requirement set, I was been asked to convert the excel files into spreadsheet before getting the range data and export those data into another sheet.
Below are the codes that i created to list the file name and file type, so i believe that the file conversion method might need to be implemented here as well because it involves the file filtering process and these are the files need to be converted later on. Please correct me if I am wrong.
function getChildFiles(parentName, parent, sheet) {
var fileIter = parent.searchFiles("title contains 'completed'and title contains 'Verification
Visit Direct Suppliers'and mimeType='application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet'");
var output = [];
var now = new Date();
var date = new Date();
var copy = new Date(date);
while (fileIter.hasNext()) {
var file = fileIter.next();
var fileName = file.getName();
var fileType = file.getMimeType();
var filecreatedate = file.getDateCreated();
var fileUpdate = file.getLastUpdated()
var path = parentName + ' |--> ' + fileName;
var fileID = file.getId();
var Url = 'https://drive.google.com/open?id=' + fileID;
output.push([fileID, fileName, path, Url,filecreatedate,fileUpdate,copy]);
Logger.log(fileType);}
if (output.length) {
var last_row = sheet.getLastRow();
sheet.getRange(last_row + 1, 1, output.length, 7).setValues(output);
SpreadsheetApp.flush();}
var childFolders = parent.getFolders();
while (childFolders.hasNext()) {
var childFolder = childFolders.next();
var childFolderName = childFolder.getName();
getChildFiles( parentName + ' |--> ' + childFolderName, childFolder, sheet);}}
So I'm trying to implement the file conversion method from excel file to spreadsheet, so that i can extract data from the excel file after the file successfully converted to spreadsheet.

How to overwrite an excel file to a fix ID google sheet

I need to overwrite with an Excel file a fixed Google spreadsheet that keep both file ID and sheet ID .
Here below the code written in Google Apps Script that works but everytime generate a new id for the sheet.
function overwrite() {
const xlsxFileName = "XXX.xlsx"; // Please set the filename of XLSX file.
const spreadsheetId = "1JnsV5Vpp0xXj1fNyDeKV04PReYGN4v2oBVcQb6bvBUA"; // Please set the Spreadsheet ID. This Spreadsheet is overwritten by EXCEL data.
const xlsx = DriveApp.getFilesByName(xlsxFileName || "XXX.xlsx");
if (!xlsx.hasNext()) throw new Error("No excel file.");
Drive.Files.update({mimeType: MimeType.GOOGLE_SHEETS}, spreadsheetId, xlsx.next().getBlob());
}
My need is to import the information included in a specific Excel sheet into a specific sheet in Google Sheet. My goal is to be able to keep the spreadsheetID and sheetID in order to be able to link a dashboard in Google Data Studio with automatic update.
Basically you want a spreadsheet which sync with excel file and whenever the data update in Excel file, spreadsheet will update without change it's sheet id and use that spreadsheet to create a report on Looker (formerly Google Data Studio).
What exactly logic use
Create two spreadsheets :
[An excel file convert to the google spreadsheet with updation gid everytime when excel file updates ] (use Apps Script)
[Import data from converted file to new or second google spreadsheet] (use Apps Script).
When you import data to new spreadsheet, the sheet id will never change and you can also use it on Looker.
var dstFileId = 'File_id'; // file Id of Existing Spreadsheet
function convertExceltoGoogleSpreadsheet(fileName) {
fileName = fileName || "excelfile.xlsx"; // excel_file_name.xlsx = name of specific Excel file
var excelFile = DriveApp.getFilesByName(fileName).next();
var fileId = excelFile.getId();
var srcFileId = fileId; // file Id of Excel file
Drive.Files.update({}, dstFileId, DriveApp.getFileById(srcFileId))
};
Upper code for 1st spreadsheet (for convert excel file to google spreadsheet)
****** must add Drive API service ******
var sourceSpreadsheetID = "id_of_1st_spreadsheet";
var sourceWorksheetName = "name_of_worksheet_of_1st_spreadsheet";
var targetSpreadsheetID = "id_of_2nd_spreadsheet";
var targetWorksheetName = "name_of_worksheet_of_2nd_spreadsheet";
function importData() {
var thisSpreadsheet = SpreadsheetApp.openById(sourceSpreadsheetID);
var thisWorksheet = thisSpreadsheet.getSheetByName(sourceWorksheetName);
var thisData = thisWorksheet.getDataRange();
var toSpreadsheet = SpreadsheetApp.openById(targetSpreadsheetID);
var toWorksheet = toSpreadsheet.getSheetByName(targetWorksheetName);
var toRange = toWorksheet.getRange(1, 1, thisData.getNumRows(),
thisData.getNumColumns())
toRange.setValues(thisData.getValues());
}
this code for second spreadsheet (import data from 1st spreadsheet without change the sheet id)
Now you can use this new spreadsheet for create your report on Looker

Move file & Rename File in Google Drive

I try to write script on Google Sheet to trigger below action.
Move a target file from root (my drive) to the destination folder then rename it in the destination folder.
Below items will be put on google sheet . I want to create a formula function to trigger the script action once below items are provide on google sheet.
Target file name
Name ID for rename
Below script works perfectly (for move file action); i would like alter below script to accomplish above action.
function copyFiles(source_folder, dest_folder) {
var source_folder = DriveApp.getFolderById(id);
var dest_folder = DriveApp.getFolderById(id);
var files = DriveApp.getFilesByName(id);
while (files.hasNext()) {
var file = files.next();
dest_folder.addFile(file);
source_folder.removeFile(file);
}
}
Thank you!!
If you just want to rename your file, you should have a look at File classe, on File.setName(name) method.
Otherwise, you question is a bit unclear and need some explanations/examples of what you trying to do.

Font and Alignment script not running

I have a spreadsheet that has information entered by multiple people on multiple devices and different font settings. I would like a simple script to change all pages of the spreadsheet, (3 on test but actually 5 pages on original). Preferably on any edit, but when you switch from page to page within the sheet would be fine.
Here is link to spreadsheet:-
https://docs.google.com/spreadsheets/d/1hUSgX4Teg71sgI6AUlxgY7HCatUTAszP3M4f6o_eyMU/edit?usp=sharing
My script below:-
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets();
var cell = sheet.getRange("C6:P26");
cell.setFontSize(12);
cell.setHorizontalAlignment("center");
}
I have tried onEdit too but still not working but debugger is not throwing up errors just not running. Not sure if it is the Range option as it doesn't select the correct area in each sheet, should I make 1 per sheet?
Here is the working code after many tries.
function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets();
var cell = ss.getRange("C6:U39");
cell.setFontSize(12);
cell.setHorizontalAlignment("center");
}

Resources