How to Align a Table in C#

2016-05-18 07:41:11 Written by  support iceblue
Rate this item
(0 votes)

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:

using Spire.Doc;
using Spire.Doc.Documents;
namespace AlignTable
{
    class Program
    {

        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); 
        }
    }
}

Additional Info

  • tutorial_title: Align a Table in C#
Last modified on Friday, 03 September 2021 03:53