Friday, July 8, 2011

Export Data to Excel/CSV file in asp.net

Hi,
We are frquentlu need this requirement to Export the Reports into Excel file.
Here the easy steps to Export to Excel.

1.We may have our Report Data in DataSet or List.

2.Create StreamWriter Object.
StringWriter sw = new StringWriter();
3.Add all Headers of your Report first.
sw.WriteLine("HEADER11,HEADER12,HEADER13,HEADER134,...);
4.Iterate the Data in foreach loop and write as below
For DataSet:

For List:


5.Finally write this to file as follow:

Response.AddHeader("Content-Disposition", "attachment; filename=FileName.csv");
Response.ContentType = "text/csv";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.Write(sw);
Response.End();

Have a Nice Day...

No comments:

Post a Comment