private void WriteDelimitedData(DataTable dt, string fileName, string delimiter)
    {
        //prepare the output stream
        Response.Clear();
        Response.ContentType = "text/csv";
        Response.AppendHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
        Response.ContentEncoding = System.Text.Encoding.UTF8;

        //write the csv column headers
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            Response.Write(dt.Columns[i].ColumnName);
            Response.Write((i < dt.Columns.Count - 1) ? delimiter : Environment.NewLine);
        }

        //write the data
        foreach (DataRow row in dt.Rows)
        {
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                Response.Write(row[i].ToString());
                Response.Write((i < dt.Columns.Count - 1) ? delimiter : Environment.NewLine);
            }
        }

        Response.End();
    }
Last modified: April 13, 2019

Author

Comments

Write a Reply or Comment