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
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 < grid.Columns.Count; i++)
{
strbldr.Append(grid.Columns[i].HeaderText + ',');
}
for (int j = 0; j < grid.Rows.Count; j++)
{
for (int k = 0; k < 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();
}
I think First you convert your list to datatable by using below code
Then Use below code for export datatable to csv..
Main Function is : This