Pages

Men

rh

7/08/2014

How to export the data from Dataset to CSV format in Asp.net with c#


Requried Name spaces :

using System.Text;



protected void btnTextExport_Click(object sender, ImageClickEventArgs e)
        {
            DataSet ds = new DataSet();
            if (Session["RoleName"].ToString() == "GlobalAdmin")
            {
                ds = objUser.Get3CReportRawData(Convert.ToInt32(ddlSupplierNames.SelectedValue.ToString().Trim()));
            }
            else
            {
                ds = objUser.Get3CReportRawData(Convert.ToInt32(Session["UserId"].ToString().Trim()));
            }

            if (ds.Tables[0].Rows.Count > 0)
            {
                Response.Clear();


                Response.Buffer = true;


                Response.AddHeader("content-disposition", "attachment; filename=" + "3c" + filename + "-alt.csv");


                Response.Charset = "";


                Response.ContentType = "application/text";
                

                StringBuilder sb = new StringBuilder();

                for (int k = 0; k < ds.Tables[0].Columns.Count; k++)
                {
                    if ((ds.Tables[0].Columns[k].ColumnName.Length <= 5) || ((ds.Tables[0].Columns[k].ColumnName.Length > 5 && ds.Tables[0].Columns[k].ColumnName.Substring(ds.Tables[0].Columns[k].ColumnName.Length - 6, 6) != "Header") && (ds.Tables[0].Columns[k].ColumnName != "UserId") && (ds.Tables[0].Columns[k].ColumnName != "ReportLevel")))
                    {
                        sb.Append(ds.Tables[0].Columns[k].ColumnName + ',');
                    }
                }
                sb.Append("\r\n");
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    for (int k = 0; k < ds.Tables[0].Columns.Count; k++)
                    {
                        if ((ds.Tables[0].Columns[k].ColumnName.Length <= 5) || ((ds.Tables[0].Columns[k].ColumnName.Length > 5 && ds.Tables[0].Columns[k].ColumnName.Substring(ds.Tables[0].Columns[k].ColumnName.Length - 6, 6) != "Header") && (ds.Tables[0].Columns[k].ColumnName != "UserId") && (ds.Tables[0].Columns[k].ColumnName != "ReportLevel")))
                        {
                            sb.Append(ds.Tables[0].Rows[i][k].ToString().Replace(",", ";") + ',');
                        }
                    }
                    sb.Append("\r\n");
                }
                Response.Output.Write(sb.ToString());


                Response.Flush();


                Response.End();

            }

        }

No comments :

Post a Comment