从Access末尾的Access缺少回车导出到文本文件

时间:2016-08-29 02:03:39

标签: vb.net

我在Access中有一个数据库,我需要将该信息导出到文本文件中我遇到的问题是它没有以正确的格式导出。这是已导出的文本文件的示例:

info|info1|info3|info4|info5|info6|info7|info8|  <this is the wrong format
info|info1|info3|info4|info5|info6|info7|info8   <this is the correct format

如您所见,我的代码是在行的末尾插入一条垂直线而不是回车符。

请查看我的代码,任何帮助都会很棒:

    Dim connetionString As String
    Dim cnn As OleDbConnection
    connetionString = "connection string.accdb;"
    cnn = New OleDbConnection(connetionString)

    Dim dtResult As New DataTable
    cnn.Open()
    'Change the query
    Dim dataAdap As New OleDbDataAdapter("SELECT * FROM table", cnn)
    dataAdap.Fill(dtResult)
    cnn.Close()

    'Change the path to your desired path
    Dim RUTA As String = "path were i want to put the text file\"
    Dim ARCHIVOTXT As String = "filename of the text file.txt"

    If Not Directory.Exists(RUTA) Then
        Directory.CreateDirectory(RUTA)
    End If

    Dim writer As New StreamWriter(RUTA + ARCHIVOTXT)
    Try
        Dim sb As New StringBuilder
        For Each row As DataRow In dtResult.Rows
            sb = New StringBuilder
            For Each col As DataColumn In dtResult.Columns
                sb.Append(row(col.ColumnName) & "|")
            Next
            writer.WriteLine(sb.ToString())
        Next
    Catch ex As Exception
        Throw ex
    Finally
        If Not writer Is Nothing Then writer.Close()
    End Try
    MsgBox("Done")
End Sub

1 个答案:

答案 0 :(得分:1)

而不是:

For Each col As DataColumn In dtResult.Columns
        sb.Append(row(col.ColumnName) & "|")
Next
writer.WriteLine(sb.ToString())

您可以使用:writer.WriteLine(String.Join("|", row.ItemArray))

String.Join("|", row.ItemArray)将分隔值的行所拥有的每个值的ToString()结果与&#34; |&#34;连接起来。