Surendra Sharma

Surendra Sharma

Search This Blog

Friday, June 4, 2010

Create word document from Template & pass data from .NET


using

Microsoft.Office.Core;

using Word;




private

void ParseWord()


{


 


    Word.ApplicationClass
myWordApp = new Word.ApplicationClass();


    Word.Document myWordDoc
= new Word.Document();


 


   
object missing = System.Reflection.Missing.Value; // our
'void' value


   
object filename =
@"E:\My Files\WordTest\Master5.dot"
; // our
word template


   
object destination =
@"E:\My Files\WordTest\ABC4.doc"
; 
// our target filename


   
object notTrue = false;  // our
boolean false

 

 


   
string myText =
"Hello World!!"
;


   
// the sample text we want as replacement

 


    myWordApp.Visible =
false;  //
tell word not to show itself

 


    myWordDoc =
myWordApp.Documents.Add( // load the template into a
document workspace


                         
ref filename,  // and
reference it through our myWordDoc


                         
ref missing,


                         
ref missing,


                         
ref missing);


 


   
// count how many fields we have to update


   
foreach (Field myField
in
myWordDoc.Fields)


    {


       
myField.Select();


       
string str = myField.Code.Text;


       
myWordApp.Selection.TypeText(DateTime.Now.ToString());


    }


 


   
//


   
// now the last touch.. save and close


   
//


    myWordDoc.SaveAs(


            
ref destination,


            
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);


 


   
// quit word


   
myWordApp.Application.Quit(


            
ref notTrue,


            
ref missing,


            
ref missing);

}

No comments:

Post a Comment