Reputation: 125
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.
Upvotes: 2
Views: 2632
Reputation: 31
I use your code but you forgot an element
rowIndex--;
On the block
if (foundEmptyRow) { table.removeRow(rowIndex) numberOfRows-- }
With this it's very nice.
if (foundEmptyRow) { table.removeRow(rowIndex) numberOfRows-- rowIndex-- }
Upvotes: 1
Reputation: 2788
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()
Upvotes: 1