![](/img/trans.png)
[英]How to export data in a DataGridView to a text file in VB.NET
[英]How to export data in datagridview into text file And Import it VB.net
如何将 datagridview 中的数据导出到文本文件并导入 VB.net 我试图解决这个问题:
Using writer As New System.IO.StreamWriter("G:\Visual Studio 2010\b.txt")
For row As Integer = 0 To DataGridView1.Rows.Count - 1
For col As Integer = 0 To DataGridView1.ColumnCount - 1
IO.File.WriteAllText("G:\Visual Studio 2010\C.txt", DataGridView1.Rows(row).Cells(col).Value.ToString & ",")
Next
Next
End Using
这是最后一个代码。我写了其他代码。但都失败了。我尝试将数据导出到 xml 并导入。 [失败] 请编写正确的代码+解决导入问题
以下是我使用的代码。 它是制表符分隔的,但您可以将其更改为您想要的方式。
#Region "*** 文件加载和保存 (DataGridView)***"
Sub ReadTSV()
Dim TextLine As String
Dim SplitLine() As String
If System.IO.File.Exists(DataPath & "\Tracker.tsv") = True Then
Dim objReader As New System.IO.StreamReader(DataPath & "\Tracker.tsv", System.Text.Encoding.Default)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ControlChars.Tab)
Me.dgvTracker.Rows.Add(SplitLine)
Loop
objReader.Close()
Else
'MsgBox("File Does Not Exist")
End If
End Sub
Public Sub WriteDataGridViewTSV()
'Build the TSV file data as a Tab separated string.
Dim tsv As String = String.Empty
'Adding the Rows
For Each row As DataGridViewRow In dgvTracker.Rows
For Each cell As DataGridViewCell In row.Cells
tsv = tsv & CType(cell.Value, String) & ControlChars.Tab 'Add the Data rows
Next
'trim the last Tab and Add new line
tsv = tsv.TrimEnd(ControlChars.Tab) & vbCrLf
Next
If tsv.Length > 4 Then 'Remove the extra lines at the end of the tsv file
tsv = tsv.Substring(0, tsv.Length - 4)
Else
tsv = "" 'Delete extra row if empty
End If
File.WriteAllText(DataPath & "\Tracker.tsv", tsv)
End Sub
此代码显示了 jmcilhinney 的注释示例。
在 Form.Load 中,我检查了 xml 和 xsd 文件是否存在。 然后他们会被读取并用模式和数据填充DataTable
。 如果它们不存在,则会创建一个新的DataTable
。 最后将DataTable
绑定到DataGridView
。
用户在DataGridView
中添加或更改的任何数据都记录在DataTable
。 保存数据和模式同样简单。 只需从网格中提取DataTable
并写入模式和数据。
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt As DataTable
If File.Exists("test.xml") AndAlso File.Exists("test.xsd") Then
dt = New DataTable
dt.ReadXmlSchema("test.xsd")
dt.ReadXml("test.xml")
MessageBox.Show(dt.Rows.Count.ToString)
Else
dt = CreateDataTable()
End If
DataGridView1.DataSource = dt
End Sub
Private Function CreateDataTable() As DataTable
Dim dt As New DataTable("MyDataTable")
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))
dt.Columns.Add("Rank", GetType(Integer))
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Pretend this is the Save button
Dim dt = DirectCast(DataGridView1.DataSource, DataTable)
dt.WriteXmlSchema("test.xsd")
dt.WriteXml("test.xml")
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.