Wednesday, August 15, 2012

Export Data Table to CSV file with comma values

public void WriteCSVToResponse(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));
      
        //write the csv column headers
        if (dt != null && dt.Rows.Count > 0)
        {
           
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                if (dt.Columns[i].ColumnName != "FormsResponseXML")
                {
                    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++)
                {
                    if (dt.Columns[i].ColumnName != "FormsResponseXML")
                    {                       
                        var append = row[i].ToString().Contains(",")? string.Format("\"{0}\"", row[i].ToString()): row[i].ToString();
                        Response.Write(append);
                        Response.Write((i < dt.Columns.Count - 1) ? delimiter : Environment.NewLine);
                    }
                }
            }
        }

        Response.End();
    }

No comments: