ASP.NET - Datatable to CSV file! - Asked By myzonal.com myzonal.com on 29-Jun-12 02:55 AM

Jitendra Faye replied to myzonal.com myzonal.com on 29-Jun-12 02:56 AM
same post

refer this link-

http://www.eggheadcafe.com/community/csharp/2/10461409/i-have-records-in-datatable-then-create-csv-file-not-using-gridview.aspx


S K replied to myzonal.com myzonal.com on 29-Jun-12 03:06 AM
Best and simply way you can run the query in Query Analyser and output just copy/paste into excel file.
But if you want to go with process than try this way
There are option in Sql Server Management Studio to create CSV file from database
So you just select the database and right-click on it and select Tasks->Export Data.
There are options to export to different kinds of formats including CSV so you just select the csv in your case.

hope this helps you
thanks you
Lalit M replied to myzonal.com myzonal.com on 29-Jun-12 03:08 AM
Use below code sample
-----------
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 employees", conn);
      DataSet ds = new DataSet();
      da.Fill(ds, "Emp");
      GridView1.DataSource = ds.Tables["Emp"].DefaultView;
      GridView1.DataBind();
      DataTable dt = ds.Tables["Emp"];
      CreateCSVFile(dt, "c:\\csvData.csv");
    }
    public void CreateCSVFile(DataTable dt, string strFilePath)
    {
      #region Export Grid to CSV
      // Create the CSV file to which grid data will be exported.
      StreamWriter sw = new StreamWriter(strFilePath, false);
     // First we will write the headers.
      //DataTable dt = m_dsProducts.Tables[0];
      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();
      #endregion
    }

show more reference code
--------------------
http://codesimplified.com/2011/04/21/datatable-to-csv-file-and-csv-file-to-dataset-in-asp-net/
http://beyondrelational.com/modules/2/blogs/374/posts/7661/datatable-to-csv-file-and-csv-file-to-dataset-in-aspnet.aspx