Wednesday, December 26, 2007

Creating MS-Word document from C#

In my workplace, I am developing procurement application. In this application, one of the requirement is to auto generate the tender form in MS-Word format for the selected vendors in the application. Vendor details and related informations are taken from the backend.

To auto generate the document, I did the following.
  1. Get the MS-Word template file (filename.dot), in which the format the client wants, from the client
  2. From the developer side, I create the bookmarks in which they want to auto populate data.
  3. In the project workspace I added the reference of Word COMponent. ( I have used MS Office 2007 Component)
  4. Use the following code to generate the doc file.

    // Include the following namespaces
    using Microsoft.Office.Core;
    using Microsoft.Office.Interop.Word;

    ....
    ....
    ....

    Microsoft.Office.Interop.Word.

    ApplicationClass wordApp = new Microsoft.Office.Interop.Word. ApplicationClass();

    string fileDesPath = @"C:\temp\output.doc";    // Output file
    object oTemplate = @"C:\temp\template.dot";   // Template file

    object fileDes = fileDesPath;
    object missing = System.Reflection. Missing.Value;
    object Visible=true;

    Microsoft.Office.Interop.Word.

    Document adoc = wordApp.Documents.Add(ref oTemplate, ref missing, ref missing, ref missing);

    object oBookMark = "name"; // In template we have to find the bookmark "name" to replace the real data
    adoc.Bookmarks.get_Item(
    ref oBookMark).Range.Text = "Prakash";

    object filename = fileDes;

    adoc.SaveAs(

    ref filename, ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing);

    wordApp.Visible =

    true;
    doc.Close(ref nullobj, ref nullobj, ref nullobj);

 

2 comments:

Anonymous said...

thanx for your article.
this's very useful 4 me

Anonymous said...

this article was very useful
thanx