DataGridView to CSV File

此生再无相见时 提交于 2019-11-28 22:06:10
greg

Don't you just love it when you spend hours searching, then post a question, and a few minutes later find the answer yourself?

This did the trick for me:

Dim headers = (From header As DataGridViewColumn In DataGridView1.Columns.Cast(Of DataGridViewColumn)() _
              Select header.HeaderText).ToArray
Dim rows = From row As DataGridViewRow In DataGridView1.Rows.Cast(Of DataGridViewRow)() _
           Where Not row.IsNewRow _
           Select Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))
Using sw As New IO.StreamWriter("csv.txt")
    sw.WriteLine(String.Join(",", headers))
    For Each r In rows
        sw.WriteLine(String.Join(",", r))
    Next
End Using
Process.Start("csv.txt")


Private Sub cmdExport_Click(sender As Object, e As EventArgs) Handles cmdExport.Click
'This way increases performance without casting
        Dim filePath As String = "OverrideViewer.csv"
        Dim delimeter As String = ","
        Dim sb As New StringBuilder
        For i As Integer = 0 To dgDataView.Rows.Count - 1
            Dim array As String() = New String(dgDataView.Columns.Count - 1) {}
            If i.Equals(0) Then
                For j As Integer = 0 To dgDataView.Columns.Count - 1
                    array(j) = dgDataView.Columns(j).HeaderText
                Next
                sb.AppendLine(String.Join(delimeter, array))
            End If
            For j As Integer = 0 To dgDataView.Columns.Count - 1
                If Not dgDataView.Rows(i).IsNewRow Then
                    array(j) = dgDataView(j, i).Value.ToString
                End If
            Next
            If Not dgDataView.Rows(i).IsNewRow Then
                sb.AppendLine(String.Join(delimeter, array))
            End If
        Next
        File.WriteAllText(filePath, sb.ToString)
'Opens the file immediately after writing
        Process.Start(filePath)
End Sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!