Click here to Skip to main content
15,904,926 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to add 9 tables in my word file while try the below code it only adds rows instead of a table in my report automation how to do it

What I have tried:

private void CreateDocument()
        {
            try
            {
                //Create an instance for word app
                Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();

                //Set animation status for word application
                winword.ShowAnimation = false;

                //Set status for word application is to be visible or not.
                winword.Visible = false;
                
                //Create a missing variable for missing value
                object missing = System.Reflection.Missing.Value;

                //Create a new document
                Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                
                //Add header into the document
                foreach (Microsoft.Office.Interop.Word.Section section in document.Sections)
                {
                    Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
                    headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    headerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue;
                    headerRange.Font.Size = 10;
                    headerRange.Text = "Header text goes here";
                }

                //Add the footers into the document
                foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
                {
                    Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed;
                    footerRange.Font.Size =10;
                    footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    footerRange.Text = "Footer text goes here";
                }

                //adding text to document
                document.Content.SetRange(0, 0);
                document.Content.Text = "This is test document "+ Environment.NewLine;
                
                //Add paragraph with Heading 1 style
                Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing);                
                object styleHeading1 = "Heading 1";
                para1.Range.set_Style(ref styleHeading1);                
                para1.Range.Text = "Para 1 text";
                para1.Range.InsertParagraphAfter();

                //Add paragraph with Heading 2 style
                Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref missing);
                object styleHeading2 = "Heading 2";
                para2.Range.set_Style(ref styleHeading2);
                para2.Range.Text = "Para 2 text";
                para2.Range.InsertParagraphAfter();

                //Add paragraph with Heading 3 style
                Microsoft.Office.Interop.Word.Paragraph para3 = document.Content.Paragraphs.Add(ref missing);
                object styleHeading3 = "Heading 3";
                para3.Range.set_Style(ref styleHeading3);
                para3.Range.Text = "Para 3 text";
                para3.Range.InsertParagraphAfter();

                //Create a 5X5 table and insert some dummy record
                Table firstTable = document.Tables.Add(para1.Range, 5, 5, ref missing, ref missing);
                
                firstTable.Borders.Enable = 1;
                

                foreach (Row row in firstTable.Rows)
                {
                    foreach (Cell cell in row.Cells)
                    {
                        //Header row
                        if (cell.RowIndex == 1)
                        {
                            cell.Range.Text = "Column " + cell.ColumnIndex.ToString();
                            cell.Range.Font.Bold = 1;
                            //other format properties goes here
                            cell.Range.Font.Name = "verdana";
                            cell.Range.Font.Size = 10;
                            //cell.Range.Font.ColorIndex = WdColorIndex.wdGray25;                            
                            cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25;                      
                            //Center alignment for the Header cells                                           
                            cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;        
                            cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                            
                        }
                        //Data row
                        else
                        {
                            cell.Range.Text = (cell.RowIndex - 2 + cell.ColumnIndex).ToString();
                        }
                    }
                }

                Table secondTable = document.Tables.Add(para2.Range, 5, 5, ref missing, ref missing);
                secondTable.Borders.Enable = 1;

                foreach (Row row in secondTable.Rows)
                {
                    foreach (Cell cell in row.Cells)
                    {
                        //Header row
                        if (cell.RowIndex == 1)
                        {
                            cell.Range.Text = "Column " + cell.ColumnIndex.ToString();
                            cell.Range.Font.Bold = 1;
                            //other format properties goes here
                            cell.Range.Font.Name = "verdana";
                            cell.Range.Font.Size = 10;
                            //cell.Range.Font.ColorIndex = WdColorIndex.wdGray25;                            
                            cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25;
                            //Center alignment for the Header cells                                           
                            cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                            cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;

                        }
                        //Data row
                        else
                        {
                            cell.Range.Text = (cell.RowIndex - 2 + cell.ColumnIndex).ToString();
                        }
                    }
                }

                //Save the document
                object filename = @"C:\Users\user\Downloads\Path\sampleWordFile.docx";
                document.SaveAs2(ref filename);
                document.Close(ref missing, ref missing, ref missing);
                document = null;
                winword.Quit(ref missing, ref missing, ref missing);
                winword = null;
                MessageBox.Show("Document created successfully !");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

    }
Posted
Updated 2-Aug-22 1:28am
v2
Comments
0x01AA 2-Aug-22 13:57pm    
Can't explain it but: If I put add table for each table like this it works:

...
para1.Range.InsertParagraphAfter();
Table firstTable = document.Tables.Add(para1.Range, 5, 5, ref missing, ref missing);

// ... and same for secondTable and so on...
Manojkumar-dll 3-Aug-22 23:36pm    
Thanks!! it works

1 solution

To create another table you have to call Tables.Add(Range, Int32, Int32, Object, Object) Method (Microsoft.Office.Interop.Word)[^]

Assuming that you have a 9 paragraphs, you can insert into them 9 tables:
C#
//on the top of file
using Word = Microsoft.Office.Interop.Word;
//further
for(int i=0; i<9; i++)
{
  Word.Paragraph para = document.Content.Paragraphs[i+1];
  Word.Table table = document.Tables.Add(para.Range, 5, 5, ref missing, ref missing);
}


For further information, please see: How to: Programmatically create Word tables - Visual Studio (Windows) | Microsoft Docs[^]
 
Share this answer
 
v3
Comments
Manojkumar-dll 2-Aug-22 7:31am    
Thanks! i'll try and update asap
0x01AA 2-Aug-22 7:42am    
If I remember correctly, access to Paragraphs is '1' based, but I can be wrong ;)
Maciej Los 2-Aug-22 9:16am    
In VBA it can be 1 (as the first element in an array) if you use Option Base 1 instruction. :)
0x01AA 2-Aug-22 10:37am    
Just checked it. Accessing the Item '0' with Microsoft.Office.Interop.Word.Paragraph p = document.Content.Paragraphs[0]; gives an exception something like 'Element not in List' (and I have 35 Paragraphs in the document).
Also if I googl for c# examples, they always start at Index 1 for Word- Interop- Collections and most examples use foreach ;)
Maciej Los 2-Aug-22 15:14pm    
OK. I'll update my answer.
Thanks, Bruno.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900