Wednesday 20 February 2013

Export DataTable To MicroSoft Word In C#

we have Export the DataTable as a Word Format. I hope the below code is useful to us.

using System;
using System.Data;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.UI;

protected void Page_Load(object sender, EventArgs e)
    {
        ExportToWord();
    }

protected void ExportToWord()
    {      
        DataTable dt = new DataTable();
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Qualification", typeof(string));
        dt.Rows.Add("Raja", "M.B.A");
        dt.Rows.Add("Durai", "M.B.B.S");
        dt.Rows.Add("SRD", "BE");
        //Create a dummy GridView
        GridView GridView1 = new GridView();
        GridView1.AllowPaging = false;
        GridView1.DataSource = dt;
        GridView1.DataBind();
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition",
        "attachment;filename=DataTable.doc");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-word ";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.RenderControl(hw);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }
 

2 comments: