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:
"MS Word document generated successfully."
Here is the code:
<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>
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>" +
"</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);
}
}
Thanks & Regards,
Ramgopal