VB.net | 将数据从 DataGridView 保存到文本文件(每行一行)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37855611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:57:13  来源:igfitidea点击:

VB.net | Save data from DataGridView to text file (Line per line)

vb.netdatagridviewtext-files

提问by Ruan

The application I designed so far has a DataGridView which loads data from a text file line per line.

到目前为止,我设计的应用程序有一个 DataGridView,它从每行的文本文件行加载数据。

All I want is for the code to save the (first row, first column) on the first line as a string, then (first row, second column) on the second line, etc.

我想要的只是代码将第一行上的(第一行,第一列)保存为字符串,然后(第一行,第二列)保存在第二行上,依此类推。

Here is an example of what my table looks like:

这是我的表的示例:

|-------------------------------------------------------|
|  ID  |  Date  |  Height  |  Weight  |  BMI  |  Units  |
|-------------------------------------------------------|
|  01  | 16/06  |   1.74   |    64    | 20.9  | Metric  |
|  02  | 17/06  |   1.74   |    63    | 20.6  | Metric  |
|-------------------------------------------------------|

So from this example, after the data has been saved to the text file it should look exactly like this:

所以从这个例子来看,在数据被保存到文本文件之后,它应该看起来像这样:

01
16/06
1.74
64
20.9
Metric
02
17/06
1.74
63
20.6
Metric

I came across some excellent code which does this with tabs, instead of a next line, here it is:

我遇到了一些出色的代码,它使用选项卡来完成此操作,而不是下一行,它是:

dgvMeasures.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText
dgvMeasures.SelectAll()
IO.File.WriteAllText(fileName, dgvMeasures.GetClipboardContent.GetText.TrimEnd)
dgvMeasures.ClearSelection()

NOTE: The DataGridView is called dgvMeasures

注意:DataGridView 称为 dgvMeasures

Also please note that I cannot provide anything that I have already tried since there is nothing I can do, I have no idea what to do.

另请注意,我无法提供任何我已经尝试过的东西,因为我无能为力,我不知道该怎么做。

So if there is anyone who could help, it would be greatly appreciated

因此,如果有人可以提供帮助,将不胜感激

采纳答案by Sastreen

To do this, you just need to use a writer, and go through it in the way you want.

为此,您只需要使用编写器,并按照您想要的方式完成它。

Using writer As New System.IO.StreamWriter(filePath)
    For row As Integer = 0 To dgvMeasures.RowCount - 1
        For col As Integer = 0 To dgvMeasures.ColumnCount - 1
            writer.WriteLine(dgvMeasures.Rows(row).Cells(col).Value.ToString)
        Next
    Next
End Using

This will go through each column for each row (as you describe), and then go to the next row.

这将遍历每一行的每一列(如您所述),然后转到下一行。

I am sure you have a reason for writing the text file like this, but if you want to read it back in at some point, I would really recommend using a tab-delimited (or similar) format.

我相信您有理由像这样编写文本文件,但是如果您想在某个时候重新阅读它,我真的建议您使用制表符分隔(或类似)格式。