导入带有“,”作为分隔符的文件

时间:2017-10-09 07:19:23

标签: c# datagridview

我试图阅读的文件看起来像这样:

123,123,123h123m,123123123

我有以下代码试图阅读:

public DataTable DataTableFromTextFile(string location, char delimiter = ',')
{
    DataTable result;

    string[] LineArray = File.ReadAllLines(path);

    result = FormDataTable(LineArray, delimiter);

    return result;
}

private static DataTable FormDataTable(string[] LineArray, char delimiter)
{
    DataTable dt = new DataTable();

    AddColumnToTable(LineArray, delimiter, ref dt);

    AddRowToTable(LineArray, delimiter, ref dt);

    return dt;
}

private static void AddRowToTable(string[] valueCollection, char delimiter, ref DataTable dt)
{

    for (int i = 1; i < valueCollection.Length; i++)
    {
        string[] values = valueCollection[i].Split(delimiter);
        DataRow dr = dt.NewRow();
        for (int j = 0; j < values.Length; j++)
        {
            dr[j] = values[j];
        }
        dt.Rows.Add(dr);
    }
}

private static void AddColumnToTable(string[] columnCollection, char delimiter, ref DataTable dt)
{
    string[] columns = columnCollection[0].Split(delimiter);
    foreach (string columnName in columns)
    {
        DataColumn dc = new DataColumn(columnName, typeof(string));
    }
}

但它似乎还没有奏效。我尝试过改变一些东西,但后来又在DataGridView中添加了空格(称为infoTabelle)。 有人能帮我解决问题吗?

**** EDIT 现在解决了这一切。我改变了将我的分隔文本放入DataGridView的方法。现在就像魅力一样工作。**

1 个答案:

答案 0 :(得分:1)

你正在寻找这样的东西:

// Simple: quotation "..." e.g. "123,456",789 is not implemented 
private static DataTable FromCsvSimple(string path, char delimiter = ',') {
  // Try avoiding ReadAllLines; use ReadLines
  // Where - let's skip empty lines (if any)
  var lines = File
    .ReadLines(path)
    .Where(line => !string.IsNullOrWhiteSpace(line))
    .Select(line => line.Split(delimiter));

  DataTable result = new DataTable();

  foreach (string[] items in lines) {
    // Do we have any columns to add?
    for (int c = 0; c < items.Length; ++c) 
      while (c >= result.Columns.Count)
        result.Columns.Add();

    result.Rows.Add(items);
  }

  return result;
}

...

DataTable myTable = FromCsvSimple(@"c:\MyCsv.csv", ';');