Need help to handle a table or a list

Peter_1985 2,506 Reputation points
2021-10-29T06:12:57.337+00:00

Hi,
When handling Word paragraph, what is the code to create a list or a table within the created document?

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,374 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,247 questions
0 comments No comments
{count} votes

Accepted answer
  1. Xingyu Zhao-MSFT 5,356 Reputation points
    2021-11-01T08:15:31.397+00:00

    Hi @Peter_1985 ,
    In order to create a table within the created document, you can refer to the following example.
    Student.cs

    namespace myWindowsFormsApp  
    {  
        class Student  
        {  
            public string Name;  
            public int Score;  
            public string StuClass;  
            public string Leader;  
        }  
    }  
    

    Form1.cs

    namespace myWindowsFormsApp  
    {  
        public partial class Form1 : Form  
        {  
            public Form1()  
            {  
                InitializeComponent();  
            }  
      
            private void button1_Click(object sender, EventArgs e)  
            {  
                CreateTableToDoc();  
            }  
            protected void CreateTableToDoc()  
            {  
                Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();  
                object filename = @"C:\Users\xingyuzh\Desktop\test.docx";  
                object isread = false;  
                object isvisible = true;  
                object miss = System.Reflection.Missing.Value;  
                app.Documents.Open(ref filename, ref miss, ref isread, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref isvisible, ref miss, ref miss, ref miss, ref miss);  
                try  
                {  
                    List<Student> datas = new List<Student>();  
                    datas.Add(new Student { Leader = "aa", Name = "aaa", Score = 111, StuClass = "aaaa" });  
                    datas.Add(new Student { Leader = "bb", Name = "bbb", Score = 222, StuClass = "bbbb" });  
                    datas.Add(new Student { Leader = "cc", Name = "ccc1", Score = 333, StuClass = "cccc" });  
                    datas.Add(new Student { Leader = "cc", Name = "ccc2", Score = 555, StuClass = "cccc" });  
                    datas.Add(new Student { Leader = "dd", Name = "ddd", Score = 666, StuClass = "dddd" });  
                    var cate = datas.GroupBy(s => s.StuClass);  
                    int rows = cate.Count() + 2;  //row for title  
                    int cols = 5;  
                    object oMissing = System.Reflection.Missing.Value;  
      
                    //The title format  
                    app.Selection.Font.Bold = 700;  
                    app.Selection.Font.Size = 16;  
                    app.Selection.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;  
                    app.Selection.Text = "Title";  
      
                    //Wrap to add a table  
                    object line = Microsoft.Office.Interop.Word.WdUnits.wdLine;  
                    app.Selection.MoveDown(ref line, oMissing, oMissing);  
                    app.Selection.TypeParagraph();//Wrap  
                    Microsoft.Office.Interop.Word.Range range = app.Selection.Range;  
                    Microsoft.Office.Interop.Word.Table table = app.Selection.Tables.Add(range, rows, cols, ref oMissing, ref oMissing);  
      
                    //Set the font size of the table to be thick  
                    table.Range.Font.Size = 10;  
                    table.Range.Font.Bold = 0;  
      
                    //Set the outer and inner borders of the table  
                    table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;  
                    table.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleOutset;  
      
                    //Set the Column titles  
                    int rowIndex = 1;  
                    table.Cell(rowIndex, 1).Range.Text = "class";  
                    table.Cell(rowIndex, 2).Range.Text = "name";  
                    table.Cell(rowIndex, 3).Range.Text = "score";  
                    table.Cell(rowIndex, 4).Range.Text = "stuNumber";  
                    table.Cell(rowIndex, 5).Range.Text = "leader";  
      
                    //Loop data to create rows of data  
                    rowIndex++;  
                    foreach (var i in cate)  
                    {  
                        int moveCount = i.Count() - 1;//The number of rows merged vertically  
                        if (moveCount.ToString() != "0")  
                        {  
                            table.Cell(rowIndex, 1).Merge(table.Cell(rowIndex + moveCount, 1));//Merge classes  
                            table.Cell(rowIndex, 4).Merge(table.Cell(rowIndex + moveCount, 4));//Merge number  
                            table.Cell(rowIndex, 5).Merge(table.Cell(rowIndex + moveCount, 5));//Merge leader  
                        }  
      
                        //Write the merged data and center vertically  
                        table.Cell(rowIndex, 1).Range.Text = i.Key;  
                        table.Cell(rowIndex, 4).Range.Text = i.Count().ToString();  
                        table.Cell(rowIndex, 5).Range.Text = i.First().Leader;  
                        table.Cell(rowIndex, 1).VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;  
                        table.Cell(rowIndex, 4).VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;  
                        table.Cell(rowIndex, 5).VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;  
      
                        //Build name, score data  
                        foreach (var x in i)  
                        {  
                            table.Cell(rowIndex, 2).Range.Text = x.Name;  
                            table.Cell(rowIndex, 3).Range.Text = x.Score.ToString();  
                            rowIndex++;  
                        }  
                    }  
                    app.Documents.Save();  
                }  
                catch (Exception e)  
                {  
                    Console.WriteLine(e.Message);  
                }  
                finally  
                {  
                    if (app.Documents != null)  
                    {  
                        app.Documents.Close();  
                    }  
                    if (app != null)  
                    {  
                        app.Quit();  
                    }  
                }  
            }  
        }  
    }  
          
    

    Result of my test.

    145380-1.png
    Hope the code above could be helpful.

    Best Regards.
    Xingyu Zhao
    *
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. ShuaiHua Du 636 Reputation points
    2021-11-05T14:55:58.15+00:00

    Hi, It is recommended to use the open XML SDK to operate word documents.

    Open-XML-SDK provides tools for working with Office Word, Excel, and PowerPoint documents.

    0 comments No comments