2
votes

I'm running a GAS in Google documents to fill out a table with an array of data from G' Sheets.
When the data is longer than what will fit into the first page I'm inserting a page break into the paragraph at the end of the first table. The rest of the data is inserted into a second table on the second page.
All works fine but the rows and page break are only added to the document once the script completes its execution. This causes me a problem because I would like to convert the .gdoc to a .docx during execution and the rows don't get converted to the .docx because they aren't in the .gdoc until the script ends.

function fillSampling(fileID, data) {
  var doc = DocumentApp.openById(fileID);
  var body = doc.getBody();
  var cellStyle = {};
  cellStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
  cellStyle[DocumentApp.Attribute.FONT_SIZE] = 8;
  cellStyle[DocumentApp.Attribute.BOLD] = false;
  var boldStyle = {};
  boldStyle[DocumentApp.Attribute.BOLD] = true;
  var table = body.getTables()[1];
  var tableHeader = table.copy();
  var r = 0;

  while(data[r]) {
    if(r==10) {
      body.insertPageBreak(body.getNumChildren()-1);
      table = body.appendTable(tableHeader);
    }
    var tableRow = table.appendTableRow();
    var c = 0;
    while(data[r][c]) {
      var cell = tableRow.appendTableCell(data[r][c]).setPaddingBottom(0).setPaddingTop(0);
      cell.getChild(0).asParagraph().setAttributes(cellStyle);
      if(c==0) cell.setAttributes(boldStyle);
      c++;
    }
    r++;
  }
}

This is the function which fills out the first and following table. Another function which calls this function then goes onto converting the document from .gdoc to .docx.
Could anybody explain why the rows, page break and second table seem to be getting cached and only added to the document after execution ends?
Any help would be much appreciated, thank you.

1
Although I'm not sure whether I could correctly understand about your issue, for example, how about putting doc.saveAndClose() to the last line of the function fillSampling? Ref But if this was not the direct solution, I apologize. - Tanaike
@Tanaike You understood perfectly!! I wish I'd thought of something that simple. Thank you for your immediate response. If you post it as an answer I'll mark it as the solution. - B00mstack
Thank you for replying. I'm glad your issue was resolved. I posted it as an answer. Could you please confirm it? - Tanaike

1 Answers

2
votes

In your situation, I thought that to put the following script to the last line of the function of fillSampling will resolve your issue.

doc.saveAndClose();

Reference: