[英]Writing multiple selected DataGridView rows to CSV
The code below successfully allows for me to write a selected row to a.csv file.下面的代码成功地允许我将选定的行写入 a.csv 文件。
I'm having problems where, when I select multiple rows and try and write it to the file, it puts all of the row on the same line of the.csv file.我遇到问题,当我 select 多行并尝试将其写入文件时,它会将所有行放在 .csv 文件的同一行上。
How can I modify the code below so that it allows for multiple rows to be selected, and it writes each row to a new line of the.csv file?我如何修改下面的代码,以便它允许选择多行,并将每一行写入 .csv 文件的新行?
Dim StrExport As String = ""
For Each C As DataGridViewColumn In dataGVGeneral.Columns
StrExport &= "" & C.HeaderText & ","
Next
StrExport = StrExport.Substring(0, StrExport.Length - 1)
StrExport &= Environment.NewLine
'Only the row which is selected will be written
For Each R As DataGridViewRow In dataGVGeneral.Rows
If R.Selected = True Then
For Each C As DataGridViewCell In R.Cells
If Not C.Value Is Nothing Then
StrExport &= "" & C.Value.ToString & ","
Else
StrExport &= "" & "" & ","
End If
Next
Else
StrExport = StrExport.Substring(0, StrExport.Length - 1)
StrExport &= Environment.NewLine
End If
Next
Dim tw As System.IO.TextWriter = New System.IO.StreamWriter("E:\SAT\Work.io\Work.io\bin\Debug\Session.csv", False)
tw.Write(StrExport)
tw.Close()
On the line StrExport = StrExport.Substring(0, StrExport.Length - 1)
, I think you meant to use &=
instead of =
.在StrExport = StrExport.Substring(0, StrExport.Length - 1)
,我认为您打算使用&=
而不是=
。
However, you should be using a StringBuilder to create the string because it is more efficient when concatenating more than about ten pieces of string together.但是,您应该使用StringBuilder来创建字符串,因为将大约十个以上的字符串连接在一起时效率更高。
To join strings together with a comma/anything else between,String.Join is useful because you don't have to worry about the final comma.要将字符串与逗号/任何其他内容连接在一起,String.Join很有用,因为您不必担心最后的逗号。
And finally, with a little bit of LINQ you can make the code quite a bit shorter but still fairly easy to understand:最后,使用一点点 LINQ 可以使代码更短但仍然相当容易理解:
Private Sub bnSaveSelected_Click(sender As Object, e As EventArgs) Handles bnSaveSelected.Click
Dim sb As New Text.StringBuilder()
sb.AppendLine(String.Join(",", dataGVGeneral.Columns.Cast(Of DataGridViewColumn).Select(Function(c) c.HeaderText)))
For Each dr As DataGridViewRow In dataGVGeneral.Rows
If dr.Selected Then
sb.AppendLine(String.Join(",", dr.Cells.Cast(Of DataGridViewCell).Select(Function(c) c.Value.ToString())))
End If
Next
IO.File.WriteAllText("C:\temp\SampleCsv.csv", sb.ToString())
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.