Sunday, November 30, 2014

Export DataTable to CSV quick and dirty:

Export DataTable to CSV quick and dirty:

 static void DataTableToCSV(string path, DataTable table, bool isFirstRowHeader)
        {
            var lines = new List<string>(); 

            // headers
            if (isFirstRowHeader)
            {
                string[] colnames = table.Columns.Cast<DataColumn>().Select(column => column.ColumnName.Replace(",","")).ToArray();
                var header = string.Join(",", colnames);
                lines.Add(header);
            }
 
            // clean columns names
var valueLines = table.AsEnumerable()
                      .Cast<DataRow>()
                      .Select(row => string.Join(",", 
                              row.ItemArray
                                 .Select(o => "\"" + o.ToString().Replace(",","") + "\"")
.ToArray()));
 
            // Stuff the rows into a string joined by new line characters
            var allLines = string.Join(Environment.NewLine, valueLines.ToArray<string>());
            lines.Add(allLines);
 
            // put that file to bed
            File.WriteAllLines(path, lines.ToArray());
        }

 

No comments:

Post a Comment