I'm not even sure if this is possible but I have a Google Sheet that I'm planning to merge into a Google Doc using the mail merge method with a template document.
I would like to know if it's possible to produce a new Google document for each row of the sheet.
Currently the script I have in place will take all rows from the sheet, pass them through the template file and then output them to my final document. Each row of the sheet will be separated by a page break in the final document. But ideally I would like each row to be in a separate document.
My current script code is
function myFunction() {
var docTemplateId = "docTemplateId";
var docFinalId = "docFinalId";
var wsId = "wsId";
var docTemplate = DocumentApp.openById(docTemplateId);
var docFinal = DocumentApp.openById(docFinalId);
var ws = SpreadsheetApp.openById(wsId).getSheetByName("data");
var data = ws.getRange(2,1,ws.getLastRow()-1,7).getValues();
var templateParagraphs = docTemplate.getBody().getParagraphs();
docFinal.getBody().clear();
data.forEach(function(r){
createMailMerge(r[0],r[3],r[4],templateParagraphs, docFinal);
});
}
function createMailMerge(titre, description, suivantes,templateParagraphs, docFinal) {
templateParagraphs.forEach(function(p) {
var elType = p.getType();
if(elType == "PARAGRAPH"){
docFinal.getBody().appendParagraph(
p
.copy()
.replaceText("{titre}", titre)
.replaceText("{description}", description)
.replaceText("{suivantes}", suivantes)
);
}
else if(elType == "LIST_ITEM") {
docFinal.getBody().appendListItem(
p
.copy()
.replaceText("{titre}", titre)
.replaceText("{description}", description)
.replaceText("{suivantes}", suivantes)
).setGlyphType(DocumentApp.GlyphType.BULLET);
}
});
docFinal.getBody().appendPageBreak();
};
Can anyone help me in achieving this. I know I could possibly create documents for each row and then add them as variable but maybe there is a more efficient way.