Tables in Word documents allow users to organize data in a structured, readable format. However, at times you may find that some tables are outdated or no longer serve their intended purpose, making it necessary to remove them. In this article, you will learn how to remove tables from a Word document in C# using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Remove a Specified Table in Word in C#
Spire.Doc for .NET 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.
- C#
using Spire.Doc; namespace RemoveTable { class Program { static void Main(string[] args) { //Create a Document instance Document doc = new Document(); //Load a Word document doc.LoadFromFile("tables.docx"); //Get the first section in the document Section sec = doc.Sections[0]; //Remove the first table in the section sec.Tables.RemoveAt(0); //Save the result document doc.SaveToFile("RemoveATable.docx", FileFormat.Docx); } } }
Remove All Tables in Word in C#
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.
- C#
using Spire.Doc; namespace RemoveAllTable { class Program { static void Main(string[] args) { //Create a Document instance Document doc = new Document(); //Load a Word document doc.LoadFromFile("tables.docx"); //Iterate through all sections in the document foreach (Section section in doc.Sections) { //Iterate through all tables in each section foreach (Table table in section.Tables) { //Remove the tables section.Tables.Remove(table); } } //Save the result document doc.SaveToFile("RemoveTables.docx", FileFormat.Docx); } } }
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.