DataGridView到CSV文件

时间:2011-07-13 23:22:43

标签: vb.net csv datagridview streamwriter

我有一个VB 2010 Express项目,其中有一个DataGridView,我正在尝试写入CSV文件。

我写的所有工作。但它的速度很慢。慢速=可能30秒,超过8列6000行。

这是我的代码:

    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

有谁知道我能做些什么来加快速度?

感谢

2 个答案:

答案 0 :(得分:13)

当你花几个小时搜索,然后发一个问题,几分钟后你自己找到答案时,你不喜欢它吗?

这对我有用:

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

答案 1 :(得分:1)


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