将数据从MS Access导入到文本文件

时间:2015-11-05 13:58:46

标签: vb.net ms-access text-files

我试图将一些数据从MS Access导入到文本文件中。 Access数据库有3列。学生姓名,作业名称和得分标记。但是当我执行以下代码时,数据是这样的:

John Cena
John Cena Assignment Submission System
JohnCenaMNUAssignment Submission System75
JohnCenaMNUAssignment Submission System75
Mark
MarkGussing Game
MarkGussing Game80
MarkGussing Game80

我想在学生姓名,作业名称和得分标记之间留出一些空格。此外,两个学生信息之间还有一条额外的线。这是我尝试的代码,但它没有给出所需的结果:

Private Sub DataTableToTXT()

    Dim connetionString As String
    Dim cnn As OleDbConnection
    connetionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=.\\reportcard.accdb;Persist Security Info=False"
    cnn = New OleDbConnection(connetionString)

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

    'Change the path to your desired path
    Dim exportPath As String = "D:"
    Dim exportFileName As String = "data.txt"



    Dim writer As New StreamWriter(exportPath + exportFileName)
    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))
                writer.WriteLine(sb.ToString())
            Next
            writer.WriteLine(sb.ToString())
        Next
    Catch ex As Exception
        Throw ex
    Finally
        If Not writer Is Nothing Then writer.Close()
    End Try

End Sub

1 个答案:

答案 0 :(得分:2)

您应该删除内部循环中的WriteLine。当您循环列时,该行将逐步打印StringBuilder的内容。完成内循环后,您只需要一个WriteLine

Dim writer As New StreamWriter(exportPath + exportFileName)
Try
    Dim sb As 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))
            sb.Append(" ") ' The space between columns values
            ' REMOVE this line
            ' writer.WriteLine(sb.ToString())
        Next
        writer.WriteLine(sb.ToString())
    Next

但是,如果你的表没有包含太多数据,你可以避免在每一行写一行,并在StringBuilder中累积所有输出,并在行的循环结束时写下所有内容

    Dim sb As New StringBuilder

    For Each row As DataRow In dtResult.Rows
        For Each col As DataColumn In dtResult.Columns
            sb.Append(row(col.ColumnName))
            sb.Append(" ")
        Next
        sb.AppendLine()
    Next

    ' Just one write at the end of the rows loop
    writer.WriteLine(sb.ToString())

这也应该更快,因为您只访问文件系统一次而不是n次(其中n是行数)。当然,如果行数很小,真正的好处可以忽略不计。

最后,最好的方法可能是使用string.Join和行的ItemArray属性。这将删除列上的内循环,它更清晰

    Dim sb As New StringBuilder

    For Each row As DataRow In dtResult.Rows
        sb.AppendLine(string.Join(" ", row.ItemArray))
    Next
    writer.WriteLine(sb.ToString())