vb.net DataGridView 转 CSV 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6686852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DataGridView to CSV File
提问by greg
I have a VB 2010 Express Project, that has a DataGridView in it, that I am trying to write to a CSV file.
我有一个 VB 2010 Express 项目,其中有一个 DataGridView,我正在尝试将其写入 CSV 文件。
I have the write all working. But its slow. Slow = maybe 30 seconds for 6000 rows over 8 columns.
我有写所有工作。但它的速度很慢。慢 = 8 列 6000 行可能需要 30 秒。
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
谢谢
回答by 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")