c# - 添加一种在 CSV 中将逗号保留到 DataTable 函数的方法

标签 c# asp.net vb.net

我有一个将 .csv 文件转换为数据表的函数。我正在转换的列之一是其中有一个逗号的名称字段,即“Doe, John”在转换函数时将其视为 2 个单独的字段,因为逗号。我需要数据表将其保存为数据表中的一个字段 Doe、John。

Function CSV2DataTable(ByVal filename As String, ByVal sepChar As String) As DataTable
    Dim reader As System.IO.StreamReader
    Dim table As New DataTable
    Dim colAdded As Boolean = False

    Try
        ''# open a reader for the input file, and read line by line
        reader = New System.IO.StreamReader(filename)
        Do While reader.Peek() >= 0
            ''# read a line and split it into tokens, divided by the specified 
            ''# separators
            Dim tokens As String() = System.Text.RegularExpressions.Regex.Split _
                (reader.ReadLine(), sepChar)
            ''# add the columns if this is the first line
            If Not colAdded Then
                For Each token As String In tokens
                    table.Columns.Add(token)
                Next
                colAdded = True
            Else
                ''# create a new empty row
                Dim row As DataRow = table.NewRow()
                ''# fill the new row with the token extracted from the current 
                ''# line
                For i As Integer = 0 To table.Columns.Count - 1
                    row(i) = tokens(i)
                Next
                ''# add the row to the DataTable
                table.Rows.Add(row)
            End If
        Loop

        Return table
    Finally
        If Not reader Is Nothing Then reader.Close()
    End Try
End Function

最佳答案

不要使用 .Split() 函数来读取您的 csv 数据。它不仅会导致您刚刚遇到的那种错误,而且速度也会变慢。您需要一个基于状态机 的解析器。这样会更快,并且更容易正确处理引号括起的文本。

我这里有一个例子:
Reading CSV files in C#

您还可以使用 codeplex 上备受推崇的 CSV 阅读器:
http://www.codeproject.com/KB/database/CsvReader.aspx


你会像这样使用我的代码:

Function DataTableFromCSV(ByVal filename As String) As DataTable
    Dim table As New DataTable
    Dim colAdded As Boolean = False

    For Each record As IList(Of String) In CSV.FromFile(filename)
        ''# Add column headers on first iteration
        If Not colAdded Then
            For Each token As String In record
                table.Columns.Add(token)
            Next token
            colAdded = True
        Else
            ''# add the row to the table
            Dim row As DataRow = table.NewRow()
            For i As Integer = 0 To table.Columns.Count - 1
                row(i) = record(i)
            Next
            table.Rows.Add(row)
        End If
    Next record

    Return table
End Function  

如果您使用的是 .net 3.5 或更高版本,我会稍微不同地编写它以将列创建从 for each 循环中拉出来(使用类型推断和 .Take(1) ),但我想确保这也适用于 .Net 2.0。

关于c# - 添加一种在 CSV 中将逗号保留到 DataTable 函数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2852330/

相关文章:

c# - 以编程方式创建 Oracle 数据库和架构 ADO.NET

c# - 将 DefaultIfEmpty 与对象一起使用?

asp.net - 报表服务器凭据和丢失端点异常

database - 在 vb.net 中正确处理空数据库值

vb.net - 如何避免在 Windows 应用程序的文本框中使用特殊字符

C# 在DataRow中插入ArrayList

javascript - Kendo Grid 中的日期字段在 Controller 上为空

c# - 动态表单上的 MVC 模型验证?

asp.net - 从 Sql Server 2008 在 TreeView 中添加父节点和子节点

vb.net - 如何增加 DataGridView 列标题工具提示的显示时间?