Skip to content

DataGrid/Gridview to Excel file generation

I have often feel the need for developers to generate an Excel report requirement. Here is a small code snippet to produce the same.

C# Code

string path = Path.GetTempFileName();
StreamWriter writer = new StreamWriter(path);
HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
Response.ContentType = “application/x-msexcel”;

DataGrid grid = new DataGrid();
grid.DataSource = data; //data to be written in the excel file
grid.DataBind();
grid.RenderControl(htmlWriter);

htmlWriter.Flush();
htmlWriter.Close();
writer.Close();

Response.WriteFile(path);
Response.End();

Hope it helps.

Published inASP .NET
LinkedIn
Share
WhatsApp