Search code examples
pythonpython-docx

Python-docx how do I delete a table column?


I need to delete a column of a table in a docx using python 3.

Nothing in internet.


Solution

  • You can use this function

    from docx import Document
    
    document = Document('YOUR_DOCX')
    
    def Delete_column_in_table(table, columns):
        table = document.tables[table]
        grid = table._tbl.find("w:tblGrid", table._tbl.nsmap)
        for cell in table.column_cells(columns):
            cell._tc.getparent().remove(cell._tc)
        col_elem = grid[columns]
        grid.remove(col_elem)
    
    Delete_column_in_table(0, 0)
    
    document.save('OUT.docx')