Online: 22887
Exporting the data to MS Word is similar to exporting data into MS Excel, only the ContentType and the file name extension changes
CONTROLLER ACTION METHOD
// GET: ExportData
public ActionResult ExportToWord()
{
// get the data from database
var data = db.PersonalDetails.ToList();
// instantiate the GridView control from System.Web.UI.WebControls namespace
// set the data source
GridView gridview = new GridView();
gridview.DataSource = data;
gridview.DataBind();
// Clear all the content from the current response
Response.ClearContent();
Response.Buffer = true;
// set the header
Response.AddHeader("content-disposition", "attachment;
filename=itfunda.doc");
Response.ContentType = "application/ms-word";
Response.Charset = "";
// create HtmlTextWriter object with StringWriter
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// render the GridView to the HtmlTextWriter
gridview.RenderControl(htw);
// Output the GridView content saved into StringWriter
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
return View();
}
Notice the above code snippet and focus on the highlighted words. Note that Response.ContentType is “application/ms-word” and the file name extension is “.doc”.
Calling the above action method asks user to save or download the file like below.
OUTPUT
