Skip to content

Instantly share code, notes, and snippets.

@msafadieh
Last active August 21, 2019 19:20
Show Gist options
  • Save msafadieh/3457660587de4454e2da61d6271b8e80 to your computer and use it in GitHub Desktop.
Save msafadieh/3457660587de4454e2da61d6271b8e80 to your computer and use it in GitHub Desktop.
Builds a barebone Google Doc from Google Sheet entries
var folderName = "New Copy Center Jobs";
var columnsToSkip = 2;
function createDocument(lastRow) {
const doc = createDoc();
const sheet = SpreadsheetApp.getActiveSheet();
const fullRangeValues = sheet.getDataRange().getValues();
const titles = fullRangeValues[0];
const data = lastRow ? fullRangeValues : sheet.getActiveRange().getValues();
const start = lastRow ? data.length - 1 : 0;
populateDocument(doc, titles, data, start);
displayMessage(doc);
}
function populateDocument(doc, titles, data, start) {
const body = doc.getBody();
for (var i = start; i < data.length; i++) {
for (var j = columnsToSkip; j < data[i].length; j++) {
if (titles[j]) {
var paragraph = body.appendParagraph("");
var key = paragraph.insertText(0, titles[j] + ": ");
key.setBold(true);
var value = paragraph.insertText(1, data[i][j] || " ");
value.setBold(false);
}
}
if (i + 1 != data.length) body.appendPageBreak();
}
}
function createDoc() {
const doc = DocumentApp.create(generateFileName());
const folder = createFolder();
moveToFolder(doc, folder);
return doc;
}
function generateFileName() {
const timestamp = new Date();
return "Form Entries " + timestamp.toTimeString();
}
function displayMessage(doc) {
const htmlOutput = HtmlService
.createHtmlOutput('<p>Click to open <a href="' + doc.getUrl() + '" target="_blank">' + doc.getName() + '</a></p>')
.setWidth(300)
.setHeight(80)
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Export Successful')
}
function moveToFolder(doc, folder) {
const file = DriveApp.getFileById(doc.getId());
const root = DriveApp.getRootFolder();
folder.addFile(file);
root.removeFile(file);
}
function createFolder() {
var folders = DriveApp.getFoldersByName(folderName);
if (folders.hasNext()) {
return folders.next();
} else {
return DriveApp.createFolder(folderName);
}
}
function createDocumentFromSelection() {
createDocument(false);
}
function createDocumentFromLastRow() {
createDocument(true);
}
function onOpen(e) {
SpreadsheetApp.getUi()
.createAddonMenu()
.addItem('Create document from selection', 'createDocumentFromSelection')
.addItem('Create document from last row', 'createDocumentFromLastRow')
.addToUi();
}
function onInstall(e) {
onOpen(e);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment