It is very frequntly asked question in any of the forum or question-answer section on websites. So I decided to write a very compact article with source code.
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
<form id="form1" runat="server">
<div>
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" />
</div>
</form>
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 = "<html>" +
"<body>" +
"<div>Your name is: <b>" + txtName.Text + "</b></div>" +
"<table width="100%" style="background-color:#cfcfcf;"><tr><td>1st Cell body data</td><td>2nd cell body data</td></tr></table>" +
"Ms Word document generated successfully." +
"</body>" +
"</html>";
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);
}
Thats we have to do!!!.
Just download the sample code and start using it.