gpt4 book ai didi

vb.net - 在 VB.net 中将 csv 数据转换为 DataTable,从第 0 行捕获列名

转载 作者:行者123 更新时间:2023-12-02 08:28:03 26 4
gpt4 key购买 nike

我改编了@tim-schmelter 对问题 convert csv data to DataTable in VB.net 的回答中的代码(见下文)

我想在 csv 文件第 0 行的列标题中解析

DT|Meter Number|Customer Account Number|Serial Number|Port...

但我没有任何运气试图弄清楚如何做到这一点。任何建议将不胜感激。

Public Function csvToDatatable_2(ByVal filename As String, ByVal separator As String)
'////////////////////////////////////////
'Reads a selected txt or csv file into a datatable
'based on code from http://stackoverflow.com/questions/11118678/convert-csv-data-to-datatable-in-vb-net
'////////////////////////////////////////
Dim dt As System.Data.DataTable

Try
dt = New System.Data.DataTable
Dim lines = IO.File.ReadAllLines(filename)
Dim colCount = lines.First.Split(separator).Length

For i As Int32 = 1 To colCount
dt.Columns.Add(New DataColumn("Column_" & i, GetType(String)))
Next

For Each line In lines
Dim objFields = From field In line.Split(separator)
Dim newRow = dt.Rows.Add()
newRow.ItemArray = objFields.ToArray()
Next

Catch ex As Exception
Main.Msg2User(ex.Message.ToString)
Return Nothing

End Try

Return dt

End Function

最佳答案

只需遍历文件的所有行。使用 bool 值检查第一行。

Public Function csvToDatatable_2(ByVal filename As String, ByVal separator As String)
Dim dt As New System.Data.DataTable
Dim firstLine As Boolean = True
If IO.File.Exists(filename) Then
Using sr As New StreamReader(filename)
While Not sr.EndOfStream
If firstLine Then
firstLine = False
Dim cols = sr.ReadLine.Split(separator)
For Each col In cols
dt.Columns.Add(New DataColumn(col, GetType(String)))
Next
Else
Dim data() As String = sr.Readline.Split(separator)
dt.Rows.Add(data.ToArray)
End If
End While
End Using
End If
Return dt
End Function

关于vb.net - 在 VB.net 中将 csv 数据转换为 DataTable,从第 0 行捕获列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30201592/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com