Tables in Word documents can sometimes disrupt the flow of text or the visual balance of a page. Removing these tables can help in creating a more aesthetically pleasing document, which is crucial for reports, presentations, or publications where appearance is important. In this article, you will learn how to remove tables from a Word document in Python using Spire.Doc for Python.
Install Spire.Doc for Python
This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip commands.
pip install Spire.Doc
If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows
Remove a Specified Table in Word in Python
Spire.Doc for Python provides the Section.Tables.RemoveAt(int index) method to delete a specified table in a Word document by index. The following are the detailed steps.
- Create a Document instance.
- Load a Word document using Document.LoadFromFile() method.
- Get a specified section using Document.Sections[] property.
- Delete a specified table by index using Section.Tables.RemoveAt() method.
- Save the result document using Document.SaveToFile() method.
- Python
from spire.doc import * from spire.doc.common import * inputFile = "Tables.docx" outputFile = "RemoveTable.docx" # Create a Document instance doc = Document() # Load a Word document doc.LoadFromFile(inputFile) # Get the first section in the document sec = doc.Sections[0] # Remove the first table in the section sec.Tables.RemoveAt(0) # Save the result document doc.SaveToFile(outputFile, FileFormat.Docx) doc.Close()
Remove All Tables in Word in Python
To delete all tables from a Word document, you need to iterate through all sections in the document, then iterate through all tables in each section and remove them through the Section.Tables.Remove() method. The following are the detailed steps.
- Create a Document instance.
- Load a Word document using Document.LoadFromFile() method.
- Iterate through all sections in the document.
- Iterate through all tables in each section.
- Delete the tables using Section.Tables.Remove() method.
- Save the result document using Document.SaveToFile() method.
- Python
from spire.doc import * from spire.doc.common import * inputFile = "Tables.docx" outputFile = "RemoveAllTables.docx" # Create a Document instance doc = Document() # Load a Word document doc.LoadFromFile(inputFile) # Iterate through all sections in the document for i in range(doc.Sections.Count): sec = doc.Sections.get_Item(i) # Iterate through all tables in each section for j in range(sec.Tables.Count): table = sec.Tables.get_Item(j) # Remove the table sec.Tables.Remove(table) # Save the result document doc.SaveToFile(outputFile, FileFormat.Docx) doc.Close()
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.