Export GridView Data into CSVFile In Asp.net 2.0

image

Steps.

1) Create Simple Web Application ( asp.net using C#).

2) put the below control in to the page (.aspx)

2.1) GridView (id= GridView1)

2.2) Button (id=button1 and Text =Create CSV File)

or put the below code

 
<form id="form1" runat="server">
<center>
<div>
<table>
    <tr>
      <td>
       Create CSV File
      </td>
     </tr>
     <tr>
       <td>
<asp:GridView ID="GridView1" runat="server"  CellPadding="4" ForeColor="#333333" GridLines="None">
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
                               <AlternatingRowStyle BackColor="White" />
</asp:GridView>
    </td>
    </tr>
     <tr>
     <td align="center">
 <asp:Button ID="Button1" runat="server" Text="Create CSV File" OnClick="Button1_Click" />
                       </td>
                   </tr>
               </table>
           </div>
       </center>
   </form>

3) assign data source to GridView. here i created dynamic dataset (on page load).  save the DataSet in to ViewState.

public DataSet MyData
    {
        get
        {
            if (ViewState["MyData"] == null)
               ViewState["MyData"] = new DataSet();
            return (DataSet)ViewState["MyData"];
        }
        set { ViewState["MyData"] = value; }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //create new data set
            DataSet Ds = new DataSet();
            //create new datatable
            DataTable dt = new DataTable();
            //create new column
       DataColumn dc1 = new DataColumn("Id");
       DataColumn dc2 = new DataColumn("Code");
       DataColumn dc3 = new DataColumn("Name");
       DataColumn dc4 = new DataColumn("datetime");

            //add column to datatable
            dt.Columns.Add(dc1);
            dt.Columns.Add(dc2);
            dt.Columns.Add(dc3);
            dt.Columns.Add(dc4);
            for (int i = 0; i < 10; i++)
            {
                //add new row in to datatable
                DataRow dr = dt.NewRow();
                dr["Id"] = i;
                dr["Code"] = "A" + i.ToString();
                dr["Name"] = "B" + i.ToString();
                dr["datetime"] = System.DateTime.Now.AddDays(Convert.ToDouble(i));
                dt.Rows.Add(dr);
            }
            Ds.Tables.Add(dt);
            MyData = Ds;
            GridView1.DataSource = MyData;
            GridView1.DataBind();
        }
        else
        {
            GridView1.DataSource = MyData;
            GridView1.DataBind();
        }
    }

4) Export GridView Data in to CSV format

protected void Button1_Click(object sender, EventArgs e)
   {
       try
       {
           //Create CSV file
           StreamWriter objSw = new StreamWriter(Server.MapPath("~/demo.csv"));
           //get table from GridView1
           DataTable objDt = ((DataSet)GridView1.DataSource).Tables[0];
           //Get No Of Column in GridView
           int NoOfColumn = objDt.Columns.Count;
           //Create Header
           for (int i = 0; i < NoOfColumn; i++)
           {
               objSw.Write(objDt.Columns[i]);
               //check not last column
               if (i < NoOfColumn - 1)
               {
                   objSw.Write(",");
               }
           }
           objSw.Write(objSw.NewLine);
           //Create Data
           foreach (DataRow dr in objDt.Rows)
           {
               for (int i = 0; i < NoOfColumn; i++)
               {
                   objSw.Write(dr[i].ToString());

                   if (i < NoOfColumn - 1)
                   {
                       objSw.Write(",");
                   }
               }
               objSw.Write(objSw.NewLine);
           }
           objSw.Close();
       }
       catch (Exception ex)
       {
           Response.Write("Can Not Generate CSV File");
       }
   }
Thanks.
Advertisements

5 comments

  1. very nice , i am unable to see the values in date type column.Instead of date #’s are displayed, how to solve this

  2. hi sreevi,
    i am not getting exactly what you say. i am understand only thing is in data column i am not give any datatype. i think you want that how to assign datatype to the data column.
    DataColumn dcol = new DataColumn(“columnName”, System.Type.GetType(“System.Decimal”));

  3. hey it not given option for open and save and cancel Please help mr

  4. Walter Neeckx · · Reply

    Hi, this is exactly what I need, but in VB, especially the line
    //get table from GridView1
    DataTable objDt = ((DataSet)GridView1.DataSource).Tables[0]

    Could you convert that to VB pls.
    thanks

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