How to Align a Table in C#

Usually there are three kinds of alignment style for a word table: left aligned, centered and right aligned. On Microsoft word, we can go to table properties to set the alignment for the whole table. Spire.Doc also offers a property table.TableFormat.HorizontalAlignment to enable developers to set the table alignment style easily in C#. This article will demonstrate how to align a table in C#.

Firstly, view the how to align a table for Microsoft word:

How to align a table in C#

Here come to the code snippet of how Spire.Doc align a table.

Step 1: Create a word document and load from file.

Document doc = new Document();
doc.LoadFromFile("sample.docx");

Step 2: Get the first section and two tables from the word document.

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

Step 3: Set the different alignment properties for each table.

table.TableFormat.HorizontalAlignment = RowAlignment.Right;
table.TableFormat.LeftIndent = 34;

table1.TableFormat.HorizontalAlignment = RowAlignment.Left;
table1.TableFormat.LeftIndent = 34;

Step 4: Save the document to file:

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

Effective screenshots after align the table format:

How to align a table in C#

Full codes:

static void Main(string[] args)
{
    Document doc = new Document();
    doc.LoadFromFile("sample.docx");

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

    table.TableFormat.HorizontalAlignment = RowAlignment.Right;
    table.TableFormat.LeftIndent = 34;

    table1.TableFormat.HorizontalAlignment = RowAlignment.Left;
    table1.TableFormat.LeftIndent = 34;

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