How to export DataGrid data to excel

Platform: ASP.NET|Category: DataGrid

Use namespace System.IO

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        	’Put user code to initialize the page here
        	’Bind the DataGrid to DataSet
        	DataGridToExcel(DataGrid1, Response)
End Sub

Protected Sub DataGridToExcel(ByVal dGridExport As DataGrid, ByVal httpResp As HttpResponse)
        	httpResp.Clear()
        	httpResp.Charset = ''
        	httpResp.ContentType = 'application/vnd.ms-excel'
        	Dim stringWrite As New StringWriter
        	Dim htmlWrite As New HtmlTextWriter(stringWrite)
        	Dim dGrid As New DataGrid
        	dGrid = dGridExport
        	dGrid.HeaderStyle.Font.Bold = True
        	dGrid.DataBind()
        	dGrid.RenderControl(htmlWrite)
        	httpResp.Write(stringWrite.ToString)
        	httpResp.End()
End Sub

C#

private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	//Bind the DataGrid to DataSet
	DataGridToExcel (DataGrid1, Response);
}
protected void DataGridToExcel(DataGrid dGridExport  ,    HttpResponse httpResp)
{
	httpResp.Clear();
	httpResp.Charset = '';
	httpResp.ContentType = 'application/vnd.ms-excel';
	StringWriter stringWrite = new  StringWriter();
	HtmlTextWriter htmlWrite = new  HtmlTextWriter(stringWrite);
	DataGrid dGrid = new DataGrid();
	dGrid = dGridExport;
	dGrid.HeaderStyle.Font.Bold = true;
	dGrid.DataBind();
	dGrid.RenderControl(htmlWrite);
	httpResp.Write(stringWrite.ToString());
	httpResp.End();
}