vb.net – DataGridView到CSV文件

我有一个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

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

谢谢

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

这对我有用:

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

相关文章

Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强制返回为文本 --------------------------...
VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办法, Format 或者FormatDateTime 竟然结果和...
在项目中添加如下代码:新建窗口来显示异常信息。 Namespace My ‘全局错误处理,新的解决方案直接...
转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用的爽呀,这篇文章写与2011年,看来我以前没...
Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选中的单元格进行处理 Dim m As Range, t...
  窗体代码 1 Private Sub Text1_OLEDragDrop(Data As DataObject, Effect As Long, Button As Integ...