DataGridView到CSV文件 [英] DataGridView to CSV File
本文介绍了DataGridView到CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个VB 2010 Express Project,它有一个DataGridView,我试图写一个CSV文件。
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.
这是我的代码:
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?
感谢
推荐答案
然后发布一个问题,几分钟后自己找到答案?
Don't you just love it when you spend hours searching, then post a question, and a few minutes later find the answer yourself?
这对我有帮助:
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")
这篇关于DataGridView到CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文