CSV到DataTable

时间:2018-04-10 14:10:12

标签: vb.net datatable

我想知道将CSV解析为DataTable的最佳选择是什么。

我的CSV格式为

分隔符:逗号
分隔符:双引号(例如"字符串")
逃脱:2倍双引号

以下是示例:

Col1,Col2,Col3,Col4
1234,active,"This is a long text with new lines, commas and all", XGF232
1235,active,"This is also a ""long"" text with new lines and all", XHD233
  1. 问题是数字还是短暂的;一个单词字符串不包含在引号内。
  2. 另一个问题是长引号括在引号内的字符串也有"字符串"嵌套用""字符串""进行转义。
  3. PS:Excel理解这种格式没有问题。

    编辑:

    评论指出我有不同的选择。我搜索了可用的库,我找到了LumenWorks.Framework.IO.Csv,它似乎完美地完成了这项工作。

    Using csv As CsvReader = New CsvReader(New StreamReader(filename), True)
                    Dim fieldCount = csv.FieldCount
                    Dim headers() As String = csv.GetFieldHeaders()
                    dt.Load(csv)
    End Using
    

1 个答案:

答案 0 :(得分:0)

您可以从DGV导入Excel吗?

Imports System.Data.SqlClient
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim MyConnection As System.Data.OleDb.OleDbConnection
        Dim DtSet As System.Data.DataSet
        Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
        MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\vb.net-informations.xls';Extended Properties=Excel 8.0;")
        MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
        MyCommand.TableMappings.Add("Table", "Net-informations.com")
        DtSet = New System.Data.DataSet
        MyCommand.Fill(DtSet)
        DataGridView1.DataSource = DtSet.Tables(0)
        MyConnection.Close()

    End Sub
End Class