[英]How to Fill a Datatable with a tab delimited text file in C#?
I want to fill a DataTable with a tab delimited Text file. 我想用制表符分隔的文本文件填充DataTable。 The text file contains data as follows: 文本文件包含以下数据:
Name Id Place
Sam 2001 USA
Raja 3455 India
Allan 90101 Canada
When I use OleDBConnection
to import the text file into the DataTable, I am getting data in DataTable as follows: 当我使用OleDBConnection
将文本文件导入到DataTable中时,我正在DataTable中获取数据,如下所示:
Name_Id_Place
Sam2001USA
Raja3455India
Allan90101Canada
The actual text file has 3 columns and 3 rows, but in the DataTable I got all 3 columns as a single column Name_Id_Place
. 实际的文本文件具有3列和3行,但是在DataTable中,我将所有3列作为单个列Name_Id_Place
。
Can anyone tell me the solution for this problem? 谁能告诉我这个问题的解决方案?
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();
}
Here I think you reading data from text file in right way, only problem I see that your used Provider cannot understand where a end of column, that why read all row as one column 在这里,我认为您以正确的方式从文本文件中读取数据,唯一的问题是我看到您使用的提供程序无法理解列的结尾位置,为什么将所有行都读取为一列
I had exact same result when trying read data from text file with OleDBConnection. 当尝试使用OleDBConnection从文本文件读取数据时,我得到了完全相同的结果。
In my connectionstring as Provider I used: 在我作为提供者的连接字符串中,我使用了:
Provider=Microsoft.Jet.OLEDB.4.0;
If you used same then you need only change "Format" options for this provider in Windows registry: 如果使用相同的格式,则只需在Windows注册表中为此提供程序更改“格式”选项:
HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ Jet \ 4.0 \ Engines \ Text
Then modify "Format" key to value="TabDelimited" 然后将“格式”键修改为value =“ TabDelimited”
or if you want use some other delimiter character(for example ";") then Format = "Delimited(;)" 或者,如果您要使用其他分隔符(例如“;”),则Format =“ Delimited(;)”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.