I'm trying to execute a mailmerge script that reads fields from a spreadsheet and the template from a google doc. The script runs on the google doc.
The script works fine except it doesn't copy the formatting or table that is in the document. This is crucial.
Below is the code I am using.
function mmerge() {
var mdoc=DocumentApp.getActiveDocument();
var mdat=SpreadsheetApp.openById("1Nc2xu--").getSheetByName("MailMerge List);
var numcols=mdat.getDataRange().getNumColumns();
var numrows=mdat.getDataRange().getNumRows();
var mtxt=mdoc.getBody().getText();
var flds=[];
for (var j=0;j<numcols;j++) {flds.push(mdat.getRange(1, j+1).getValue());}
var rtxt;
for (var i=2; i<=numrows; i++) {
rtxt=mtxt
for (var j=1; j<=numcols; j++) {
rtxt=rtxt.replace("{"+flds[j-1]+"}",mdat.getRange(i, j).getValue());
}
mdoc.getBody().appendParagraph(rtxt);
}
}
I suspect that it has to do with the method used here: mtxt=mdoc.getBody().getText()
but I don't know how to change it. My attempts to change it to copy() results in an error.
Does anyone know what I am doing wrong? Any help would be greatly appreciated.
Update: This is not a straight forward copy problem: the process involves having to execute the mail merge and then apply the formatting to the mailmerged doc.
Thanks