我正在尝试使用Google Apps脚本使用电子表格中的信息大量创建文档,但我不知道如何使用Table类(特别是方法:RemoveRow)
我创建了一个示例(不太复杂)以说明我的问题。我有一个名为“Sales Reports”的Google文档,此文档从此Google表格中读取了名为Data的信息。到目前为止没问题,我可以做到。
然而,有一个条件。产品A和产品B是独家的,即:如果我购买“产品A”,那么我不买“产品B”,反之亦然。 Google文档必须显示1行(而不是2行)。代码类似于:
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
我需要做些什么改变?
问候,提前致谢。
答案 0 :(得分:0)
此功能会删除Google文档中所有表格中的所有空行:
/**
* 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()
答案 1 :(得分:-1)
我使用了您的代码,但您忘记了一个元素
rowIndex-;
在街区
if (foundEmptyRow) { table.removeRow(rowIndex) numberOfRows-- }
这很好。
if (foundEmptyRow) { table.removeRow(rowIndex) numberOfRows-- rowIndex-- }