I am trying to copy formatted texts from google sheets to google docs using google scripts. I have successfully converted text from sheets to docs however I am unable to carry over the relevant formatting/markdowns like bold, italics, colour, underlined & etc. Does anyone have any idea as to what I am doing wrong or what functions I can use in the google scripting library which allows me to copy over the formatting as well?
Currently, I have an existing google doc that acts as the template. All future google docs created will follow a similar template. I have created a sheet named 'doc Builder' and have used ,for loops and switch statements to choose which cell within the sheet to be copied over to the word doc.
function createDocument() {
var docbuilder = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('doc Builder');
//active data range
var range = docbuilder.getRange(4, 1, docbuilder.getLastRow() - 3, docbuilder.getLastColumn() - 1).getDisplayValues();
var templateId = 'myworddocIDwhichihaveremoved'; //the word doc
//Make a copy of the template file
var documentId = DriveApp.getFileById(templateId).makeCopy().getId();
//Rename the copied file
DriveApp.getFileById(documentId).setName('name of new doc');
//Get the document body as a variable
var body = DocumentApp.openById(documentId).getBody();
//copies texts from cell to word doc
//i = row, j = column
for(var i = 0; i < range.length; i++){
for(var j = 0; j < range[i].length; j++){
var cells = [];
switch(j) {
case 0:
body.appendParagraph(range[i][j]);
break;
case 1:
body.appendParagraph(range[i][j]);
break;
case 2:
if(range[i][j] != ""){
body.appendParagraph('PARAGRAPH 1:' + range[i][j]);
}
break;
case 3:
body.appendParagraph('PARAGRAPH 2:' + range[i][j]);
break;
}
}
}
}
I have tried copyTo()
and it copies the formatting from sheet to sheet successfully however am unable to do the same for sheet to doc. I am also aware of the attributes which I can add to my word doc like BACKGROUND_COLOR, BOLD and etc from the documentation however the data I am handling often only has some parts of the cell formatted for example : sally is a girl instead of sally is a girl. Thus making it difficult to hard code when the number of cells increases.
Simply put I am trying to bring over the formatting from the sheet to the doc so I don't have to handle each cell individually.
I am working with more cases but I have removed them to simplify the code, also every cell within the active data range is formatted but when the new google doc is created the formatting disappears.
I hope someone has a solution to this haha :""D
RichTextValue
and has a methodappendAsNewParagraph(body)
so it keeps usage relatively simple. As you both have said, it breaks down each of the runs, extracting its start and end indices and all the formatting info, then translating that over to a new paragraph. – iansedano