Friday, January 4, 2008

How To Export Datatable To CSV Format in ASP.NET

  1. Create a new Web Application in VS.NET
  2. Add a button control to the page .
  3. write down following code in the click event of the button
    protected void Button1_Click(object sender, EventArgs e)
    {

        string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

        SqlConnection conn = new SqlConnection(strConn);

        SqlDataAdapter da = new SqlDataAdapter("select * from tablename ", conn);

        DataSet ds = new DataSet();

        da.Fill(ds, "tbl");

        GridView1.DataSource = ds.Tables["tbl"].DefaultView;

        GridView1.DataBind();

        DataTable dt = ds.Tables["Emp"];

        CreateCSVFile(dt, "c:\\csvData.csv");

    }

 public void CreateCSVFile(DataTable dt, string strFilePath)
    {
        // Create the CSV file to which grid data will be exported.
        StreamWriter sw = new StreamWriter(strFilePath, false);
        // First we will write the headers.

        int iColCount = dt.Columns.Count;
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dt.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);
        // Now write all the rows.
        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    sw.Write(dr[i].ToString());
                }
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();
    }

No comments:

Post a Comment