Datatable To CSV

By Peter Bromberg

Often we need to convert a Datatable to a CSV - format file string to be able to save the file to the filesystem. Here's a neat little method to accomplish same

public string DataTableToCsv(DataTable dt)
        {
             var sb = new StringBuilder();
            var colStuff = dt.Columns.Cast<DataColumn>().Aggregate("", (current, col) => current + ("\"" + col.ColumnName + "\","));
            colStuff += "\r\n";
            sb.Append(colStuff);
             for (var x = 0; x < dt.Rows.Count; x++)
            {
                 var rowString = "";
                 for (var y = 0; y < dt.Columns.Count; y++)
                {
                    rowString += "\"" + dt.Rows[x][y].ToString() + "\",";

                }
                rowString += "\r\n";
                 sb.Append(rowString);
             }
             return sb.ToString();
        }

Datatable To CSV  (2224 Views)