Home > Code > ASP.NET > Export to CSV file from Data Table in Asp.net

Export to CSV file from Data Table in Asp.net

by Thamil   on Nov 01, 2012   Category: ASP.NET   |  Views: 21413    |  Points: 25   |  Gold 


In most of the projects, we may need to have export the data to csv file from grid view or data table. See the below c# sample code to export the data from data table to .csv file in a simple way.

Load data into Datatable
 DataTable dtTable = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
DataRow dtRow;

dtTable.Columns.Add("No", typeof(int));
dtTable.Columns.Add("Name", typeof(string));

for (int i = 0; i <= 9; i++)
{
dtRow = dtTable.NewRow();
dtRow[0] = i;
dtRow[1] = "Name " + i.ToString();
dtTable.Rows.Add(dtRow);
}
//Bind it to gridview
GridView1.DataSource = dtTable;
GridView1.DataBind();
}

Export to .CSV file
protected void BtnExporttoCSV_Click(object sender, EventArgs e)
{
Response.ContentType = "Application/x-msexcel";
Response.AddHeader("content-disposition", "attachment;filename=test.csv");
Response.Write(ExportToCSVFile(dtTable));
Response.End();
}

DataTable to stringbuilder
private string ExportToCSVFile(DataTable dtTable) 
{
StringBuilder sbldr = new StringBuilder();
if (dtTable.Columns.Count != 0)
{
foreach (DataColumn col in dtTable.Columns)
{
sbldr.Append(col.ColumnName + ',');
}
sbldr.Append("\r\n");
foreach (DataRow row in dtTable.Rows)
{
foreach (DataColumn column in dtTable.Columns)
{
sbldr.Append(row[column].ToString() + ',');
}
sbldr.Append("\r\n");
}
}
return sbldr.ToString();
}






Post Code  |  Code Snippet Home

User Responses


No response found, be the first to review this code snippet.

Submit feedback about this code snippet

Please sign in to post feedback

Latest Posts