Sunday, January 9, 2011

Export Excel From DataGrid using C#

Hi Guys.,
Using c# we need to Export To Excel from datagrid .Following Code will help For you


sample Code:

// create the DataGrid and perform the databinding
System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();
grid.HeaderStyle.Font.Bold = true;

DataSet ds = new DataSet();
ds.ReadXml("File Location");
grid.DataSource = ds.Tables[0];
//grid.DataMember = data.Stats.TableName;

grid.DataBind();

// render the DataGrid control to a file
using(StreamWriter sw = new StreamWriter(textBox1.Text))
{
using(HtmlTextWriter hw = new HtmlTextWriter(sw))
{
grid.RenderControl(hw);
}
}
}

No comments: