I have a Google Sheets document containing various cells with different colors. I’ve created a script that successfully replaces a Google Docs template with the values from a specified range in Sheets. However, I am struggling to update the text color according to the original colors from the cells during this replacement. While I can extract the colors from the cells, I can’t find a method to apply them appropriately. For instance, the function setTextColor(color); only seems to apply black text color. Here’s the code I’ve developed so far:
const templateFile = DriveApp.getFileById('your_template_id');
const outputFolder = DriveApp.getFolderById('your_folder_id');
const selectedRange = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange('C3:E26');
const valuesFromRange = selectedRange.getDisplayValues();
const styledText = selectedRange.getRichTextValues();
const currentSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data');
const currentDate = `${new Date().getDate()}/${new Date().getMonth()+1}/${new Date().getFullYear()}`;
const copiedDoc = templateFile.makeCopy(`Report ${currentDate}`, outputFolder);
const document = DocumentApp.openById(copiedDoc.getId());
const documentBody = document.getBody();
for (let row = 0; row < valuesFromRange.length; row++) {
for (let col = 0; col < valuesFromRange[row].length; col++) {
const textInCell = styledText[row][col];
const textStyle = textInCell.getTextStyle();
const cellColor = textStyle.getForegroundColor();
documentBody.replaceText(`{{${row}-${col}}}`, valuesFromRange[row][col]).setTextColor(cellColor);
}
}
document.saveAndClose();
const docLink = document.getUrl();
currentSheet.getRange('J1').setValue(docLink);
I would appreciate any guidance on how to achieve the desired outcome!