Apply Built-In Table Styles to Existing Word Tables in C#, VB.NET

Every time we create a plain table in a Word document, we may want to change the style of the table so as to make it more vivid and attractive. In our previous article, we have demonstrated how to set Word table formatting with custom style. However, if we do not have much time to do so, we can apply built-in table styles to own a better appearance within a few minutes. This article focuses on how to apply built-in table styles to existing Word tables using Spire.Doc with C#, VB.NET.

In the class of Spire.Doc.Table, it provides Table.ApplyStyle() method which enable us to easily change the layout of tables with default styles. As is shown below, here is a Word document that contains two plain tables in the first page. Let us see how we can format the table style with several lines of code.

Test File:

Apply Built-In Table Styles to Existing Word Tables in C#, VB.NET

Code Snippet:

Step 1: Create a new Word document and load the test file.

Document doc = new Document("table.docx", FileFormat.Docx2010);

Step 2: Get the two tables from document.

Section section = doc.Sections[0];
Table table1 = section.Tables[0] as Table;
Table table2 = section.Tables[1] as Table;

Step 3: Apply tables with built-in table styles separately.

table1.ApplyStyle(DefaultTableStyle.MediumShading1Accent2);
table2.ApplyStyle(DefaultTableStyle.MediumShading2Accent1);

Step 4: Save the file.

doc.SaveToFile("result.docx", FileFormat.Docx);

Output:

Apply Built-In Table Styles to Existing Word Tables in C#, VB.NET

Entire Code:

[C#]
Document doc = new Document("table.docx", FileFormat.Docx2010);
Section section = doc.Sections[0];
Table table1 = section.Tables[0] as Table;
Table table2 = section.Tables[1] as Table;
           
table1.ApplyStyle(DefaultTableStyle.MediumShading1Accent2);
table2.ApplyStyle(DefaultTableStyle.MediumShading2Accent1);
doc.SaveToFile("result.docx", FileFormat.Docx);
[VB.NET]
Dim doc As New Document("table.docx", FileFormat.Docx2010)
Dim section As Section = doc.Sections(0)
Dim table1 As Table = TryCast(section.Tables(0), Table)
Dim table2 As Table = TryCast(section.Tables(1), Table)

table1.ApplyStyle(DefaultTableStyle.MediumShading1Accent2)
table2.ApplyStyle(DefaultTableStyle.MediumShading2Accent1)
doc.SaveToFile("result.docx", FileFormat.Docx)