如何将CSV文本文件内容存入ArrayList并分配给独立变量?
处理逗号分隔TXT文件:分配字段到变量并存储到ArrayList
需求说明
你有一个逗号分隔的TXT文件,示例行如下:
706202212011417.G001,1024,20221201,172300,3600,35479,....
需要实现:
- 将每个逗号分隔的字段存入
ArrayList - 将第一个字段赋值给
A1变量,并用MessageBox显示格式为"A1 is ******.***"的内容 - 现有代码已能拆分字段,但无法将数组项分配给独立变量
修改后的代码实现
首先确保导入System.Collections命名空间(用于使用ArrayList):
Imports System.Collections
修改原代码,加入变量赋值和ArrayList存储逻辑:
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\TestFolder\test.txt") MyReader.TextFieldType = FileIO.FieldType.Delimited MyReader.SetDelimiters(",") Dim currentRow As String() ' 初始化ArrayList用于存储当前行的所有字段 Dim fieldList As New ArrayList() While Not MyReader.EndOfData Try currentRow = MyReader.ReadFields() ' 清空列表,准备存储当前行字段 fieldList.Clear() ' 将当前行所有字段添加到ArrayList For Each currentField In currentRow fieldList.Add(currentField) Next ' 从ArrayList提取第一个字段赋值给A1 Dim A1 As String = fieldList(0).ToString() ' 弹窗显示指定格式内容 MsgBox($"A1 is {A1}") ' 如需提取其他字段,直接按索引获取即可 ' Dim A2 As String = fieldList(1).ToString() ' Dim A3 As String = fieldList(2).ToString() Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException MsgBox($"Line {ex.Message} is not valid and will be skipped.") End Try End While End Using
简化方案(无需ArrayList)
如果仅需要将字段分配给独立变量,不需要存储到ArrayList,可以直接从currentRow数组中按索引提取:
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\TestFolder\test.txt") MyReader.TextFieldType = FileIO.FieldType.Delimited MyReader.SetDelimiters(",") Dim currentRow As String() While Not MyReader.EndOfData Try currentRow = MyReader.ReadFields() ' 直接从数组提取字段赋值给变量 Dim A1 As String = currentRow(0) MsgBox($"A1 is {A1}") ' 其他字段同理 ' Dim A2 As String = currentRow(1) ' Dim A3 As String = currentRow(2) Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException MsgBox($"Line {ex.Message} is not valid and will be skipped.") End Try End While End Using
关键说明
currentRow是String()类型数组,每个元素对应一行中的一个逗号分隔字段,通过索引(从0开始)即可访问指定字段ArrayList适合需要动态存储或操作字段集合的场景,若仅需提取固定位置的字段,直接使用数组更高效- 使用字符串插值
$"A1 is {A1}"可以简洁地格式化输出内容
内容的提问来源于stack exchange,提问作者Nate
相关产品推荐
相关产品推荐

