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.

Advertisements

B.E in Electronics and Telecommunications from Raipur, Chhattisgarh. Currently working on Microsoft's .NET and SQL Server Technology

Tagged with: , ,
Posted in ASP .NET

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: