Generate Msword Document using C#

When we enter the Name in txtName and father's name in txtFather and we press the "prepdocument" button it will ask to save for the document in desired location by name "MsWordSample.doc" and after opening the document file looks like:

Your name is: and Your father's name is:
"MS Word document generated successfully."

Here is the code:

<form id="form1" runat="server">
Write your name: <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator id="req1" runat="server" ControlToValidate="txtName" Text="*"></asp:RequiredFieldValidator>
<br />
<asp:Button ID="btn" runat="server" OnClick="GenerateMsWordDoc" Text="Generate Ms Word Document" />

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public class GenerateMsWord : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)



/// Fires when button is clicked

protected void GenerateMsWordDoc(object sender, EventArgs e)
string strBody = "<html>" +
"<body>" +
"<div>Your name is: <b>" + txtName.Text + "</b> and Your father's name is: <b>" + txtFather.Text +"</b></div>" +

"Ms Word document generated successfully." +
"</body>" +
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);

Thanks & Regards,


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: