I am trying to make automated reports by filling a form. The data is read out by the script from the last spreadsheet line. Then the report is made as a Google Doc. Here some tags inside this document present where the items should be. %meterx% is for meters.
These can be images or text. For normal paragraphs, this is working fine with the first loop where the type = paragraph. But it skips tables. I need to replace the %meterx% in a table cell with the image, just like I do with the paragraph, but I am stuck at the code to look through the table.
I see some ways to replace text but this seems to be the only way to replace it with images.
var totalElements = doc.getNumChildren();
var el=[]
for( var j = 0; j < totalElements; ++j ) {
var element = doc.getChild(j);
var type = element.getType();
if (type =='PARAGRAPH'){
el[j]=element.getText()
if(el[j]=='%meter3%'){element.removeFromParent();
var newimage = UrlFetchApp.fetch('http://chart.googleapis.com/chart?chf=bg,s,67676700&chs=280x150&cht=gm&chds=0,10&chd=t:'+row[4]+'&chdlp=b').getBlob();
doc.insertImage(j, newimage);
if (type =='TABLE'){
var tablerows=element.getNumRows();
Logger.log(tablerows);
for ( var i = 0; i < tablerows; ++i ) {
var tablerow = element.getRow(0)
Logger.log(tablerow); // <--- gives TableRow
} /// STUCK !! :)
A
TableRowcontains child elements, of typeTableCell, which also contain child elements. Those are typePARAGRAPHif they are blank or contain text.You can access the text within a
TableCellwithgetText(), but it’s a good idea to confirm that the cell contains text first.The code below handles
PARAGRAPHandTABLEelement types, and for tables it explores theTABLECELLelements. I don’t know what you’re doing with your arrayel[], so I’ve left that out, and also commented out the image-replacement code – instead, I’m just logging the structure and content of the table for illustration. To complete your goal, you should replace the logging with the same match & replace behavior you have forPARAGRAPH.NOTE: I am using a couple of helper functions not detailed here, which should be self-explanatory,
getFileByName_()andelementTypeToText_().This is an excerpt of the logs from a sample doc, with a table containing a cell with the
%meter3%tag: