[英]Writing DataRows into multiple CSV files
我正在使用以下代碼從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
我認為這有點草率,並且我認為在這種情況下使用循環不是很有意義,因為我正在為每個記錄打開和關閉寫入器。 做這個的最好方式是什么?
您可以做的是將所有行放入一個字符串中,然后一次寫入整個字符串。 而不是初始化每一行的writer可能會更好一些?
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將確保每一行都分開。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.