Export DataTable to Excel/CSV C#


protected void btnExport_Click(object sender, EventArgs e)
    {
        DataTable dtTable = new DataTable();
        DataRow dtRow;

        dtTable.Columns.Add("SNo", typeof(int));
        dtTable.Columns.Add("Address", typeof(string));

        for (int i = 0; i <= 9; i++)
        {
            dtRow = dtTable.NewRow();
            dtRow[0] = i;
            dtRow[1] = "Address " + i.ToString();
            dtTable.Rows.Add(dtRow);
        }

        Response.ContentType = "Application/x-msexcel";
        Response.AddHeader("content-disposition", "attachment;filename=test.csv");
        Response.Write(ExportToCSVFile(dtTable));
        Response.End();
    }

    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();
    }
}

Share