Export datatable to CSV (Comma Separated Values) in Asp.net.


DataTable to CSV format.

          
DataTable dtData = GetDataTable()//Your data to Export;
string sFileName = "Export";
if (dtData.Rows.Count > 0)
{
bool bHeader;
if (cbWithHeader.Checked == true)
    bHeader = true;
else
    bHeader = false;
                
string strData = Export(dtData, bHeader);
byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(strData);
Response.Clear();
Response.AddHeader("Content-Type", "application/vnd.ms-excel");
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFileName);
Response.BinaryWrite(data);
Response.End();
Response.Close();
}
else
{
   "No records found!";
}
public string Export(DataTable dt, bool exportColumnHeadings)
{
    string header = string.Empty;
    string body = string.Empty;
    string record = string.Empty;
    // If you want column to be part of the CSV ...
    if (exportColumnHeadings)
    {
        foreach (DataColumn col in dt.Columns)
        {
            header = header + col.ColumnName + ",";
        }
        header = header.Substring(0, header.Length - 1);
    }
    // Iterate into the rows
    foreach (DataRow row in dt.Rows)
    {
        Object[] arr = row.ItemArray;
        for (int i = 0; i < arr.Length; i++)
        {
            DataColumn dc = dt.Columns[i];
            if (!Convert.IsDBNull(row[i]))
            {
                record = record + arr[i].ToString() + ",";
            }
            else
            {
                record = record + ",";
            }
        }

        body = body + record.Substring(0, record.Length - 1) + Environment.NewLine; record = "";
    }
    if (exportColumnHeadings)
    {
        return (header + Environment.NewLine + body);
    }
    else
    {
        return body;
    }
}