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 :)
CodePudding user response:
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;
}