Indesign – remove empty cells from table

I have imported XML which contains nested tables and have created a script to remove all empty cells which is as:

var myDocument = app.activeDocument;
for(var i=myDocument.textFrames.length-1; i>=0; i--){
    for(var j=myDocument.textFrames[i].tables.length-1; j>=0; j--){
        for(var k=myDocument.textFrames[i].tables[j].rows.length-1; k>=0; k--){
            myContents = 0;
            for(var l=myDocument.textFrames[i].tables[j].rows[k].cells.length-1; l>=0; l--){
                if (myDocument.textFrames[i].tables[j].rows[k].cells[l].contents != "") myContents++;  
                }
                    if (myContents == 0) myDocument.textFrames[i].tables[j].rows[k].remove();
            }
        }
    }

This works for an ordinary table, but on my XML document which contains the tables it doesnt remove the empty cells even though it hits the right if statement

Does anyone have any solutions?

Answer

As mentioned in a comment, the empty rows that are not found by the script are those that are in a table nested in its entirety inside a larger table.

The script logic does not see them; it only looks at tables ‘immediately’ inside text frames. To fix this, it needs a separate loop inside the Table loop that specifically checks for nested tables. (Which does not scale well – if there may be tables inside these tables inside tables, it needs another loop. It is better to write a separate function, which can call itself recursively; then it works with tables-in-tables-in-tables-in …)

An additional minor improvement is to not loop over text frames, but instead over entire stories. (Which, apart from speed, also has the advantage that tables in overset text also get processed.)

All in all, the following complete script should work for nested tables:

var myDocument = app.activeDocument;
for(var i=0; i<myDocument.stories.length; i++)
{
    for(var j=0; j<myDocument.stories[i].tables.length; j++)
    {
        processTable(myDocument.stories[i].tables[j]);
    }
}

function processTable (any_table)
{
    var r,c,t, isEmpty;

    for (r=any_table.rows.length-1; r>=0; r--)
    {
        isEmpty = true;
        for (c=0; c< any_table.rows[r].cells.length; c++)
        {
            for (t=0; t<any_table.rows[r].cells[c].tables.length; t++)
                processTable (any_table.rows[r].cells[c].tables[t]);

            if (any_table.rows[r].cells[c].contents != '')
                isEmpty = false;
        }
        if (isEmpty)
            any_table.rows[r].remove();
    }
}

Attribution
Source : Link , Question Author : lanes123 , Answer Author : Jongware

Leave a Comment