如何从格式化文本文件创建csv文件

时间:2013-06-05 17:02:25

标签: vb.net loops

我有一个包含数百个潜在客户的文本文件,我正在尝试将其转换为csv进行导入。

整个文档的格式。

潜在客户名称

描述 网站

潜在客户名称

描述 网站

我如何编写一个vb程序来循环创建一个csv文件。每4行就是一个新的前景。

2 个答案:

答案 0 :(得分:0)

将您的文件内容作为IEnumerable(String)获取,然后旋转它,为每条记录添加一个CSV行(进入一个新的列表(String))。最后写出文件内容。您可能想要添加标题行。

        Dim lstLines As IEnumerable(Of String) = IO.File.ReadLines("C:\test\ConvertToCSV.txt")

        Dim lstNewLines As New List(Of String)

        Dim intRecordTracker As Integer = 0

        Dim strCSVRow As String = String.Empty

        For Each strLine As String In lstLines

            If intRecordTracker = 4 Then

                intRecordTracker = 0

                'Trim off extra comma.
                lstNewLines.Add(strCSVRow.Substring(0, (strCSVRow.Length - 1)))

                strCSVRow = String.Empty

            End If

            strCSVRow += strLine & ","

            intRecordTracker += 1

        Next

        'Add the last record.
        lstNewLines.Add(strCSVRow.Substring(0, (strCSVRow.Length - 1)))

        'Finally write the CSV file.
        IO.File.WriteAllLines("C:\Test\ConvertedCSV.csv", lstNewLines)

答案 1 :(得分:0)

 Dim count As Integer = -1, lstOutput As New List(Of String)

 lstOutput.AddRange(From b In File.ReadAllLines("C:\temp\intput.txt").ToList.GroupBy(Function(x) (Math.Max(Threading.Interlocked.Increment(count), count - 1) \ 4)).ToList() Select String.Join(",", b))

 File.WriteAllLines("c:\temp\test\output.txt", lstOutput)
相关问题