I am working on a script to copy all the all data from sheets saved in a folder and concatenate them to a single spreadsheet.
The variable combinedData is not returning any data when I run it through the logger outside the while loop. Any ideas why this is happening?
// DATA CONCATINATION
function Data_concat() {
var folder = DriveApp.getFolderById("1Rky5tOyrTMJ15uhTog1ltBMwONap7Rx1");
var filesIterator = folder.getFiles();
var file;
var filetype;
var ssID;
var combinedData = [];
var data;
while(filesIterator.hasNext()){
file = filesIterator.next();
filetype = file.getMimeType();
if(filetype === "application/vnd.google-apps.spreadsheet"){
ssID = file.getId();
data = getDatafromSS(ssID);
combinedData = combinedData.concat(data);
}//end of if
}//end of while
Logger.log(combinedData)
//var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("raw_Data");
//ws.getRange("A2:J").clearContent();
//ws.getRange(2,1,combinedData.length, combinedData[0].length).setValues(combinedData)
}//end of Data_concat
//GET DATA FROM TARGET SHEET
function getDatafromSS(ssID){
var ss = SpreadsheetApp.openById(ssID);
var ws = ss.getSheets()[0];
var data = ws.getRange("A2:G" + ws.getLastRow()).getValues();
return data;
}
Save Data in all Spreadsheets in a folder
On Different Sheets:
function saveDataInAllSheetsInAFolder() {
const tss = SpreadsheetApp.getActive();
const tssnames = tss.getSheets().map(sh => sh.getName()).flat();
const fldr = DriveApp.getFolderById("Folderid");
const files = fldr.getFilesByType(MimeType.GOOGLE_SHEETS);
while(files.hasNext()) {
let file = files.next();
let ss = SpreadsheetApp.openById(file.getId());
ss.getSheets().forEach((sh,i) => {
let vs = sh.getDataRange().getValues();
let nsh = tss.insertSheet(ss.getName() + "-" + sh.getName() + "-" + Utilities.formatDate(new Date(),tss.getSpreadsheetTimeZone(),"yyyyMMdd HH:mm:ss.S"));
nsh.getRange(1,1,vs.length,vs[0].length).setValues(vs)
})
}
}
google-apps-script reference
Learn More
On Same Sheet:
function saveDataInAllSheetsInAFolder() {
const tss = SpreadsheetApp.getActive();
const nsh = tss.insertSheet(Utilities.formatDate(new Date(),tss.getSpreadsheetTimeZone(),"yyyyMMdd HH:mm:ss.S"));
nsh.getRange(1,1).setValue("Data Sheet " + Utilities.formatDate(new Date(),tss.getSpreadsheetTimeZone(),"yyyyMMdd HH:mm:ss.S") );
tss.setActiveSheet(nsh);
const tssnames = tss.getSheets().map(sh => sh.getName()).flat();
const fldr = DriveApp.getFolderById("Folderid");
const files = fldr.getFilesByType(MimeType.GOOGLE_SHEETS);
while(files.hasNext()) {
let file = files.next();
let ss = SpreadsheetApp.openById(file.getId());
ss.getSheets().forEach((sh,i) => {
let vs = sh.getDataRange().getValues();
nsh.getRange(nsh.getLastRow() + 1,1,vs.length,vs[0].length).setValues(vs);
})
}
}
Related
I currently have an app script that exports the contents of a cell into a HTML file in google sheets below:
function saveToTextfile() {
var ss = SpreadsheetApp.getActive();
var sh = ss.getActiveSheet();
var rg = sh.getRange(1, 1, sh.getLastRow(), 2);
var vs = rg.getValues();
var folder = DriveApp.getFolderById('1rTOhLtYzFAtPH-NuO-uu7OXYH4Ri6vFK')
var files = folder.getFiles();
while (files.hasNext()) files.next().setTrashed(true);
vs.forEach(r => folder.createFile(r[0] + '.html', r[1]) );
}
This works perfectly, however, I was wanting to add in another step to export the file to a folder name which would also be based on a cell value. So for example, instead of simply exporting the files "Index-1.html", "Index-2.html" etc, I want to export this way "/1/index.html", "/2/index.html". I hope that is clear.
Any help would be very much appreciated :)
Try
function saveToTextfile() {
var ss = SpreadsheetApp.getActive();
var sh = ss.getActiveSheet();
var rg = sh.getRange(1, 1, sh.getLastRow(), 2);
var vs = rg.getValues();
vs.forEach(r => DriveApp.getFolderById(getChildId('1rTOhLtYzFAtPH-NuO-uu7OXYH4Ri6vFK', r[0])).createFile('index.html', r[1]));
}
function getChildId(parentId, name) {
var parent = DriveApp.getFolderById(parentId);
var id;
var folders = parent.getFoldersByName(name);
if (folders.hasNext()) {
var folder = folders.next();
id = folder.getId();
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
if (file.getName() == 'index.html') { file.setTrashed(true) }
}
}
else {
var folder = parent.createFolder(name);
id = folder.getId();
}
return id;
}
I have a script that creates a new file, names it and copies data from a template. The problem I am having is getting all of the formatting over such as merged cells. Here is the code I have so far.
function createNewSheet(e) {
const sh = e.range.getSheet();
var name = sh.getRange(e.range.rowStart, 1).getValue();
var crNew = SpreadsheetApp.create("Job Traveler-" + name);
var ssNew = SpreadsheetApp.openByUrl(crNew.getUrl()).getId();
importRange("1X4iOzc_shcOR8UM7OEM4F1-eR62YZmwKWyyEuu59Pf4","Job!A1:D", ssNew,"Sheet1!A1");
copiedFormat();
}
function importRange(sourceId,sourceRange,destinationID,destinationRangeStart){
const sourceSS = SpreadsheetApp.openById(sourceId);
const sourceRng = sourceSS.getRange(sourceRange);
const sourceVals = sourceRng.getValues();
// Get formatting data
const sourceFontStyle = sourceRng.getFontStyles();
const sourceFontWeight = sourceRng.getFontWeights();
const sourceFontBackgroundColor = sourceRng.getBackgrounds();
const destinationSS = SpreadsheetApp.openById(destinationID);
const destStartRange = destinationSS.getRange(destinationRangeStart);
const destSheet = destinationSS.getSheetByName(destStartRange.getSheet().getName());
destSheet.clear();
const destRange = destSheet.getRange(
destStartRange.getRow(),
destStartRange.getColumn(),
sourceVals.length,
sourceVals[0].length
);
destRange.setValues(sourceVals);
// Set formatting
destRange.setFontStyles(sourceFontStyle);
destRange.setFontWeights(sourceFontWeight);
destRange.setBackgrounds(sourceFontBackgroundColor);
SpreadsheetApp.flush();
}
Best
Description
I've only provided the addtional steps to duplicate merged cells from one range to another. I leave it to you to incorporate the relavent code to your script. I've included a debugging step 'merged.forEach()' which you can remove for production.
Script
function createNewSheet() {
try {
// in my case source and destination are the same spreadsheet but different sheets
// and I have made the ranges arbitrary
importRange("Sheet5","Sheet5!C6:L11","Sheet6","Sheet6!E11")
}
catch(err) {
console.log(err)
}
}
function importRange(sourceId,sourceRange,destinationID,destinationRangeStart) {
try {
var sourceSS = SpreadsheetApp.getActiveSpreadsheet();
var sourceRng = sourceSS.getRange(sourceRange);
var sourceVals = sourceRng.getValues();
var destinationSS = sourceSS;
var destStartRange = destinationSS.getRange(destinationRangeStart);
var destSheet = destinationSS.getSheetByName(destStartRange.getSheet().getName());
var row = destStartRange.getRow();
var col = destStartRange.getColumn();
var rows = sourceVals.length;
var cols = sourceVals[0].length;
destSheet.getRange(row,col,rows,cols).setValues(sourceVals);
var merged = sourceRng.getMergedRanges();
merged.forEach( range => console.log(range.getA1Notation()));
var rowOffset = destStartRange.getRow()-sourceRng.getRow();
var columnOffset = destStartRange.getColumn()-sourceRng.getColumn();
for( var i=0; i<merged.length; i++ ) {
row = merged[i].getRow()+rowOffset;
col = merged[i].getColumn()+columnOffset;
rows = merged[i].getNumRows();
cols = merged[i].getNumColumns();
destSheet.getRange(row,col,rows,cols).merge();
}
}
catch(err) {
console.log(err)
}
}
Reference
https://developers.google.com/apps-script/reference/spreadsheet/range#getMergedRanges()
https://developers.google.com/apps-script/reference/spreadsheet/range#merge()
I am trying to save a sheet as a PDF in my drive - and I've been successful with this code:
function createPDF() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet = ss.getActiveSheet()
var data = sheet.getDataRange().getValues()
var folder = DriveApp.getFolderById('my folder ID')
var tempFile = SpreadsheetApp.create("TempSheetv2")
sheet.copyTo(SpreadsheetApp.openById(tempFile.getId()))
var tempSS = SpreadsheetApp.openById(tempFile.getId())
var tempSheet = tempSS.getSheetByName('Sheet1')
tempSS.deleteSheet(tempSheet)
var blob = SpreadsheetApp.openById(tempFile.getId()).getAs('application/pdf')
var pdf = folder.createFile(blob).setName("Test PDF for 8th Grade")
DriveApp.getFileById(tempFile.getId()).setTrashed(true)
console.log(data)
}
The only problem is - the PDF has 27 pages (26 of which are blank). Is there a way to limit the PDF to only the data range?
function createPDF() {
var ss = SpreadsheetApp.getActive()
var sheet = ss.getActiveSheet();
const name = sheet.getName();//change
ss.getSheets().filter(sh => sh.getName() != name).forEach(s => s.hideSheet());//change
var data = sheet.getDataRange().getValues()
var folder = DriveApp.getFolderById('folderid')
var tempFile = SpreadsheetApp.create("TempSheetv2")
sheet.copyTo(SpreadsheetApp.openById(tempFile.getId()))
var tempSS = SpreadsheetApp.openById(tempFile.getId())
var tempSheet = tempSS.getSheetByName('Sheet1')
tempSS.deleteSheet(tempSheet)
var blob = SpreadsheetApp.openById(tempFile.getId()).getAs('application/pdf')
folder.createFile(blob).setName("Test PDF for 8th Grade")
DriveApp.getFileById(tempFile.getId()).setTrashed(true)
console.log(data)
}
I want to IMPORT a list of files and folders in a specific folder in a google sheet. In active cell of spreadsheet im using.
I am new to programming and i have managed to try following code, but it does nt seem to work so far. Can you check please?
function listFolderContents() {
var foldername = '14DWNgJloxIjw9zeE-0Q2u_k5wQflkMMC';
var folderlisting = 'listing of folder ' + foldername;
var folders = DriveApp.getFoldersByName(foldername)
var folder = folders.next();
var contents = folder.getFiles();
//var ss = SpreadsheetApp.create(folderlisting);
var cc = SpreadsheetApp.getCurrentCell();
// var sheet = ss.getActiveSheet();
var file;
var name;
var link;
var cc;
while(contents.hasNext()) {
file = contents.next();
name = file.getName();
link = file.getUrl();
cc.push([name,link]);
}
};
For files AND folders ...
https://docs.google.com/spreadsheets/d/13fHMrWR9OOWa045uJbkz67YoVkOG4Pg6ScvrRpE-WBc/copy
function listFilesAndFolders() {
var folderid = '18akqHAN7PSPMnG3h5HpCskQsMCv4TqCM'; // change FolderID
var sh = SpreadsheetApp.getActiveSheet();
sh.clear();
sh.appendRow(["parent","folder", "name", "update", "size", "URL", "ID", "description", "type"]);
try {
var parentFolder =DriveApp.getFolderById(folderid);
listFiles(parentFolder,parentFolder.getName())
listSubFolders(parentFolder,parentFolder.getName());
} catch (e) {
Logger.log(e.toString());
}
}
function listSubFolders(parentFolder,parent) {
var childFolders = parentFolder.getFolders();
while (childFolders.hasNext()) {
var childFolder = childFolders.next();
Logger.log("Fold : " + childFolder.getName());
listFiles(childFolder,parent)
listSubFolders(childFolder,parent + "|" + childFolder.getName());
}
}
function listFiles(fold,parent){
var sh = SpreadsheetApp.getActiveSheet();
var data = [];
var files = fold.getFiles();
while (files.hasNext()) {
var file = files.next();
data = [
parent,
fold.getName(),
file.getName(),
file.getLastUpdated(),
file.getSize(),
file.getUrl(),
file.getId(),
file.getDescription(),
file.getMimeType()
];
sh.appendRow(data);
}
}
function youfunc() {
const folderid = '';
const folder = DriveApp.getFolderById(folderid);
const files = folder.getFiles();
var a = '';
while(files.hasNext()) {
let file = files.next();
a += `filename: ${file.getName()} fileid: ${file.getId()} filesize: ${file.getSize()}\n`;
}
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1');
const rg = sh.getrange('A1').setValue(a)
}
I have a spreadsheet in which I have image urls saved in a column(column H), I am trying to create PDFs by fetching URLs from column and fetch the image stored to create my PDF
Here is my code
function createBulkPdf() {
var TEMPLATE_ID = '<<Template_id>>';
var PDF_FILE_NAME = '<<PDF folder id>>';
const copyFile = DriveApp.getFileById(TEMPLATE_ID);
const folderFile = DriveApp.getFolderById(PDF_FILE_NAME);
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var lastrow = sheet.getLastRow();
Logger.log(lastrow);
const data = sheet.getRange(2, 1, lastrow, 8).getValues();
var i = 2;
data.forEach(row => {
var url = createPdf(copyFile, folderFile, row);
sheet.getRange(i, 8).setValue(url);
Logger.log(i);
i = i + 1;
});
}
function createPdf(copyFile, folderFile, data) {
const copyfilenew = copyFile.makeCopy(folderFile);
const copyDoc = DocumentApp.openById(copyfilenew.getId());
const body = copyDoc.getBody();
var resp = UrlFetchApp.fetch(data[7]); //data[7] represents column H
Logger.log(resp.getContentText());
var next = body.findText("{al}");
var r = next.getElement();
r.asText().setText("");
var img = r.getParent().asParagraph().appendInlineImage(resp.getBlob());
img.setWidth(100);
img.setHeight(80);
body.replaceText("{b}", data[1]); //body.toString().replaceText("{b}",b);
body.replaceText("{c}", data[2]);
body.replaceText("{d}", data[3]);
body.replaceText("{e}", data[4]);
body.replaceText("{f}", data[5]);
body.replaceText("{g}", data[6]);
copyDoc.saveAndClose();
const newpdffile = copyfilenew.getAs(MimeType.PDF);
var docid = folderFile.createFile(newpdffile).setName(data[3]).getId();
var filelink = "http://drive.google.com/uc?export=view&id=" + docid;
Logger.log(filelink);
folderFile.removeFile(copyfilenew);
return filelink;
}