Thursday, May 15, 2008

Export DataGrid to a Excel Spreadsheet

Here is the code to do that:

Steps:
1. Load your DataGrid any way you want.
2. Name your DataGrid to be grdDataGrid.
3. Add a new button on the page "Button1".
4. Copy and Paste following code, and you are done.

*****************************************************
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();

Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", "test"));
Response.Charset = "";

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

StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

grdDataGrid.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.Flush();
Response.End();
}

public override void VerifyRenderingInServerForm(Control control)
{

}
*******************************************************



When you click on the button1, the following dialog window will show up.





I hope it helps, please feel free to contact me if you have any question/comments.

Thanks,
Sanjeev

No comments: