How to convert Gridview to word document

Abstract


Here we will discuss about how to convert Gridview to Word Document using asp.net C#.
Drag and drop the Grid view control to your web page and call the LoadData() on page load event.


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}

private void LoadData()
{
try
{
SqlConnection con = new SqlConnection();
con = new SqlConnection("server=servername;uid=userid;password=password;database=databasename;");
con.Open();
string sql = ("select userid,username from Tablename");
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataSet resultData = new DataSet();
da.Fill(resultData);
GridView1.DataSource = resultData;
GridView1.DataBind();
con.Close();
if (resultData.Tables[0].Rows.Count > 0)
{
Convert(resultData, Response);
}

}
catch (Exception ex)
{
// Response.Write(ex.ToString());
}


}


public void Convert(DataSet ds, HttpResponse response)
{

//*********Export to Excel/Doc**************
//Let's clean up the response.object

response.Clear();
response.Charset = "";
response.ContentType = "application/msword"; // doc export
//create a string writer
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
//create an htmltextwriter which uses the stringwriter
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
//instantiate a datagrid
DataGrid dg = new DataGrid();
//set the datagrid datasource to the dataset passed in
dg.DataSource = ds.Tables[0];
//bind the datagrid
dg.DataBind();
//tell the datagrid to render itself to our htmltextwriter
dg.RenderControl(htmlWrite);
//all that's left is to output the html
response.Write(stringWrite.ToString());
response.End();

}

}

No comments:

Post a Comment

Plz Share your comments...