vb.net 在VB.net中将csv数据转换为DataTable
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11118678/
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
convert csv data to DataTable in VB.net
提问by Matt
I am trying to import a large array of integers stored as a csv file into a VB.Net DataTable called BeamMap
. The .csv file consists only of integers, with a delimiter of ,
, no quotes around the data (ie., 1,3,-2,44,1
), and an end of line character of line feed and carriage return. All I want to do is get each integer into a DataTable cell with the appropriate rows and columns (there are the same number of columns for each row) and be able to reference it later on in my code. I really don't want anything more than absolutely necessary in the code (no titles, captions, headings, etc.), and I need it to be fairly efficient (the csv array is approx. ~1000 x ~1000).
我正在尝试将存储为 csv 文件的大量整数导入到名为BeamMap
. .csv 文件仅由整数组成,分隔符为,
,数据周围没有引号(即1,3,-2,44,1
),以及换行和回车的行尾字符。我想要做的就是将每个整数放入具有适当行和列的 DataTable 单元格中(每行有相同的列数),并能够稍后在我的代码中引用它。我真的不想要代码中绝对必要的东西(没有标题、标题、标题等),我需要它相当高效(csv 数组大约为 ~1000 x ~1000)。
Thanks!
谢谢!
采纳答案by Tim Schmelter
Here's a simple approach which requires a strict format (as you've mentioned):
这是一种需要严格格式的简单方法(正如您所提到的):
Dim lines = IO.File.ReadAllLines(path)
Dim tbl = New DataTable
Dim colCount = lines.First.Split(","c).Length
For i As Int32 = 1 To colCount
tbl.Columns.Add(New DataColumn("Column_" & i, GetType(Int32)))
Next
For Each line In lines
Dim objFields = From field In line.Split(","c)
Select CType(Int32.Parse(field), Object)
Dim newRow = tbl.Rows.Add()
newRow.ItemArray = objFields.ToArray()
Next
回答by adatapost
Use OleDb
provider to read CSV and pouplate the DataTable
.
使用OleDb
provider 读取 CSV 并将DataTable
.
Dim folder = "c:\location\of\csv\files\"
Dim CnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & folder & ";Extended Properties=""text;HDR=No;FMT=Delimited"";"
Dim dt As New DataTable
Using Adp As New OleDbDataAdapter("select * from [nos.csv]", CnStr)
Adp.Fill(dt)
End Using
回答by johann
Getting the file from a mapped drive and putting the retrieved data in a dataset:
从映射驱动器获取文件并将检索到的数据放入数据集中:
Dim folder = "Z:\"
Dim CnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & folder & ";Extended Properties=""text;HDR=No;FMT=Delimited"";"
Dim dssample As New DataSet
Using Adp As New OleDbDataAdapter("select * from [samplecsv.csv]", CnStr)
Adp.Fill(dssample)
End Using
If dssample.Tables.Count > 0 Then
'some code here
End If
回答by Daniel Bonetti
Also, don't forget to include the
另外,不要忘记包括
Imports System.Data.OleDb
And if you wish to link to a DataGridView (after read):
如果您希望链接到 DataGridView(阅读后):
Dim bs As New BindingSource
bs.DataSource = dt
DataGridView1.DataSource = bs