Friday, 15 February 2013

Generating Ms Word document in ASP.NET and C#



 

Lets start with creating a simple .aspx page where we will give a text box to enter user's Name and a button to click on. After clicking on the button Ms Word document will be generated. 

.aspx page

The code will be 


   

        Write your name:

       

       

       

   

   


When button will be clicked, GenerateMsWordDoc event will fire. 

Now lets write the code behind code. What we are going to do here is we are generating a dynamic html content based on the textbox value. Also we are writing one table with 2 cell and at last we are adding some text. 

.cs file code



protected void GenerateMsWordDoc(object sender, EventArgs e)

    {

        string strBody = "" +

            "" +

                "
Your name is: " + txtName.Text + "
" +

                "
1st Cell body data2nd cell body data
" +

                "Ms Word document generated successfully." +

            "
" +

            "
";

        string fileName = "MsWordSample.doc";

        // You can add whatever you want to add as the HTML and it will be generated as Ms Word docs

        Response.AppendHeader("Content-Type", "application/msword");

        Response.AppendHeader ("Content-disposition", "attachment; filename="+ fileName);

        Response.Write(strBody);

    }

No comments:

Post a Comment

Comment Here