VB.net项目主要使用微软旗下的Visual Studio 2022编辑器来进行,打开VS2022.新建一个VB.net窗体项目,保存。
然后在窗体上添加以下控件:
DataGridView(数据表格控件)、Label(标签控件)、ContextMenuStrip(右键关联菜单控件)等
然后,设置DataGridView控件的contextmenustrip属性(关联到添加的contextmenustrip控件上)。
由于需要读取csv文档,所以需要添加一些namespace。
Imports System.IO
Imports System.Text
Imports CsvHelper
上面的namespace中,system.IO是windows用于读取流数据的类,而CsvHelper是一个.NET程序包,其封装了.net的文本读取类textreader,提供便捷的处理csv文档api接口。
使用streamreader读取csv为流数据,使用csvhelper提供的函数,获取一个idatareader的实例(datatable数据格式),再新建一个datatable,使用load加载csv的数据,然后将datatable的数据添加到datagridview控件上,或者直接使用DataSource绑定datatable(不过我用这个方法,读取的csv数据无法编辑,暂时不清楚原因)
Private Sub import_csv(fl As String)
Dim strd1 As StreamReader = Nothing
Try
strd1 = New StreamReader(fl, Encoding.GetEncoding("gb2312")) '中文编码gb2312
Dim csv = New CsvReader(strd1, CultureInfo.InvariantCulture)
Dim dr = New CsvDataReader(csv)
Dim dt = New DataTable()
dt.Load(dr)
DataGridView1.Rows.Clear()
For i = 0 To dt.Rows.Count - 1
Dim inx0 = DataGridView1.Rows.Add()
For j = 0 To dt.Columns.Count - 1
DataGridView1.Columns(j).HeaderText = dt.Columns(j).ToString()
DataGridView1.Rows(i).Cells(j).Value = dt.Rows(i).Item(j).ToString()
Next
Next
strd1.Dispose()
csv.Dispose()
dr.Dispose()
dt.Dispose()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.OkOnly, "tip!")
Finally
strd1.Close()
End Try
End Sub
由于表格数据中,数据都是在单元格中,所以,将datagridview中的数据导出为csv,就是把单元格的数据一一对应赋值即可。
同样是使用流数据操作,首先打开一个已存在的csv文档或者新建一个(文件路径),然后获取文件的流(stream),使用streamwriter,将数据写入流中(也就是写入csv文件中),完成后记得释放资源(dispose)。
其中麻烦一点的,是需要算一下datagridview的单元格与csv文档的单元是如何一一对应的,不过,这种程序网上很多,不需要自己花费时间去计算,按照网上的程序,自己修改一下即可。
Private Sub export_csv(dgv As DataGridView, s1 As Stream)
Using sw1 As New StreamWriter(s1, 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)
sw1.WriteLine(columntitle)
For j As Integer = 0 To dgv.Rows.Count - 1
Dim columevalue As String = ""
For k As Integer = 0 To dgv.Columns.Count - 1
If k > 0 Then
columevalue += ","
End If
If dgv.Rows(j).Cells(k).Value Is Nothing Then
columevalue += ""
Else
Dim m As String = dgv.Rows(j).Cells(k).Value.ToString().Trim()
columevalue += m.Replace(",", ", ")
End If
Next
columevalue.Remove(columevalue.Length - 1)
sw1.WriteLine(columevalue)
Next
sw1.Close()
s1.Close()
Catch ex As Exception
Finally
sw1.Close()
s1.Close()
End Try
End Using
End Sub
这个例子没有测试过大量数据的csv文档的读取,只是提供了一个实现的方法。如果是那种有大量数据的读写,应该需要多线程来实现(将文件分割读取,否则加载时应该会等很久)。
演示视频:
vb.net下csv导入导出演示
完整代码:
Imports System.Windows.Forms.DataVisualization.Charting
Imports System.IO
Imports System.Text
Imports CsvHelper
Imports System.Globalization
Public Class Form9
Public series1 As Series
Public caiyang_num As Integer
Public caiyang_time As Integer
Private Sub Form9_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "表格浏览器"
DataGridView1.Columns.Add("col1", "X 坐标(100ms)")
DataGridView1.Columns.Add("col2", "Y 坐标(mm/10000)")
For i = 0 To DataGridView1.Columns.Count - 1
DataGridView1.Columns(i).SortMode = DataGridViewColumnSortMode.NotSortable '列的排序模式
Next
If series1 IsNot Nothing Then
chart_data_show(series1)
End If
Label8.Text = caiyang_num.ToString() & "个"
Label9.Text = caiyang_time.ToString() & "ms"
End Sub
Private Sub chart_data_show(s1 As Series)
For i = 0 To s1.Points.Count - 1
Dim inx0 = DataGridView1.Rows.Add()
DataGridView1.Rows(inx0).SetValues(s1.Points(i).XValue.ToString())
DataGridView1.Rows(inx0).Cells(1).Value = s1.Points(i).YValues(0).ToString()
Next
caiyang_num = s1.Points.Count
End Sub
Private Sub 导入数据CSVToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 导入数据CSVToolStripMenuItem.Click
OpenFileDialog1.Filter = "CSV(逗号分隔)(*.csv)|*.csv|文本文件(*.txt)|*.txt|所有文件 (*.*)|*.*"
OpenFileDialog1.InitialDirectory = "C:\User\rongjv\Desktop\"
OpenFileDialog1.RestoreDirectory = True
Dim fl As String = Nothing
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
fl = OpenFileDialog1.FileName
Dim fi1 = New FileInfo(fl)
If fi1.Length > 1048576 Then
Label5.Text = String.Format("{0,10:#.0000}", fi1.Length / 1024 / 1024) & "MB"
Else
Label5.Text = String.Format("{0,10:#.0000}", fi1.Length / 1024) & "KB"
End If
Label3.Text = fl
import_csv(fl)
End If
End Sub
Private Sub 导出数据CSVToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 导出数据CSVToolStripMenuItem.Click
Dim st1 As Stream = Nothing
SaveFileDialog1.Filter = "CSV(逗号分隔)(*.csv)|*.csv|文本文件(*.txt)|*.txt|所有文件 (*.*)|*.*"
SaveFileDialog1.InitialDirectory = "C:\User\rongjv\Desktop\"
SaveFileDialog1.RestoreDirectory = True
If SaveFileDialog1.ShowDialog = DialogResult.OK Then
st1 = SaveFileDialog1.OpenFile()
Label4.Text = SaveFileDialog1.FileName
export_csv(DataGridView1, st1)
st1.Dispose()
End If
End Sub
Private Sub import_csv(fl As String)
Dim strd1 As StreamReader = Nothing
Try
strd1 = New StreamReader(fl, Encoding.GetEncoding("gb2312")) '中文编码gb2312
Dim csv = New CsvReader(strd1, CultureInfo.InvariantCulture)
Dim dr = New CsvDataReader(csv)
Dim dt = New DataTable()
dt.Load(dr)
DataGridView1.Rows.Clear()
For i = 0 To dt.Rows.Count - 1
Dim inx0 = DataGridView1.Rows.Add()
For j = 0 To dt.Columns.Count - 1
DataGridView1.Columns(j).HeaderText = dt.Columns(j).ToString()
DataGridView1.Rows(i).Cells(j).Value = dt.Rows(i).Item(j).ToString()
Next
Next
strd1.Dispose()
csv.Dispose()
dr.Dispose()
dt.Dispose()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.OkOnly, "tip!")
Finally
strd1.Close()
End Try
End Sub
Private Sub export_csv(dgv As DataGridView, s1 As Stream)
Using sw1 As New StreamWriter(s1, 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)
sw1.WriteLine(columntitle)
For j As Integer = 0 To dgv.Rows.Count - 1
Dim columevalue As String = ""
For k As Integer = 0 To dgv.Columns.Count - 1
If k > 0 Then
columevalue += ","
End If
If dgv.Rows(j).Cells(k).Value Is Nothing Then
columevalue += ""
Else
Dim m As String = dgv.Rows(j).Cells(k).Value.ToString().Trim()
columevalue += m.Replace(",", ", ")
End If
Next
columevalue.Remove(columevalue.Length - 1)
sw1.WriteLine(columevalue)
Next
sw1.Close()
s1.Close()
Catch ex As Exception
Finally
sw1.Close()
s1.Close()
End Try
End Using
End Sub
Private Sub 清空数据ToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles 清空数据ToolStripMenuItem1.Click
DataGridView1.Rows.Clear()
End Sub
End Class