Delete Blank Rows from Tables in a Google Document with Apps Script

This Google App Script snippet will help you quickly delete all the blank rows of any tables inside your Google Document.

You can either pass the Google Drive File ID to the removeBlankRows() method or it will take the currently active Google Document as input.


/* 
*  Written by Amit Agarwal
*  Email: amit@labnol.org
*
*/

function removeBlankRows(docId) {

    var document = docId ?
        DocumentApp.openById(docId) :
        DocumentApp.getActiveDocument();

    var body = document.getBody();
    var search = null;
    var tables = [];

    // Extract all the tables inside the Google Document
    while (search = body.findElement(DocumentApp.ElementType.TABLE, search)) {
        tables.push(search.getElement().asTable());
    }

    tables.forEach(function (table) {
        var rows = table.getNumRows();
        // Iterate through each row of the table
        for (var r = rows - 1; r >= 0; r--) {
            // If the table row contains no text, delete it
            if (table.getRow(r).getText().replace(/\s/g, "") === "") {
                table.removeRow(r);
            }
        }
    });

    document.saveAndClose();
}