Skip to main content

Remove empty tables

Removes all the empty tables from the document.

(function () {
let doc = Api.GetDocument();
let tables = doc.GetAllTables();

if (!tables || tables.length === 0) {
return;
}

let removedCount = 0;
let hasCellText = (cell) => {
let content = cell.GetContent();
let paragraphs = content.GetAllParagraphs();

for (let para of paragraphs) {
if (para.GetText().trim() !== "") {
return true;
}
}
return false;
};

for (let i = tables.length - 1; i >= 0; i--) {
let table = tables[i];
let hasContent = false;

let rowCount = table.GetRowsCount();
for (let row = 0; row < rowCount && !hasContent; row++) {
let cellCount = table.GetRow(row).GetCellsCount();
for (let cell = 0; cell < cellCount && !hasContent; cell++) {
if (hasCellText(table.GetCell(row, cell))) {
hasContent = true;
}
}
}

if (!hasContent) {
table.Delete();
removedCount++;
}
}
})();

Methods used: GetDocument, GetAllTables, GetContent, GetAllParagraphs, GetText, GetRowsCount, GetRow, GetCellsCount, GetCell, Delete

Result

RemoveEmptyTables RemoveEmptyTables