B00mstack
B00mstack

Reputation: 23

Why does a Google apps script insert a page break and data into a table only after the script execution ends?

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.

Upvotes: 2

Views: 292

Answers (1)

Tanaike
Tanaike

Reputation: 201408

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:

Upvotes: 3

Related Questions