How to Set Word Table Style in C#, VB.NET

Table in Microsoft Word is used to present data information which can assist to explain specified paragraph contents. In order to have a better appearance, people can set Word table style. This guide shows how to use Spire.Doc to set table style in Word with C#/VB.NET.

Download Spire.Doc (or Spire.Office) with .NET Framework 2.0 (or above) together. Once make sure Spire.Doc (or Spire.Office) are correctly installed on system, follow the steps below to set Word table style

In this example, a Word document with table has been prepared. It is a student transcript template from Office.com.

Step 1Create a C#/VB.NET project in Visual Studio. Add Spire.Doc.dll as reference.

[C#]
Document document = new Document();
document.LoadFromFile(@"E:\work\Documents\Student Transcript.docx");
[VB.NET]
Dim document As New Document()
document.LoadFromFile("E:\work\Documents\Student Transcript.docx")

Step 2: Set Table Style

Get table which you want to set style

Because table1 type is different from document.Sections[0].Tables[1] type, so use (Table) to transformed forcibly.

[C#]
Table table1 = (Table)document.Sections[0].Tables[1];
[VB.NET]
Dim table1 As Table = CType(document.Sections(0).Tables(1), Table)

Set table row height.

[C#]
table1.Rows[0].Height = 25;
[VB.NET]
table1.Rows(0).Height = 25

Set Table Style

In order to have distinction. Keep the first cell in first row as before and set style for the second cell. Firstly, set alignment and background color for the second cell. Secondly, declare a paragraph style, including font size, color and apply this style in cell.

[C#]
table1.Rows[0].Cells[1].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
table1.Rows[0].Cells[1].CellFormat.BackColor = Color.LimeGreen;

ParagraphStyle style = new ParagraphStyle(document);
style.Name = "TableStyle";
style.CharacterFormat.FontSize = 14;
style.CharacterFormat.TextColor = Color.GhostWhite;
document.Styles.Add(style);
table1.Rows[0].Cells[1].Paragraphs[0].ApplyStyle(style.Name);
[VB.NET]
table1.Rows(0).Cells(1).CellFormat.VerticalAlignment = VerticalAlignment.Middle
table1.Rows(0).Cells(1).CellFormat.BackColor = Color.LimeGreen

Dim style As New ParagraphStyle(document)
style.Name = "TableStyle"
style.CharacterFormat.FontSize = 14
style.CharacterFormat.TextColor = Color.GhostWhite
document.Styles.Add(style)
table1.Rows(0).Cells(1).Paragraphs(0).ApplyStyle(style.Name)

Step 3: Save and Launch

[C#]
document.SaveToFile("WordTable.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("WordTable.docx");
[VB.NET]
document.SaveToFile("WordTable.docx", FileFormat.Docx)
System.Diagnostics.Process.Start("WordTable.docx")

Effective Screenshot:

Word Table Format

This guide shows how to set Word table style such as size and color via Spire.Doc. However, Spire.Doc can do a lot on operating Word document Click to learn more