Click here to Skip to main content
15,881,139 members
Articles / DevOps / Automation
Tip/Trick

Word Automation using C#: Create a Word Table Programatically

Rate me:
Please Sign up or sign in to vote.
5.00/5 (6 votes)
13 Sep 2014CPOL3 min read 73.3K   3.8K   12   6
This tip gives you an idea about how to create Word table using C# (Word automation)

Introduction

Many times in real world scenario, we need to create our reports in Word file, need to export 'things' to Word file. In such cases, we need to create and write Word file programmatically and to accomplish the task COM winword interop library will play a role for you.

Using the Code

Our Aim: Create a Word file programmatically and create a table in it
Things we need: C#, Word interop object

wordC#

Here are the code steps we follow to get to our destination:

  1. Create a simple Windows/web/WPF application (You may use console application or class library too, here I have used Windows application in C# with Visual Studio 2010 and Microsoft Word 2007)
  2. Now just right click on solution explorer, click on Add reference and select COM tab
  3. Select Word com library (If you have Word 2007 installed, you will see 12.0 object library, if you have Word 2010 installed, you will see 14.0 object library and for Word 2013 you will see 16.0 object library)
    See the image below.

    Add_Reference

  4. Add reference. Now in reference folder of solution explorer, you will see 'Microsoft.Office.Interop.word' library added.
  5. Now we are ready to code, first we need to create a new Word document using C#.
  6. Import Word namespace and create Word object.
    See below snippet:
    C#
    Word._Application objApp;
    Word._Document objDoc;
    objApp = new Word.Application();
    objApp.Visible = true;
    objDoc = objApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
    

    With the help of the above code, we will be able to create a new Word file. (Note: Do not ever create new object of Word document.) .Visible property will open a new Word file.

  7. Now to add a new table in Word document, we need to define bookmark first (which is the range of Word document from which we need to start writing the things)
    See the below snippet to define default bookmark of Word document:
    C#
    object objMiss = System.Reflection.Missing.Value;
    object objEndOfDocFlag = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
    
  8. Yes, we have successfully defined 'end of doc' flag, now we can first add some caption to table with the help of Paragraph object (Paragraph object is a object which is used to write some text in Word document)
    See the below snippet:
    C#
    Word.Paragraph objPara1; //define paragraph object
    object oRng = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range; //go to end of the page
    objPara1 = objDoc.Content.Paragraphs.Add(ref oRng); //add paragraph at end of document
    objPara1.Range.Text = "Test Table Caption"; //add some text in paragraph
    objPara1.Format.SpaceAfter = 10; //define some style
    objPara1.Range.InsertParagraphAfter(); //insert paragraph
    

    Here, we have defined a paragraph and insert that paragraph to the end of the document.

  9. Now, we need to define rows and columns for table that we need to draw. Here, I have drawn a table with 2 rows and 2 columns.
    In code, simply go to the end of the document and create 2X2 table, see the below snippet:
    C#
    Word.Table objTab1;
    Word.Range objWordRng = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range;
    objTab1 = objDoc.Tables.Add(objWordRng, 2, 2, ref objMiss, ref objMiss);
    objTab1.Range.ParagraphFormat.SpaceAfter = 6;
    int iRow, iCols;
    string strText;
    for (iRow = 1; iRow <= 2; iRow++)
      for (iCols = 1; iCols <= 2; iCols++)
          {
            strText = "r" + iRow + "c" + iCols;
            objTab1.Cell(iRow, iCols).Range.Text = strText;
          }
    objTab1.Rows[1].Range.Font.Bold = 1;
    objTab1.Rows[1].Range.Font.Italic = 1;
    

    Here, we have created a 'word.table' object and added some text with the help of Range object.

    C#
    //Add text after the table.
    objWordRng = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range;
    objWordRng.InsertParagraphAfter();
    objWordRng.InsertAfter("THE END.");
    

We are done with the task. Let's checkout the final code.

C#
object objMiss = System.Reflection.Missing.Value;
object objEndOfDocFlag =
        "\\endofdoc"; /* \endofdoc is a predefined bookmark */
//Start Word and create a new document.
Word._Application objApp;
Word._Document objDoc;
objApp = new Word.Application();
objApp.Visible = true;
objDoc = objApp.Documents.Add(ref objMiss, ref objMiss,
ref objMiss, ref objMiss);
//Insert a paragraph at the end of the document.
Word.Paragraph objPara2; //define paragraph object
object oRng = objDoc.Bookmarks.get_Item
            (ref objEndOfDocFlag).Range; //go to end of the page
objPara2 = objDoc.Content.Paragraphs.Add
            (ref oRng); //add paragraph at end of document
objPara2.Range.Text = "Test Table Caption"; //add some text in paragraph
objPara2.Format.SpaceAfter = 10; //define some style
objPara2.Range.InsertParagraphAfter(); //insert paragraph
//Insert a 2 x 2 table, (table with 2 row and 2 column)
Word.Table objTab1; //create table object
Word.Range objWordRng = objDoc.Bookmarks.get_Item
            (ref objEndOfDocFlag).Range; //go to end of document
objTab1 = objDoc.Tables.Add(objWordRng, 2, 2,
            ref objMiss, ref objMiss); //add table object in word document
objTab1.Range.ParagraphFormat.SpaceAfter = 6;
int iRow, iCols;
string strText;
for (iRow = 1; iRow <= 2; iRow++)
   for (iCols = 1; iCols <= 2; iCols++)
   {
     strText = "row:" + iRow + "col:" + iCols;
     objTab1.Cell(iRow, iCols).Range.Text = strText; //add some text to cell
   }
objTab1.Rows[1].Range.Font.Bold = 1; //make first row of table BOLD
objTab1.Columns[1].Width = objApp.InchesToPoints(3); //increase first column width
//Add some text after table
objWordRng = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range;
objWordRng.InsertParagraphAfter(); //put enter in document
objWordRng.InsertAfter("THIS IS THE SIMPLE WORD DEMO : THANKS YOU.");
object szPath = "test.docx";
objDoc.SaveAs(ref szPath);

Summing Up

So, we have seen with the help of a little bit of code, we can develop a nice Word table application.
If you want to download the source code, then you may do so from the link at the top of the post.

Finally

COM interop is not a single cup of tea. There are thousands of things we need to discuss, we can cover them one by one in later articles.

Suggestions and doubts are welcome.

Thank you for reading.

License

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


Written By
Technical Lead
India India
Hi there, I am Prasad. Author, Blogger, contributor and passionate about Microsoft .NET technologies. I like to write an articles/blogs on different .NET aspects and like to help Developers, to resolve their issues and boost them on Microsoft Technologies.


Certifications: Microsoft Certified professional (MCP), Microsoft Certified technology specialist (MCTS), Agile-Scrum Master.


Awards: Microsoft Re-connect MVP (GSC Member), Most valuable member at dotnetspider, Most popular curator, Most active curator, featured curator at Microsoft Curah, Editor at dotnetspider.


Microsoft MVP 2014 [ASP.NET/IIS]
Click here for more .NET Tips
-After all Knowledge is an endless entity

Comments and Discussions

 
QuestionThanks! very useful!. However, consider using MailMerge as Templates. Pin
Member 1376839717-Apr-18 3:03
Member 1376839717-Apr-18 3:03 
Questionoffice.dll location Pin
subbus689127-Oct-15 21:57
subbus689127-Oct-15 21:57 
AnswerRe: office.dll location Pin
koolprasad200328-Oct-15 2:46
professionalkoolprasad200328-Oct-15 2:46 
Questionit is good! it's my wanted! Pin
Tony Lee Cn22-Jul-15 18:21
Tony Lee Cn22-Jul-15 18:21 
QuestionVery Useful Pin
gggustafson24-Jan-15 15:24
mvagggustafson24-Jan-15 15:24 
GeneralMy Vote is 5 Pin
Umesh Bhosale18-Dec-14 23:52
Umesh Bhosale18-Dec-14 23:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.