export a list of table to CSV file
<p>I am trying to export a list of table to comma-separated value(CSV) .but not getting the correct output .output coming from this code is in the form of html table.
Here is my code,Help Me ....
Thanks</p>

<pre><code>      public void ExportToCsv()
      {

      DataClassesDataContext db = new DataClassesDataContext();
      var employee = db.Employees.ToList();
      var grid = new System.Web.UI.WebControls.GridView();
      grid.DataSource = employee;
      grid.DataBind();

      StringBuilder strbldr = new StringBuilder();

      for (int i = 0; i &lt; grid.Columns.Count; i++)
        {
            strbldr.Append(grid.Columns[i].HeaderText + ',');
        }
        for (int j = 0; j &lt; grid.Rows.Count; j++)
        {
            for (int k = 0; k &lt; grid.Columns.Count; k++)
            {
                //separating gridview columns with comma
                strbldr.Append(grid.Rows[j].Cells[k].Text + ',');
            }
            //appending new line for gridview rows
            strbldr.Append("\n");
        }
        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=YourFileName.csv");
        Response.ContentType = "text/csv";
        StringWriter sa = new StringWriter(strbldr);
        HtmlTextWriter ht = new HtmlTextWriter(sa);
        grid.RenderControl(ht);
        Response.Write(sa.ToString());
        Response.End();
    }
</code></pre>
