Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a VB 2010 Express Project, that has a DataGridView in it, that I am trying to write to a CSV file.

I have the write all working. But its slow. Slow = maybe 30 seconds for 6000 rows over 8 columns.

Here is my code:

    Private Sub btnExportData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExportData.Click
    Dim StrExport As String = ""
    For Each C As DataGridViewColumn In DataGridView1.Columns
        StrExport &= """" & C.HeaderText & ""","
    Next
    StrExport = StrExport.Substring(0, StrExport.Length - 1)
    StrExport &= Environment.NewLine

    For Each R As DataGridViewRow In DataGridView1.Rows
        For Each C As DataGridViewCell In R.Cells
            If Not C.Value Is Nothing Then
                StrExport &= """" & C.Value.ToString & ""","
            Else
                StrExport &= """" & "" & ""","
            End If
        Next
        StrExport = StrExport.Substring(0, StrExport.Length - 1)
        StrExport &= Environment.NewLine
    Next

    Dim tw As IO.TextWriter = New IO.StreamWriter("C:Test1.CSV")
    tw.Write(StrExport)
    tw.Close()
End Sub

Does anyone know what I can do to speed it up?

thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...