如何从Txt文件创建和填充数据表

时间:2019-01-15 14:32:30

标签: vb.net text datatable

我是vb.net的新手,所以我不知道这个问题听起来很愚蠢。我在输入中有一个txt文件,想要创建一个数据表并用文本文件填充它,但是由于某些原因,我无法填充它。 这是我的代码:

Public Function TxtToCsv(ByVal txtPath As String)

    Console.ReadLine()
    Dim dt As DataTable = New DataTable

    dt.Columns.Add("1", GetType(String))
    dt.Columns.Add("2", GetType(String))

    Dim myString As String = File.ReadAllText(txtPath)
    Dim rows() As String = myString.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)

    For i As Integer = 1 To dt.Rows.Count - 1

        Dim dr As DataRow
        dr = dt.NewRow()

        dr(columnIndex:=0) = rows(i).Substring(0, 25)
        dr(columnIndex:=1) = rows(i).Substring(26, 8)

        i += 1

    Next

    Console.WriteLine(dt)
    Console.ReadLine()

2 个答案:

答案 0 :(得分:1)

Console.WriteLine(dt)将在dt上调用.ToString,它返回完全限定的名称。

Sub Main()
    Dim dt As DataTable = FillDataTable("C:\Users\***\Desktop\TestData.txt")
    Console.Write(DataTableToString(dt))
    Console.ReadKey()
End Sub

Private Function FillDataTable(txtPath As String) As DataTable
    Dim dt As New DataTable
    dt.Columns.Add("1", GetType(String))
    dt.Columns.Add("2", GetType(String))
    'ReadAllLines returns and array of the lines in the text file
    Dim rows() As String = File.ReadAllLines(txtPath)
    'Start at zero, the index of the first line
    For i As Integer = 0 To rows.Length - 1
        Dim dr As DataRow
        dr = dt.NewRow()
        dr(columnIndex:=0) = rows(i).Substring(0, 5)
        dr(columnIndex:=1) = rows(i).Substring(7, 3)
        dt.Rows.Add(dr)
        'Your index is incremented by the For...Next loop
        'i += 1
    Next
    Return dt
End Function

Private Function DataTableToString(dt As DataTable) As String
    Dim sb As New StringBuilder
    For Each r As DataRow In dt.Rows
        For Each c As DataColumn In dt.Columns
            sb.Append(r(c).ToString & " ")
        Next
        sb.AppendLine()
    Next
    Return sb.ToString
End Function

答案 1 :(得分:0)

您正在循环数据表的行而不是文件的行。

For i As Integer = 1 To rows.length - 1

for循环会自动增加“ I”,删除+ = 1

' i += 1

我认为您不能直接写一行数据表。

Console.WriteLine(dt) ' Find an other way to print the data

我建议您打开Option Strict。这将帮助您发现错误。另外,一次只写几行并进行测试。