我正在研究抓取程序,从我的程序中抓取项目后的下一步是从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
首先,这里没有必要调用两次ToList
:
Dim dgvColumnNames As List(Of String) = DataGridView1.Columns.Cast(Of DataGridViewColumn).ToList().Select(Function(c) c.Name).ToList()
你不需要一个通用的List
来做Select
,所以删除第一个ToList
:
Dim dgvColumnNames = DataGridView1.Columns.
Cast(Of DataGridViewColumn).
Select(Function(c) c.Name).
ToList()
如果您想过滤该列表以只包含可见列,那么您就可以这样做。Where
方法是如何过滤的:
Dim dgvColumnNames = DataGridView1.Columns.
Cast(Of DataGridViewColumn).
Where(Function(c) c.Visible).
Select(Function(c) c.Name).
ToList()
你也应该替换这个:
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
与这个:
Dim rowData As New List(Of String)
For Each columnName In dgvColumnNames
rowData.Add(Convert.ToString(row.Cells(columnName).Value))
Next
,或者更简单地说:
Dim rowData = dgvColumnNames.Select(Function(s) row.Cells(columnName).Value.ToString()).ToList()
最后一个ToList
也不需要,因为String.Join
接受IEnumerable(Of String)
。除非您确实需要,否则不要花费额外的时间和精力将内容转换为通用的List
。