DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Export DataSet To Excel In C#

08.19.2009
| 21041 views |
  • submit to reddit
        // description of your code here
exports a dataset to excel in csv format.

                DataSet ds = new DataSet();
                //load dataset "ds"
                ds = (DataSet)ViewState["CurrentDS"];
                DataView dv = new DataView(ds.Tables[0]);
                dv.Sort = "PercentClosed DESC";


                System.Text.StringBuilder builder = new System.Text.StringBuilder();
                DataTable dt = dv.Table;

                string headerToExport = string.Empty;

                foreach (DataColumn col in dt.Columns)
                    headerToExport += (char)34 + col.ColumnName + (char)34 + (char)44;

                headerToExport.Remove(headerToExport.Length - 1, 1);
                headerToExport = headerToExport + Environment.NewLine + Environment.NewLine;
                builder.Append(headerToExport);

                string body = string.Empty;

                foreach (DataRow row in dt.Rows)
                {
                    foreach (object obj in row.ItemArray)
                        body = body + obj.ToString() + (char)44;

                    body.Remove(body.Length - 1, 1);

                    body = body + Environment.NewLine;
                }

                builder.Append(body);
                builder.Append(Environment.NewLine);
                builder.Append(Environment.NewLine);


                Response.ContentType = "application/vnd.ms-excel";
                Response.AddHeader("content-disposition", "attachment;filename=myfile.csv");
                Response.Charset = "";
                Response.Write(builder.ToString());
                Response.Flush();
                Response.End();