none
如何将DataGridView控件中的内容保存为.csv文件? RRS feed

  • 问题

  • 大家好。

    我在窗口中添加了一个DataGridView控件,然后我想点击一下按钮,把这个DataGridVie控件中的内容保存为.csv文件,好方便使用Excel打开。如何做到这一点?谢谢。

    2012年5月30日 14:17

答案

  •         <Extension()>
            Public Function ExportToCsv(dgv As DataGridView) As Boolean
                Dim dlg As New SaveFileDialog()
                dlg.Filter = "CSV(逗号分隔)(*.csv)|*.csv"
                dlg.FilterIndex = 0
                dlg.RestoreDirectory = True
                dlg.CreatePrompt = True
                dlg.Title = "保存为CSV(逗号分隔)文件"
                If dlg.ShowDialog() = DialogResult.OK Then
                    Dim myStream As Stream
                    myStream = dlg.OpenFile()
                    Using sw As New StreamWriter(myStream, Encoding.Default)
                        Dim columnTitle As String = ""
                        Try
                            '写入列标题  
                            For i As Integer = 0 To dgv.ColumnCount - 1
                                If i > 0 Then
                                    columnTitle += ","
                                End If
                                columnTitle += dgv.Columns(i).HeaderText
                            Next
                            columnTitle.Remove(columnTitle.Length - 1)
                            sw.WriteLine(columnTitle)
                            '写入列内容     
                            For j As Integer = 0 To dgv.Rows.Count - 1
                                Dim columnValue As String = ""
                                For k As Integer = 0 To dgv.Columns.Count - 1
                                    If k > 0 Then
                                        columnValue += ","
                                    End If
                                    If dgv.Rows(j).Cells(k).Value Is Nothing Then
                                        columnValue += ""
                                    Else
                                        Dim m As String = dgv.Rows(j).Cells(k).Value.ToString().Trim()
                                        columnValue += m.Replace(",", ",")
                                    End If
                                Next
                                columnValue.Remove(columnValue.Length - 1)
                                sw.WriteLine(columnValue)
                            Next
                            sw.Close()
                            myStream.Close()
                        Catch e As Exception
                            Return False
                        Finally
                            sw.Close()
                            myStream.Close()
                        End Try
                    End Using
                    Return True
                Else
                    Return False
                End If
            End Function

    使用的时候,在按钮单击事件中加入以下语句

    DataGridView1.ExportToCsv

    算神的博客

    2012年5月30日 23:13