Wednesday, July 23, 2014

Create a word table using C# : Word Automation step by step

Our Aim: Create a word file programmatically and create a table in it


Things we need : C#, Word interop object


Word Automation


Getting started

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

follow the steps below to know how to do it
1. Create a simple windows/web/wpf application (You may take console application or class library too, here I have used windows application in C# with Visual studio 2010)
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 below snap

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 snap
 
   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 above code we can 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 below snap to define default bookmark of word document

 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 used to write some text in word document)
see below snap

 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; //defind some style  
 objPara1.Range.InsertParagraphAfter(); //insert paragraph  

Here we have define a paragraph and insert that paragraph to end of the document.
9. Now we need to define a rows and columns for table that we need to draw. Here I have draw a table with 2 rows and 2 columns
In code, Simply go to the end of the document and create 2X2 table, see below snippet

  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 create a 'word.table' object and add some text with the help of Range object
 
  //Add text after the chart.  
       objWordRng = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range;  
       objWordRng.InsertParagraphAfter();  
       objWordRng.InsertAfter("THE END.");  

We have done with the task. lets checkout the final code as Whole
C#

checkout here,
       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; //defind 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 bit code, we can develop a nice word table application.
If you want to download source code then you may follow the link
Click here to download Source Code

Finally
COM interop is not a single cup of tea, There are thousands of things needs to discuss, we can cover them one by one in later article
Suggestions and Doubts are welcome.

Thanking You
-Prasad
 

7 comments:

  1. Want to learn C# from basics & in most professional Code development style. I'll have you writing real working applications in no time flat-before you reach the end of course.
    Hire C# Teacher.

    ReplyDelete
  2. IT's very informative blog and useful article thank you for sharing with us , keep posting learn more From
    .NET Online Training

    ReplyDelete
  3. Prasad Daily Dotnet Tricks: Create A Word Table Using C : Word Automation Step By Step >>>>> Download Now

    >>>>> Download Full

    Prasad Daily Dotnet Tricks: Create A Word Table Using C : Word Automation Step By Step >>>>> Download LINK

    >>>>> Download Now

    Prasad Daily Dotnet Tricks: Create A Word Table Using C : Word Automation Step By Step >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete