Tuesday, January 22, 2008

Exporting the DataGrid to a Word file

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!IsPostBack)
{
SqlConnection conn = new SqlConnection ("data source=(local);initial catalog=Northwind;Pwd=xxxxxx;User ID=sa");
SqlCommand cmd = new SqlCommand ("Select LastName, FirstName, Title, TitleOfCourtesy, BirthDate, HireDate, Address, City, Region, PostalCode, Country from Employees", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
myDataGrid.DataSource = ds.Tables[0];
myDataGrid.DataBind();
}

}

private void Button2_Click(object sender, System.EventArgs e)
{
// export to word
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");

Response.Charset = "";

Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.ContentType = "application/vnd.word";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();

System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

myDataGrid.RenderControl(htmlWrite);

Response.Write(stringWrite.ToString());

Response.End();

}

No comments: