VB.NET中DataGridView数据导出文本文件及导入的正确代码实现
VB.NET DataGridView 导出/导入文本(CSV)及XML解决方案
先说说你原来代码的问题哈:你同时用了StreamWriter和File.WriteAllText,后者每次调用都会覆盖整个文件,所以最后只会留下最后一个单元格的内容;另外没处理单元格值为空的情况,直接ToString会报错;还有每行写完没换行,内容全堆一起了。下面给你整理好的正确实现:
一、导出为CSV文本文件
这个是最常用的文本格式,用逗号分隔单元格,兼容大部分工具:
Private Sub ExportToCsv(filePath As String) ' 检查DataGridView是否有数据 If DataGridView1.Rows.Count = 0 Then MessageBox.Show("没有数据可导出!") Return End If ' 使用StreamWriter写入文件,默认UTF-8编码 Using writer As New System.IO.StreamWriter(filePath, False, System.Text.Encoding.UTF8) ' 先写出列名(可选,如果你需要表头的话) Dim header As New List(Of String)() For Each col As DataGridViewColumn In DataGridView1.Columns ' 处理列名可能包含逗号的情况,用引号包裹 header.Add($"""{col.HeaderText}""") Next writer.WriteLine(String.Join(",", header)) ' 遍历每一行数据 For Each row As DataGridViewRow In DataGridView1.Rows ' 跳过新行(DataGridView默认的空行) If row.IsNewRow Then Continue For Dim rowData As New List(Of String)() For Each cell As DataGridViewCell In row.Cells ' 处理单元格为空的情况,避免NullReferenceException Dim cellValue As String = If(cell.Value Is Nothing, "", cell.Value.ToString()) ' 如果内容包含逗号或引号,用引号包裹并转义内部的引号 If cellValue.Contains(",") OrElse cellValue.Contains("""") Then cellValue = $"""{cellValue.Replace("""", """""")}""" End If rowData.Add(cellValue) Next ' 写出当前行,用逗号分隔 writer.WriteLine(String.Join(",", rowData)) Next End Using MessageBox.Show("导出成功!") End Sub ' 调用示例: ' ExportToCsv("G:\Visual Studio 2010\data.csv")
二、从CSV文本文件导入到DataGridView
注意要先确保DataGridView的列已经和CSV的列对应,或者动态创建列:
Private Sub ImportFromCsv(filePath As String) ' 检查文件是否存在 If Not System.IO.File.Exists(filePath) Then MessageBox.Show("文件不存在!") Return End If ' 清空现有数据 DataGridView1.Rows.Clear() ' 如果需要动态创建列,先清空列 ' DataGridView1.Columns.Clear() Dim lines As String() = System.IO.File.ReadAllLines(filePath, System.Text.Encoding.UTF8) If lines.Length = 0 Then MessageBox.Show("文件为空!") Return End If ' 处理表头(如果CSV有表头的话) Dim headers As String() = ParseCsvLine(lines(0)) ' 如果需要动态创建列 ' For Each header As String In headers ' DataGridView1.Columns.Add(header, header) ' Next ' 遍历数据行 For i As Integer = 1 To lines.Length - 1 Dim line As String = lines(i).Trim() ' 跳过空行 If String.IsNullOrEmpty(line) Then Continue For Dim cellValues As String() = ParseCsvLine(line) ' 添加新行到DataGridView DataGridView1.Rows.Add(cellValues) Next MessageBox.Show("导入成功!") End Sub ' 辅助方法:正确解析CSV行(处理带引号的内容) Private Function ParseCsvLine(line As String) As String() Dim result As New List(Of String)() Dim currentValue As New StringBuilder() Dim inQuotes As Boolean = False For Each c As Char In line If c = """"c Then inQuotes = Not inQuotes ' 如果是两个连续的引号,解析为一个引号 If inQuotes AndAlso currentValue.Length > 0 AndAlso currentValue(currentValue.Length - 1) = """"c Then currentValue.Remove(currentValue.Length - 1, 1) End If ElseIf c = ","c AndAlso Not inQuotes Then ' 遇到逗号且不在引号中,结束当前值 result.Add(currentValue.ToString()) currentValue.Clear() Else currentValue.Append(c) End If Next ' 添加最后一个值 result.Add(currentValue.ToString()) Return result.ToArray() End Function ' 调用示例: ' ImportFromCsv("G:\Visual Studio 2010\data.csv")
三、导出为XML文件
XML格式更适合结构化数据,这里用DataSet来处理,更简单可靠:
Private Sub ExportToXml(filePath As String) If DataGridView1.Rows.Count = 0 Then MessageBox.Show("没有数据可导出!") Return End If ' 创建DataSet和DataTable Dim ds As New DataSet() Dim dt As New DataTable("DataGridViewData") ' 添加列到DataTable For Each col As DataGridViewColumn In DataGridView1.Columns dt.Columns.Add(col.HeaderText, col.ValueType) Next ' 添加行数据到DataTable For Each row As DataGridViewRow In DataGridView1.Rows If row.IsNewRow Then Continue For Dim dr As DataRow = dt.NewRow() For Each cell As DataGridViewCell In row.Cells dr(cell.ColumnIndex) = If(cell.Value Is Nothing, DBNull.Value, cell.Value) Next dt.Rows.Add(dr) Next ds.Tables.Add(dt) ' 导出XML ds.WriteXml(filePath) MessageBox.Show("XML导出成功!") End Sub ' 调用示例: ' ExportToXml("G:\Visual Studio 2010\data.xml")
四、从XML文件导入到DataGridView
同样用DataSet来读取,自动匹配结构:
Private Sub ImportFromXml(filePath As String) If Not System.IO.File.Exists(filePath) Then MessageBox.Show("文件不存在!") Return End If Dim ds As New DataSet() Try ds.ReadXml(filePath) Catch ex As Exception MessageBox.Show($"XML文件格式错误:{ex.Message}") Return End If If ds.Tables.Count = 0 Then MessageBox.Show("XML中没有数据!") Return End If ' 清空现有数据和列 DataGridView1.Columns.Clear() DataGridView1.Rows.Clear() ' 绑定DataTable到DataGridView DataGridView1.DataSource = ds.Tables(0) MessageBox.Show("XML导入成功!") End Sub ' 调用示例: ' ImportFromXml("G:\Visual Studio 2010\data.xml")
注意事项
- 导出时记得处理权限问题:如果写入的路径是系统目录(比如C:\根目录),可能需要管理员权限。
- 导入CSV时,如果你的DataGridView列是固定的,要确保CSV的列顺序和数量和DataGridView一致;如果是动态列,就打开代码里的动态创建列的注释。
- XML导入时,XML的结构要和导出的一致,否则会解析失败。
内容的提问来源于stack exchange,提问作者Kudo Shinichi




