拆分文件.txt以填充Datatable C#

时间:2015-05-29 07:55:18

标签: c#

我需要帮助, 我有如下文件txt:

Jhonathan   Car   17000
Tony        Bike   4000
Mika        Home  20000

然后我想将此文件.txt加载到带分割的数据表(''),我确实创建了如下代码

DataTable dt = new DataTable();
dt.Columns.Add("COL1"); dt.Columns.Add("COL2"); dt.Columns.Add("COL3");
string[] aa = File.ReadAllLines(txtFileName);
       foreach (var item in aa)
   {
       DataRow dr = dt.NewRow();
       dr[0] = item.ToString();
       dt.Rows.Add(dr);
   }
   dataGridView3.DataSource = dt;

}

我希望结果如下: 真实结果:

COL1       | COL2   | COL3 
----------------------------     
Jhonathan  | Car    |17000
Tony       | Bike   |4000
Mika       | Home   |20000

但是我的代码的结果与预期不符,结果如下: 结果失败:

 COL1                   | COL2    | COL3 
-------------------------------------------     
 Jhonathan  Car   17000 |         |
 Tony       Bike  4000  |         |
 Mika       Home  20000 |         |

所以如何分割结果就像真实结果一样。 谢谢: - )

2 个答案:

答案 0 :(得分:4)

正则表达式解决方案

// regular expression for split row:
Regex parser = new Regex(@"\s+");

// modified code (replace with your file path)
DataTable dt = new DataTable();
dt.Columns.Add("COL1"); dt.Columns.Add("COL2"); dt.Columns.Add("COL3");
string[] lines = File.ReadAllLines(@"D:\Temp\text.txt");
foreach (var line in lines)
{
    DataRow dr = dt.NewRow();
    string[] words = parser.Split(line);
    dr[0] = words[0];
    dr[1] = words[1];
    dr[2] = words[2];
    dt.Rows.Add(dr);
}

固定字符串掩码解决方案

// fixed length mask (number of charachers for each field except last field)
int[] mask = { 12, 6 };
int maskLength = mask.Length;

// modified code (replace with your file path)
DataTable dt = new DataTable();
dt.Columns.Add("COL1"); dt.Columns.Add("COL2"); dt.Columns.Add("COL3");
string[] lines = File.ReadAllLines(@"D:\Temp\text.txt");
foreach (var line in lines)
{
    DataRow dr = dt.NewRow();
    int pos = 0;
    for (int i = 0; i < maskLength; pos += mask[i++])
    {
        dr[i] = line.Substring(pos, mask[i]).Trim();
    }
    dr[maskLength] = line.Substring(pos).Trim();
    dt.Rows.Add(dr);
}

答案 1 :(得分:1)

我宁愿将提取例程转换为方法,它将CSV类型(在您的情况下是制表分隔文件)转换为表格:

private static DataTable FileToTable(String fileName) {
  DataTable result = new DataTable();

  foreach (var line in File.ReadLines(fileName)) {
    DataRow row = result.NewRow();

    //TODO: you may want tabulation ('\t') separator as well as space
    String[] items = line.Split(new Char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
    // Columns adjusting: you don't need exactly 3 columns  
    for (int i = result.Columns.Count; i < items.Length; ++i) 
      result.Columns.Add(String.Format("COL {0}", i + 1));

    row.ItemArray = items;
    result.Rows.Add(row);
  }

  return result;
}

...

dataGridView3.DataSource = FileToTable(txtFileName);