将DataRows写入多个CSV文件

时间:2014-07-21 19:11:07

标签: vb.net

我使用以下代码从DataRows集合创建CSV:

      Dim filename = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".csv" 'assign a temp file
        Using csvWriter As New System.IO.StreamWriter(filename, True)

            'write column headings
            csvWriter.WriteLine(String.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}", "AcctNumber", "AccountHolderName", "AccountOption", "Address1", "Address2", "City", "State", "Zip"))

            For Each row in LetterRows 'collection of datarows
                csvWriter.WriteLine(String.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}", row.AcctNumber, row.AcctHolderName, row.AccountOption, row.Address1, row.Address2, row.City, row.ST, row.ZIP))
            Next row

        End Using

这正确地将所有数据行写入CSV。我现在想要设置一个上限,比如说5000,并在每次写入~5000条记录时创建一个新的csv(我将每个文件保存在一个字符串列表中)。我正在思考这个问题:

 Dim filesCreated As New List(Of String)
 Dim filename As String = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".csv" 'assign a temp file
    filesCreated.Add(filename)

    For i = 0 To LetterRows.Count - 1

        Using csv As New System.IO.StreamWriter(filename, True) 'dont think this is efficient, what to do

            'write data here


        End Using

        If i Mod 5000 = 0 Then
            filename = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".csv" 'assign a temp file
            filesCreated.Add(filename)
        End If
    Next i

我认为这有点草率但我认为在这种情况下使用循环没有多大意义,因为我正在为每条记录打开和关闭编写器。这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:1)

您可以做的是将所有行放入字符串并一次写入整个字符串。这可能会更好,而不是每行初始化编写器?

 Dim to_write as String 

 For i = 0 To LetterRows.Count - 1

   to_write = to_write & vbCrLf & 'newline 

   if i = 5000 Then
      System.IO.File.WriteAllText(filename,to_write)   
      filename = 'increment or set your new/next filename here
      to_write = ""   'reset string and continue 
   End if

 Next 

因此字符串将存储您的所有数据,直到它准备好写入。 vbCrLf将确保每一行都是分开的。