![](/img/trans.png)
[英]How to export data in datagridview into text file And Import it VB.net
[英]How to export data in a DataGridView to a text file in VB.NET
我想知道代码,如何将DataGridView1
的内容导出到 VB.NET 中的文本文件。 我正在使用Visual Studio 2019
。 该表将包含:
样本:
-------------------------------------------------------------------------------------
| Item Code | Item Name | Item Description | Price | In-Stock | Supplier |
-------------------------------------------------------------------------------------
|12345 |Cupboard |a small sized cupboard |Rs.15,000 |15 |ABC Industry |
-------------------------------------------------------------------------------------
|45689 |Chair |a small chair |Rs.10,000 |10 |ABC Industry |
-------------------------------------------------------------------------------------
and so on...
在文本文件中,上面的数据将存储为
12345|Cupboard|a small sized cupboard|15000|15|ABC Industry
45689|Chair|a small chair|10000|10|ABC Industry
and so on...
谢谢[香农]
尝试这个
Dim OPString As String=""
Dim SW As StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(filepath, True)
Dim grid as DatagridView = DataGridView1
'print col header names
For i = 1 To grid.Columns.Count
OPString = grid.Columns(i - 1).HeaderText & "|"
Next
SW.WriteLine(OPString)
OPString=""
'Clear the code above if you don't want headers to be added everytime
'print data
For i = 0 To grid.RowCount - 2
For j = 0 To grid.ColumnCount - 1
OPString = grid(j, i).Value & "|"
Next
Next
SW.WriteLine(OPString)
你可以试试这个代码:
Dim sw As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(filepath, True)
Dim str As String = String.Empty
For a As Integer = 0 To DataGridView1.RowCount - 1
str = String.Empty
For b As Integer = 0 To DataGridView1.ColumnCount - 1
str = str & DataGridView1.Rows(a).Cells(b).Value.ToString & "|"
Next
str = str.Substring(0, str.Length - 1)
sw.WriteLine(str)
Next
sw.Close()
假设DataGridView
的源中有一个DataTable
。 创建为StringBuilder
。 重建DataTable
。 遍历数据表中的行,将每一行转换为对象数组。 将对象数组更改为带有一点 Linq 的字符串数组。 使用管道连接字符串数组并将该行附加到字符串构建器。 循环完成后保存到文本文件。
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim sb As New StringBuilder
Dim dt = DirectCast(DataGridView1.DataSource, DataTable)
For Each row As DataRow In dt.Rows
Dim arr = row.ItemArray
Dim strArr = From element In arr
Select CStr(element)
Dim rowString = String.Join("|", strArr)
sb.AppendLine(rowString)
Next
File.WriteAllText("C:\Users\xxxx\Desktop\MyGrid.txt", sb.ToString)
MessageBox.Show("Finished")
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.