Share via


How to set Alignment of cells in word table using c#

Question

Tuesday, July 31, 2012 12:01 PM

Hi,

I have created a word document. I have inserted table with 1 row and 3 columns by setting ParagraphFormat alignment as well as Rows Alignment but trouble in setting cell alignment. How to do this.

I want to set col1 as Left align, col2 as center align, and col3 as right align.

Here is my code

//Adding Table here
                Word.Table oTable;
                Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                oTable = oDoc.Tables.Add(wrdRng, 1, 3, ref oMissing, ref oMissing);
                oTable.Range.ParagraphFormat.SpaceAfter = 6;
                int r, c;
                string strText;
                for (r = 1; r <= 1; r++)
                    for (c = 1; c <= 3; c++)
                    {
                        strText = "Lsoft" + r + "Pune" + c;
                        oTable.Cell(r, c).Range.Text = strText;
                    }
                oTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;                               
                oTable.Cell(0, 0).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                oTable.Rows[0].Alignment = WdRowAlignment.wdAlignRowCenter;

Thanks in advance. 

All replies (2)

Wednesday, August 1, 2012 5:43 AM âś…Answered | 3 votes

Hi,

Thanks for posting in the MSDN Forum.

Based your issue,  I would suggest you use oTable.Cell(i,j).Range.ParagraphFormat.Alignment to set table cell alignment in Word. Please refer to the following snippet.

//Adding Table here
Word.Table oTable;
Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oTable = oDoc.Tables.Add(wrdRng, 1, 3, ref oMissing, ref oMissing);
oTable.Range.ParagraphFormat.SpaceAfter = 6;
int r, c;
string strText;
for (r = 1; r <= 1; r++)
    for (c = 1; c <= 3; c++)
    {
        strText = "Lsoft" + r + "Pune" + c;
        oTable.Cell(r, c).Range.Text = strText;
    }
//The col1 cell
oTable.Cell(1,1).Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphLeft;
//The col2 cell
oTable.Cell(1,2).Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphCenter;
//The col3 cell
oTable.Cell(1,3).Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphRight;

Hope this can help you.

If anything is unclear, please do not hesitate to let me know.

Have a good day.

Leo_Gao [MSFT]
MSDN Community Support | Feedback to us


Wednesday, August 1, 2012 10:30 AM

Hi Leo_Gao, Thanks it solves my thread. Thanks wonderful help.