Merge n Google spreadsheets files to n sheets - google-apps-script

Say, I have 100 google spreadsheets file and I need to merge into one file with 100 tabs(sheets). Is it possible with app script. Currently I have a code below,
function popForm() {
var ss = SpreadsheetApp.getActive();
for(var b = 0; b<100; b++){
var sheet = ss.getSheetByName('Sheet '+b);
var numberRows = sheet.getDataRange().getNumRows();
....
....
The above code will work with spreadsheets with 100 tabs(Sheets). But I have 100 sreadsheets with one tab(Sheet).

Explanation:
You have a folder with FolderId that contains all the spreadsheet
files. You find this folder using the getFolderById() method.
You get the files of this folder using the getFiles() method and
you use a while loop to iterate over these files.
For every file, you get the first sheet and you copy it using the
copyTo() method to the source (active) spreadsheet file.
The newly create sheet will be named after the name of the spreadsheet file that it came from. Feel free to change this part or let me know so I can modify it.
Solution:
You must be looking for this:
function myFunction() {
const source_sh = SpreadsheetApp.getActive();
const folder = DriveApp.getFolderById('FolderId');
const files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
var target_ss = SpreadsheetApp.openById(file.getId());
var target_sh = target_ss.getSheets()[0];
target_sh.copyTo(source_sh).setName(file.getName());
}
}

Related

App Script for saving a sheet as PDF to a specific folder

I am looking for an app script that lets me save a sheet as PDF from my Google Workbook to a specific folder in Google Drive based on a condition.
In my Google Drive I have a Google Sheet Workbook file and an employee folder.
The employee folder Id is 1Jy2Yr7u0qrgy90Gvtb6p8V27baS7T_eP
My google workbook has a sheet called 'Sheet2' whose Id is 1DmDBmEijUkolVp7aVgGNK4cTRu5y4uLdzbCrDYO5XRA.
This sheet has a cell C3 that has an employee name. The value in this cell needs to be checked, i.e. if the employee name matches then the script should convert the sheet to a PDF format and place the PDF in employee folder.
I am not a programmer or a coder but doing my best to get this working. I went through many scripts that I found here in stackoverflow and in Youtube and came up with this. I am not sure if it is correct. Need some expert help. Hoping someone can help.
function checkSheet() {
var sheetName = "1DmDBmEijUkolVp7aVgGNK4cTRu5y4uLdzbCrDYO5XRA";
var folderID = "1Jy2Yr7u0qrgy90Gvtb6p8V27baS7T_eP";
var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var folder = DriveApp.getFolderById(folderID);
var checkForNews = spreadsheetApp.getActiveSpreadsheet().getSheetByName("Tracking").getRange("c6").getValue();
if (checkForNews='Yes') {
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf", folder));
var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
var newFile = folder.createFile(theBlob);
}
}
Here are the resource that I found,
Using Google Apps Script to save a single sheet from a spreadsheet as pdf in a specific folder
How to check for cell value?
How can I modify this to save a spreadsheet into a new folder
As mentioned above I came up with that script which I think is not right. Please help.
Try it this way:
function checkSheet() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Tracking");
var fldr = DriveApp.getFolderById("folder id");
if(sh.getRange("C6").getValue() == "Yes") {
var theBlob = ss.getBlob().getAs('application/pdf').setName("mypdf");
fldr.createFile(theBlob);
}
}

Google Apps Script, Google Sheets - Getting Spreadsheet ID and Sheet ID programmatically

I've been reading this without making any headway:
https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app
Is there a way to programmatically get the Spreadsheet ID and Sheet ID of a particular Google SpreadSheet's sheet without manually typing or copying the URL?
1.) If the script is bound to the spreadsheet then you can just use getID and getSheetID as mentioned by TheMaster in the comments. See codes below:
function getIDs() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var spreadSheetID = ss.getId();
var sheetID = sheet.getSheetId();
console.log(spreadSheetID);
console.log(sheetID);
}
Result:
Take note that the first sheet always has an ID of 0 (gid=0) as the default value.
2.) Otherwise if what you are trying to do is get the Spreadsheet ID and Sheet ID from different spreadsheets it is not possible without copying the URL since there is no way it can identify which spreadsheet to refer to.
3.) Suggestion
What you can do if you need to get IDs of different files is to move them to a folder in your drive, then you can use the code below:
function listFilesInFolder(folderName) {
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(1,1,sheet.getLastRow(),sheet.getLastColumn()).clearContent();
sheet.appendRow(["Name", "Spreadsheet ID", "Sheet ID"]);
//change the folder ID below to reflect your folder's ID (look in the URL when you're in your folder)
var folder = DriveApp.getFolderById("HIS_SHOULD_BE_YOUR_FOLDER_ID");
var contents = folder.getFiles();
var cnt = 0;
var file;
while (contents.hasNext()) {
var file = contents.next();
cnt++;
data = [
file.getName(),
file.getId(),
];
var spreadsheetSheets = SpreadsheetApp.openById(data[1]).getSheetByName("Sheet2").getSheetId();
data.push(spreadsheetSheets);
sheet.appendRow(data);
};
};
Folder:
Result:
Note: In my example code I've made use of Sheet2 to see that it is working as expected. Please set accordingly to the name of the sheet which you are trying to get the ID.
Let me know if this works for you or if you have other questions.
References:
Are Google Spreadsheets' first sheets always given an ID of 0?
Getting all files ID in drive folder

Google Sheets - copy 2 spreadsheets into specific folder with specific name

I have spreadsheet with multiple sheets inside. I'd like to make a macro which would copy two specific sheets into another spreadsheet and name it using format "MYNAME_YYYY_MM_DD" where YYYY_MM_DD is replaced with the date on which macro was ran.
So far i have this:
function X() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('INPUT'), true);
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('OUTPUT'), true);
};
Copy two spreadsheets into a folder
function lfunko() {
const ss0 = SpreadsheetApp.openById("id0");
const ss1 = SpreadsheetApp.openById("id1");
const file0 = DriveApp.getFileById(ss0.getId());
const file1 = DriveApp.getFileById(ss1.getId());
const folder = DriveApp.getFolderById("folderid");
file0.makeCopy(`myname${Utilities.formatDate(new Date(),Session.getScriptTimeZone(),"yyyy_MM_dd")}`,folder);
file0.makeCopy(`myname${Utilities.formatDate(new Date(),Session.getScriptTimeZone(),"yyyy_MM_dd")}`,folder);
}

Get Spreadsheets from a folder and modify them

I have a folder called "Adform" in my Drive and I want to take all the spreadsheets from there and modify them by adding new columns, change headers.
At this point I managed to get the files name, one by one, but I don't know how to use SpreadSheetApp to modify those Spreadsheets.
var folders = DriveApp.getFoldersByName('Adform');
while (folders.hasNext()) {
var files = folders.next().getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
}
}
How to loop through all the Spreadsheets in a Drive folder
You are almost there. The best way in my opinion is to check if the mime type of the file is application/vnd.google-apps.spreadsheet, and if so, get the id. Then pass this id to another function that will modify the Spreadsheet in any way that you want.
function myFunction() {
var folders = DriveApp.getFoldersByName('Adform');
while (folders.hasNext()) {
var files = folders.next().getFiles();
while (files.hasNext()) {
var file = files.next();
// Check if file is a spreadsheet
if (file.getMimeType() === "application/vnd.google-apps.spreadsheet") {
// Call the function to modify the spreadsheet with the file id
modifySpreadhsheet(file.getId())
}
}
}
}
function modifySpreadsheet(id) {
// Open the file with the id
var file = SpreadsheetApp.openById(id);
// Get all the sheets
var sheets = file.getSheets()
// Get the first sheet
var firstSheet = sheets[0]
// Get the range that contains all the data in that sheet
var range = firstSheet.getDataRange();
// Get all the values in that range
var values = range.getValues();
Logger.log(values)
}
This sample function will just get the first sheet of the spreadsheet and then Log all the data within that spreadsheet to the logger.
Then you can use functions like setValues(values) to modify the content as needed.
References
getMimeType()
getId()
openById(id)
getSheets()
getDataRange()
getValues()

Get list of folders on Gsuite google drive, list them alphabetically on a Google Sheet

Trying to get a list of folders (not sub folders or files) in a Gsuite shared drive to populate a Google Sheet worksheet, but the script below fails after first time and will not overwrite the list when I re-run.
I have tried quite a few variations, but my problem is:
1. I would love to have a 3rd column produced showing the html
2. Script works once, but when I refresh or place a trigger on the sheet it no longer works or updates.
Here is my current code:
function listFilesInFolder(folderName) {
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow(["Name", "File-Id"]);
//change the folder ID below to reflect your folder's ID (look in the URL when you're in your folder)
var folder = DriveApp.getFolderById("0ADTcDD3ZSaa5Uk9PVA");
var contents = folder.getFolders()
var cnt = 0;
var file;
while (contents.hasNext()) {
var file = contents.next();
cnt++;
data = [
file.getName(),
file.getId(),
];
sheet.appendRow(data);
};
};
Any suggestions on how to:
1. Get the folder list to update each hour on the Google sheet?
2. Fix error where the folder list is not updating/overwriting?
3. Add the html of each folder into a third column?
4. Have the list produced in alphabetical order?
Many thanks in advance if you have made it this far!
function listFoldersInAFolder() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
sh.clearContents();
sh.appendRow(["Name", "Folder-URL"]);
var fA=[];
var folders=DriveApp.getFolderById("folder id").getFolders();//Enter folder id
while (folders.hasNext()) {
var folder= folders.next();
fA.push([folder.getName(),folder.getUrl()]);
}
sh.getRange(sh.getLastRow()+1,1,fA.length,2).setValues(fA);
sh.getRange(2,1,sh.getLastRow()-1,2).sort({column:1,ascending:true});
}
If you want to get all folders and sub folders you will have to recurse them. Here's an example of that: https://stackoverflow.com/a/55248127/7215091