【发布时间】:2015-06-04 10:20:10
【问题描述】:
我有一个文本分隔文件需要转换成数据表。给定这样的文字:
Name,Contact,Email,Date Of Birth,Address
JOHN,01212121,hehe@yahoo.com,1/12/1987,"mawar rd, shah alam, selangor"
JACKSON,01223323,haha@yahoo.com,1/4/1967,"neelofa rd, sepang, selangor"
DAVID,0151212,hoho@yahoo.com,3/5/1956,"nora danish rd, klang, selangor"
这就是我在 C# 中读取文本文件的方式
DataTable table = new DataTable();
using (StreamReader sr = new StreamReader(path))
{
#region Text to csv
while (!sr.EndOfStream)
{
string[] line = sr.ReadLine().Split(',');
//table.Rows.Add(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]);
if (IsRowHeader)//Is user want to read first row as the header
{
foreach (string column in line)
{
table.Columns.Add(column);
}
totalColumn = line.Count();
IsRowHeader = false;
}
else
{
if (totalColumn == 0)
{
totalColumn = line.Count();
for (int j = 0; j < totalColumn; j++)
{
table.Columns.Add();
}
}
// create a DataRow using .NewRow()
DataRow row = table.NewRow();
// iterate over all columns to fill the row
for (int i = 0; i < line.Count(); i++)
{
row[i] = line[i];
}
// add the current row to the DataTable
table.Rows.Add(row);
}
}
列是动态的,用户可以在文本文件中添加或删除列。所以我需要检查有多少列并设置为数据表,然后我将读取每一行,将值设置为数据行,然后将行添加到表中。
如果我不删除双标记内的分号,则会显示错误“找不到第 5 列”,因为第一行只有 4 列(从 0 开始)。
处理文本分隔的最佳方法是什么?
【问题讨论】:
-
每次确定有多少列后,是否需要生成db表?
-
@TheBojan : 没错