如何将文本文件读取到DataTable

时间:2013-12-31 16:14:30

标签: c# datatable

我想从txt文件中提取数据并将其放入DataTable中。 txt文件中的内容采用以下格式:

  

sometext1:sometext2:sometext3
sometext4:sometext5:sometext6
  sometext7:sometext8:sometext9
...

每一行代表一行,每一列用“:”字符分隔。

我试过这样做:

            DataTable tbl = new DataTable();

            using (StreamWriter sw = File.CreateText(path))
            {
                string[] rows = content.Split('\n');
                foreach (string s in rows)
                {
                    string[] columns = s.Split(':');
                    foreach (string t in columns)
                    {
                        sw.WriteLine(t);
                    }

                }
            }

如何阅读此文件并将其添加到DataTable?

4 个答案:

答案 0 :(得分:12)

这是一种简单的方法来完成你的工作

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

答案 1 :(得分:3)

这是一个优秀的类,它将使用数据结构将CSV数据复制到数据表中以创建DataTable:

http://www.codeproject.com/Articles/11698/A-Portable-and-Efficient-Generic-Parser-for-Flat-F

此主题也在这里讨论过: How to read a CSV file into a .NET Datatable

但是,如果您愿意自己编写代码,可以举一个例子:

Dim csvFileFolder As String = "C:\YourFileFolder"
Dim csvFileName As String = "YourFile.csv"

'Note that the folder is specified in the connection string,
'not the file. That's specified in the SELECT query, later.
Dim connString As String = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" _
    & csvFileFolder & ";Extended Properties=""Text;HDR=No;FMT=Delimited"""
Dim conn As New Odbc.OdbcConnection(connString)

'Open a data adapter, specifying the file name to load
Dim da As New Odbc.OdbcDataAdapter("SELECT * FROM [" & csvFileName & "]", conn)
'Then fill a data table, which can be bound to a grid

Dim dt As New DataTableda.Fill(dt)

这是在VB.NET中,如果你不能将它翻译成C#,请告诉我。

问候。

答案 2 :(得分:0)

好吧,你可能在这里有你的数据:

string[] rows = content.Split('\n');
foreach (string s in rows)
{
    string[] columns = s.Split(':');
    foreach (string t in columns)
    {
        // each data element
    }
}

如果您定义了DataTable,则可以使用非常相似的构造向其添加行。我不知道你桌子的结构,但基本上你可以这样做:

string[] rows = content.Split('\n');
foreach (string s in rows)
{
    string[] columns = s.Split(':');
    var dataRow = someDataTable.NewRow();

    dataRow["someColumnName"] = columns[0];
    dataRow["anotherColumnName"] = columns[1];
    dataRow["someOtherColumnName"] = columns[2];
    // and so on...

    someDataTable.Rows.Add(dataRow);
}

如果DataTable列没有强名称,您还可以按索引添加项目:

dataRow.Item[0] = columns[0];
dataRow.Item[1] = columns[1];
// and so on...

答案 3 :(得分:0)

以下内容将执行您概述的整个过程。

var table = new DataTable();

var fileContents = File.ReadAllLines("yourFile");

var splitFileContents = (from f in fileContents select f.Split(':')).ToArray();

int maxLength = (from s in splitFileContents select s.Count()).Max();

for (int i = 0; i < maxLength; i++)
{
    table.Columns.Add();
}

foreach (var line in splitFileContents)
{
    DataRow row = table.NewRow();
    row.ItemArray = (object[])line;
    table.Rows.Add(row);
}