如何从vb.net中仅在DataGridView中导出CSV?
我正在研究刮擦程序,从datagridview生成/导出到CSV文件后,我程序的下一步是从我的程序中开始的。我已经制作了以下保存代码,但我只想导出一个可见的列。我怎么能喜欢?
Private Sub CmdCSV_Click(sender As Object, e As EventArgs) Handles CmdCSV.Click
Dim sfd As New SaveFileDialog()
sfd.FileName = "export-csv"
sfd.Filter = "CSV File | *.csv"
If sfd.ShowDialog() = DialogResult.OK Then
Using sw As StreamWriter = File.CreateText(sfd.FileName)
Dim dgvColumnNames As List(Of String) = DataGridView1.Columns.Cast(Of DataGridViewColumn).ToList().Select(Function(c) c.Name).ToList()
sw.WriteLine(String.Join(";", dgvColumnNames))
For Each row As DataGridViewRow In DataGridView1.Rows
Dim rowData As New List(Of String)
For Each column As DataGridViewColumn In DataGridView1.Columns
rowData.Add(Convert.ToString(row.Cells(column.Name).Value))
Next
sw.WriteLine(String.Join(";", rowData))
Next
End Using
End If
End Sub
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,在这里两次都没有点调用
TOLIST
:您不需要通用
list
进行选择
,因此请删除第一个Tolist
:如果要过滤该列表以仅包含可见列,那就是您要做的。
其中
方法是您的过滤方式:您还应该替换以下
内容:
或者更简单地说:
最后
tolist
也不需要,因为string.join
接受iEnumerable(String)
。除非您实际需要一个,否则不要花更多的时间和精力将事物转换为通用列表。Firstly, there's no point calling
ToList
twice here:You don't need a generic
List
to do theSelect
, so drop the firstToList
:If you want to filter that list to include only visible columns, that's what you do. The
Where
method is how you filter:You should also replace this:
with this:
or, more simply, this:
That last
ToList
isn't required either, becauseString.Join
accepts anIEnumerable(Of String)
. Don't take the extra time and effort to convert things to a genericList
unless you actually need one.