本文介绍了如何将文本文件读取到数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从 txt 文件中提取数据并将其放入数据表中.txt文件中的内容格式如下:
I would like to extract data from a txt file and put it into a DataTable. The content in the txt file is in the following format:
sometext1:sometext2:sometext3
sometext4:sometext5:sometext6
sometext7:sometext8:sometext9
...
每行代表一行,每列用:"字符分隔.
Each line represents a row and every column is separated with ":" character.
我尝试这样做:
DataTable tbl = new DataTable();
using (StreamWriter sw = File.CreateText(path))
{
string[] rows = content.Split('
');
foreach (string s in rows)
{
string[] columns = s.Split(':');
foreach (string t in columns)
{
sw.WriteLine(t);
}
}
}
如何读取此文件并将其添加到 DataTable?
How can I read this file and add it to DataTable?
推荐答案
这是完成工作的简单方法
This is a simple method to do your job
public DataTable ConvertToDataTable (string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
for(int col =0; col < numberOfColumns; col++)
tbl.Columns.Add(new DataColumn("Column" + (col+1).ToString()));
string[] lines = System.IO.File.ReadAllLines(filePath);
foreach(string line in lines)
{
var cols = line.Split(':');
DataRow dr = tbl.NewRow();
for(int cIndex=0; cIndex < 3; cIndex++)
{
dr[cIndex] = cols[cIndex];
}
tbl.Rows.Add(dr);
}
return tbl;
}
这篇关于如何将文本文件读取到数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!