Remove row of table in a Google Document with Goog

2019-05-26 20:24发布

I'm trying to create documents massively using information from a spreadsheet to Google using Google Apps Script, but I don't know how to use the Table class (specifically the method: RemoveRow)

I created an example (less complex) in order to illustrate my problem. I have a Google document called "Sales Reports", this document read information from this Google Sheets called Data. So far no problem, I can do it.

However, there are a condition. The product A and product B are exclusive, that is: if I buy "product A" then, I do not buy the "product B" and vice versa. The Google Docs must show 1 row (not 2). The code is similar to this:

var TEMPLATE_ID = 'xyz';
function createPdf() {
  var activeSheet = SpreadsheetApp.getActiveSheet(),
  numberOfColumns = activeSheet.getLastColumn(),
  numberOfRows = activeSheet.getLastRow(),
  activeRowIndex = activeSheet.getActiveRange().getRowIndex(),
  activeRow = '',
  headerRow = activeSheet.getRange(1, 1, numberOfRows, numberOfColumns).getValues()
  var destFolder = DriveApp.getFolderById("aaaaaaa");

 for(i=2;i<=numberOfRows;i++) {
 var copyFile = DriveApp.getFileById(TEMPLATE_ID).makeCopy()
 copyId = copyFile.getId(),
 copyDoc = DocumentApp.openById(copyId),
 copyBody = copyDoc.getActiveSection()
 activeRow = activeSheet.getRange(i, 1, 1, numberOfColumns).getValues();

 for (columnIndex = 0;columnIndex < headerRow[0].length; columnIndex++) {
    copyBody.replaceText('%' + headerRow[0][columnIndex] + '%', 
                     ''+activeRow[0][columnIndex]);    
}


copyDoc.saveAndClose()

                              .....
            //code: create pdf with the custom template

}

} //fin del crear

What are the changes that I need to do?

Greetings, Thanks in advance.

1条回答
神经病院院长
2楼-- · 2019-05-26 20:36

This function removes all of the empty rows from all of the tables in a Google Document:

/**
 * Remove all the empty rows from all the tables in a document
 *
 * @param {String} documentId
 */

function removeEmptyRows(documentId) {

  var tables = DocumentApp.openById(documentId).getBody().getTables()

  tables.forEach(function(table) {

    var numberOfRows = table.getNumRows()

    for (var rowIndex = 0; rowIndex < numberOfRows; rowIndex++) {

      var nextRow = table.getRow(rowIndex)
      var numberOfColumns = nextRow.getNumCells()

      // A row is assumed empty until proved otherwise
      var foundEmptyRow = true

      for (var columnIndex = 0; columnIndex < numberOfColumns; columnIndex++) {  

        if (nextRow.getCell(columnIndex).getText() !== '') {
          foundEmptyRow = false
          break
        }

      } // for each column

      if (foundEmptyRow) {
        table.removeRow(rowIndex)
        numberOfRows--
      }

    } // For each row
  })

} // removeEmptyRows() 
查看更多
登录 后发表回答