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

时间:2013-01-11 17:19:24

标签: c#

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

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

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

Name_Id_Place
Sam2001USA
Raja3455India
Allan90101Canada

实际的文本文件有3列3行,但在数据表中我将所有3列作为单列Name_Id_Place

有人可以告诉我这个问题吗?

2 个答案:

答案 0 :(得分:4)

    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();
    }

答案 1 :(得分:0)

这里我认为你以正确的方式从文本文件中读取数据,只有问题我看到你使用过的Provider无法理解列的结尾,那为什么将所有行读为一列

尝试使用OleDBConnection从文本文件中读取数据时,我得到了完全相同的结果。

在我作为提供者使用的connectionstring中:

Provider=Microsoft.Jet.OLEDB.4.0;

如果您使用了相同的内容,则只需在Windows注册表中更改此提供程序的“格式”选项:

HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ Jet \ 4.0 \ Engines \ Text 

然后将“Format”键修改为value =“TabDelimited”

或者如果你想使用其他分隔符(例如“;”) 然后Format =“Delimited(;)”