Skip to main content
 首页 » 编程设计

c#之如何在 C# 中用制表符分隔的文本文件填充数据表

2024年02月20日1352php

我想用制表符分隔的文本文件填充数据表。文本文件包含如下数据:

Name   Id   Place 
Sam    2001   USA 
Raja    3455   India 
Allan    90101   Canada 

当我使用 OleDBConnection 将文本文件导入 DataTable 时,我在 DataTable 中获取数据如下:

Name_Id_Place 
Sam2001USA 
Raja3455India 
Allan90101Canada 

实际的文本文件有 3 列和 3 行,但在 DataTable 中,我将所有 3 列作为一个列 Name_Id_Place。

谁能告诉我这个问题的解决方案?

请您参考如下方法:

    static void Main() 
    { 
        //create a data table and add the column's 
        DataTable table = new DataTable("table_name"); 
        table.Columns.Add("name", typeof (String)); 
        table.Columns.Add("id", typeof (Int32)); 
        table.Columns.Add("place", typeof (String)); 
 
        //start reading the textfile 
        StreamReader reader = new StreamReader("file_to_read"); 
        string line; 
        while ((line = reader.ReadLine()) != null) 
        { 
            string[] items = line.Split('\t'); 
            //make sure it has 3 items 
            if (items.Length == 3) 
            { 
                DataRow row = table.NewRow(); 
                row["name"] = items[0]; 
                row["id"] = Int32.Parse(items[1]); 
                row["place"] = items[2]; 
                table.Rows.Add(row); 
            } 
        } 
        reader.Close(); 
        reader.Dispose(); 
 
        // make use of the table 
 
 
        // when use is done dispose it 
        table.Dispose(); 
    }