Joseph Michael Pesch
VP Programming

Convert C# DataTable to Delimited File

by 22. August 2011 16:11

 

public static DataTable GetDataTableFromCsv(string FilePath)
{
  return GetDataTableFromDelim(FilePath, ",");
}
public static DataTable GetDataTableFromTab(string FilePath)
{
  return GetDataTableFromDelim(FilePath, @"\t");
}
public static DataTable GetDataTableFromDelim(string FilePath, string Delim)
{
  DataTable tbl = new DataTable();
  string CsvData = string.Empty;
  CsvData = File.ReadAllText(FilePath);
  bool firstRow = true;
  foreach (string row in CsvData.Split("\n".ToCharArray()))
  {
    DataRow dr = tbl.NewRow();
    System.Text.RegularExpressions.RegexOptions options = (
        System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace
      | System.Text.RegularExpressions.RegexOptions.Multiline
      | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    Regex reg = new Regex(Delim 
      + @"(?=(?:[^\""]*\""[^\""]*\"")*(?![^\""]*\""))", options);
    var csvArray = reg.Split(row.Replace("\n", "").Replace("\r", ""));
    for (int i = 0; i < csvArray.Length; i++)
    {
      csvArray[i] = csvArray[i].Replace("\"\"", "");
      if (firstRow)
        tbl.Columns.Add(new DataColumn() { ColumnName = csvArray[i] });
      else
        dr[i] = csvArray[i];
      Console.WriteLine(csvArray[i]);
    }
    if (!firstRow && !dr[0].ToString().Length.Equals(0)) tbl.Rows.Add(dr);
    firstRow = false;
  }
  return tbl;
}

private static string DelimTextFromTable(DataTable tbl, string delim)
{
  var sb = new StringBuilder();
  sb.AppendLine(string.Join(delim,
    tbl.Columns.Cast<DataColumn>().Select(arg => arg.ColumnName)));
  foreach (DataRow dataRow in tbl.Rows)
    sb.AppendLine(string.Join(delim,
      dataRow.ItemArray.Select(arg => arg.ToString())));
  return sb.ToString();
}

Tags:

C#

Comments are closed